xLog


Source link: https://github.com/elvishew/xLog

XLog

????

Simple and pretty, powerful and flexible logger for android and java, can concurrently print the log to multiple target like Logcat, Console and File, or even Server(or anywhere) if you like.

What XLog can do:

  • Global config(tag, formatters...) or log-based config
  • Support printing any object and customizable object formatter
  • Support printing array
  • Support printing long log (No 4K limitation)
  • XML and JSON formatted
  • Thread information (Thread name etc. Can be customized)
  • Stack trace information (Configurable call stack depth, with file name, method name, line number)
  • Support log interceptors
  • Save logs in file (Configurable file naming and backup strategy)
  • Good looking in Android Studio
  • Easy to use, powerful in customization

The differences to other logger libraries:

  • Pretty source code and document
  • So flexible that you can easily customize or enhance it
  • Lightweight, no other dependencies

Dependency

compile 'com.elvishew:xlog:1.4.0'

Preview

  • Log with thread information, stack trace information and border

* Formatted network API request

* Formatted network API response

* Log files

Architecture

Usage

Initialization

Simple way

XLog.init(LogLevel.ALL);

Or if you want to disable the log in release version

XLog.init(BuildConfig.DEBUG ? LogLevel.ALL : LogLevel.NONE);
 

Advance way

LogConfiguration config = new LogConfiguration.Builder()
  .logLevel(BuildConfig.DEBUG ? LogLevel.ALL

 // Specify log level, logs below this level won't be printed, default: LogLevel.ALL

: LogLevel.NONE)
  .tag("MY_TAG")

  // Specify TAG, default: "X-LOG"
  .t()

// Enable thread info, disabled by default
  .st(2)

 // Enable stack trace info with depth 2, disabled by default
  .b()

// Enable border, disabled by default
  .jsonFormatter(new MyJsonFormatter())

// Default: DefaultJsonFormatter
  .xmlFormatter(new MyXmlFormatter())

  // Default: DefaultXmlFormatter
  .throwableFormatter(new MyThrowableFormatter())

  // Default: DefaultThrowableFormatter
  .threadFormatter(new MyThreadFormatter())

  // Default: DefaultThreadFormatter
  .stackTraceFormatter(new MyStackTraceFormatter())

// Default: DefaultStackTraceFormatter
  .borderFormatter(new MyBoardFormatter())

// Default: DefaultBorderFormatter
  .addObjectFormatter(AnyClass.class,

  // Add formatter for specific class of object

new AnyClassObjectFormatter())

// Use Object.toString() by default
  .addInterceptor(new BlacklistTagsFilterInterceptor(
 // Add blacklist tags filter

"blacklist1", "blacklist2", "blacklist3"))
  .addInterceptor(new MyInterceptor())

 // Add a log interceptor
  .build();
  Printer androidPrinter = new AndroidPrinter();

 // Printer that print the log using android.util.Log Printer consolePrinter = new ConsolePrinter();

 // Printer that print the log to console using System.out Printer filePrinter = new FilePrinter

 // Printer that print the log to the file system
  .Builder("/sdcard/xlog/")

// Specify the path to save log file
  .fileNameGenerator(new DateFileNameGenerator())

  // Default: ChangelessFileNameGenerator("log")
  .backupStrategy(new NeverBackupStrategy())

 // Default: FileSizeBackupStrategy(1024 * 1024)
  .logFlattener(new MyFlattener())

  // Default: DefaultFlattener
  .build();
  XLog.init(

 // Initialize XLog
  config,

// Specify the log configuration, if not specified, will use new LogConfiguration.Builder().build()
  androidPrinter,

 // Specify printers, if no printer is specified, AndroidPrinter(for Android)/ConsolePrinter(for java) will be used.
  consolePrinter,
  filePrinter);

For android, a best place to do the initialization is Application.onCreate().

Global Usage

XLog.d("Simple message") XLog.d("My name is %s", "Elvis");
 XLog.d("An exception caught", exception);
 XLog.d(object);
 XLog.d(array);
 XLog.json(unformattedJsonString);
 XLog.xml(unformattedXmlString);
 ... // Other global usage

Partial usage

Build a logger.

Logger partial = XLog.tag("PARTIAL-LOG")
  ... // Other configs
  .build();

And use it partially, the logging methods is completely the same as that ones in XLog.

partial.d("Simple message 1");
 partial.d("Simple message 2");
 ... // Other partial usage

Log-based usage

Setup log-based configs and log immediately, the logging methods is completely the same as that ones in XLog.

XLog.t()
 // Enable thread into
  .st(3)  // Enable stack trace info with depth 3
  .b()
 // Enable border
  ...
  // Other configs
  .d("Simple message 1");
  XLog.tag("TEMP-TAG")
  .st(0)  // Enable stack trace info without limitation
  ...
  // Other configs
  .d("Simple message 2");
  XLog.nt()
// Disable thread info
  .nst()  // Disable stack trace info
  .d("Simple message 3");
  XLog.b().d("Simple message 4");
 

Comparison

Let's imagine there are a JSON string and a XML string

String jsonString = "{
\"name\": \"Elvis\", \"age\": 18
}
"; String xmlString = "<team><member name="Elvis"/><member name="Leon"/></team>";

Android Log

Log.d(TAG, "Message");
 Log.d(TAG, String.format("Message with argument: age=%s", 18));
 Log.d(TAG, jsonString);
 Log.d(TAG, xmlString);
 Log.d(TAG, "Message with stack trace info", new Throwable());

XLog

XLog.init(LogLevel.ALL);
 XLog.d("Message");
 XLog.d("Message with argument: age=%s", 18);
 XLog.json(jsonString);
 XLog.xml(xmlString);
 XLog.st(5).d("Message with stack trace info");

XLog with border

XLog.init(LogLevel.ALL, new LogConfiguration.Builder().b().build());
 XLog.d("Message");
 XLog.d("Message with argument: age=%s", 18);
 XLog.json(jsonString);
 XLog.xml(xmlString);
 XLog.st(5).d("Message with stack trace info");

Similar libraries

Compatibility

In order to be compatible with Android Log, all the methods of Android Log are supported here.
See the Log class defined in XLog.

Log.v(String, String);
 Log.v(String, String, Throwable);
 Log.d(String, String);
 Log.d(String, String, Throwable);
 Log.i(String, String);
 Log.i(String, String, Throwable);
 Log.w(String, String);
 Log.w(String, String, Throwable);
 Log.wtf(String, String);
 Log.wtf(String, String, Throwable);
 Log.e(String, String);
 Log.e(String, String, Throwable);
 Log.println(int, String, String);
 Log.isLoggable(String, int);
 Log.getStackTraceString(Throwable);

Migration

If you have a big project using the Android Log, and it is a hard work to change all usage of Android Log to XLog, then you can use the compatible API, simply replace all 'android.util.Log' to 'com.elvishew.xlog.XLog.Log'.
( For a better performance, you should think about not using the compatible API.)

Linux/Cygwin:

grep -rl "android.util.Log" <your-source-directory> | xargs sed -i "s/android.util.Log/com.elvishew.xlog.XLog.Log/g"

Mac

grep -rl "android.util.Log" <your-source-directory> | xargs sed -i "" "s/android.util.Log/com.elvishew.xlog.XLog.Log/g"

Android Studio

In 'Project' pane, switch to the 'Project Files' tab, then right-click on the your source directory.
In the menu, click the 'Replace in Path...' option.
In the dialog, fill the 'Text to find' with 'android.util.Log', and 'Replace with' with 'com.elvishew.xlog.XLog.Log', and click 'Find'.

TODO

  • Print any object: XLog.d(Object) (since 1.1.0)
  • Support log interceptors(similar to okhttp's Interceptor, here we use it for intercepting log) (since 1.3.0)
  • Add tags filter (blacklist filter and whitelist filter) (since 1.3.0)
  • Add PatternFlattener(mostly used when logging to file), e.g: use pattern "{ d yyyy-MM-dd hh:mm:ss.SSS } { l } /{ t } : { m } " and the flattened log would be "2016-10-30 13:00:00,000 W/my_tag: Simple message" (since 1.3.0)
  • Log to file asynchronously (since 1.3.0)
  • Logger-based log level control rather than current global one (since 1.3.0)
  • Add builtin formatter for Bundle and Intent object (since 1.4.0)
  • Export log files to a .zip (since 1.4.0)

Releases

Latest release: 1.3.0 Change log

Issues

If you meet any problem when using XLog, or have any suggestion, please feel free to create an issue.

Thanks

Thanks to Orhan Obut's logger, it give me many ideas of what a logger can do.

Thanks to Serge Zaitsev's log, it give me the thought of making XLog compatible with Android Log.

License

Copyright 2016 Elvis Hew  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

Python script to highlight adb logcat output in console.

The HttpResponseCache library provides transparent and automatic caching of HTTP and HTTPS requests that use the java.net.HttpUrlConnection classes.

For information on how to use HttpUrlConnection, refer to the Android documentation - don't worry, the information also applies to non-Android Java.

Smooth activity switch animation.

PoppyView is a library which implements view on the bottom which come and go relative to the user scroll.

Just add the library to your application as a library project. And don't forget that your project must use NineOldAndroids.

A small library replicating the new dialogs in Android L.

Just as there was Retroweaver et al. for running Java 5 code with generics on Java 1.4, Retrolambda lets you run Java 8 code with lambda expressions on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime. After the transformation they are just a bunch of normal .class files, without adding any runtime dependencies.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes