XLog

repository·master·Indexed 25 days ago

https://github.com/elvishew/xlog

A lightweight, powerful, and flexible logging library for Android and Java. XLog supports printing logs to Logcat, the console, files, or custom destinations via a plugin-like Printer system. It features structured data formatting for JSON, XML, Collections, Maps, Intents, and Bundles, as well as advanced configuration for log rotation, cleanup strategies, and bytecode-level interception of third-party logs via LibCat.

Tokens
6.6K
Snippets
18
Records
36
Agent score
85%

What's inside XLog

  1. Save logs to a file using FilePrinter

    master

    To persist logs to a file, create a FilePrinter using its Builder and add it during initialization or when creating a Logger.

    Key configuration options for FilePrinter.Builder():

    • Builder(String path): Specify the full path to the log directory.
    • fileNameGenerator(FileNameGenerator): Specify how filenames are generated. Defaults to ChangelessFileNameGenerator("log").
    • backupStrategy(BackupStrategy): Specify the backup policy. Defaults to FileSizeBackupStrategy(1024 * 1024).
    • cleanStrategy(CleanStrategy): Specify the log cleanup policy. Defaults to NeverCleanStrategy().
    • flattener(Flattener): Specify how log elements are flattened into a string. Defaults to DefaultFlattener.
    Printer filePrinter = new FilePrinter                      // 打印日志到文件的打印器
        .Builder("<日志目录全路径>")                             // 指定保存日志文件的路径
        .fileNameGenerator(new DateFileNameGenerator())        // 指定日志文件名生成器,默认为 ChangelessFileNameGenerator("log")
        .backupStrategy(new NeverBackupStrategy())             // 指定日志文件备份策略,默认为 FileSizeBackupStrategy(1024 * 1024)
        .cleanStrategy(new FileLastModifiedCleanStrategy(MAX_TIME))     // 指定日志文件清除策略,默认为 NeverCleanStrategy()
        .flattener(new MyFlattener())                          // 指定日志平铺器,默认为 DefaultFlattener
        .build();
    
    // Option 1: Global initialization
    XLog.init(config, filePrinter);
    
    // Option 2: Non-global Logger
    Logger logger = XLog.printer(filePrinter).build();
    
    // Option 3: One-time print
    XLog.printer(filePrinter).d("用一次性配置打印的消息");
  2. Quick Start with XLog

    master

    To quickly initialize XLog with default settings and print a message, use XLog.init() followed by a logging method.

    Available log levels are v (VERBOSE), d (DEBUG), i (INFO), w (WARNING), and e (ERROR).

    XLog.init(LogLevel.ALL);
    XLog.d("你好 xlog");
  3. Save third party logs via LibCat

    master

    You can capture and save logs from third-party libraries within your application by configuring LibCat after initializing XLog. This redirects third-party logs to your configured FilePrinter.

    LibCat.config(true, filePrinter);
  4. Configure automatic log backup and cleanup

    master

    Automatic Backup

    Use BackupStrategy to prevent log files from growing indefinitely. When a condition is met, a new log file is created and the old one is renamed with a .bak.n suffix.

    • FileSizeBackupStrategy: Triggers backup when the file reaches a certain size.
    • FileSizeBackupStrategy2: Allows for multiple backup files to exist simultaneously (the default FileSizeBackupStrategy only keeps one backup).

    Automatic Cleanup

    To prevent disk space exhaustion, use a CleanStrategy to delete old logs.

    • FileLastModifiedCleanStrategy: Automatically deletes log files that haven't been modified for a specified period (e.g., one week).
  5. Install LibCat via Gradle

    master

    LibCat requires the android-aspectjx plugin to intercept android.util.Log calls at the bytecode level. Configure your build.gradle as follows:

    1. Apply the android-aspectjx plugin.
    2. Set sourceCompatibility and targetCompatibility to JavaVersion.VERSION_1_8.
    3. Add the aspectjx classpath to your buildscript dependencies.
    4. Configure the aspectjx block. If using Kotlin, you must exclude 'kotlin' to avoid zip file is empty build errors. You can also use exclude or include to specify packages/classes for interception.
    5. Add com.elvishew:xlog-libcat:1.0.0 to your dependencies.
    apply plugin: 'android-aspectjx'
    
    android {
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    
    buildscript {
        repositories {
            jcenter()
            google()
        }
        dependencies {
            classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10'
        }
    }
    
    aspectjx {
        // if you use kotlin in your project make sure to exclude `kotlin`,
        // otherwise a build error `zip file is empty` will be thrown
        exclude 'kotlin'
    
        // add 'exclude' packages/classes that you don't want to intercept the logs from
        exclude 'androidx.appcompat'
        exclude 'android.support'
    
        // or add 'include' packages/classes that you want to intercept the logs from
    }
    
    dependencies {
        implementation 'com.elvishew:xlog-libcat:1.0.0'
    }
  6. Setup LibCat using AspectJX

    master

    LibCat requires the android-aspectjx plugin to intercept android.util.Log calls during the compilation phase. During compilation, AspectJ removes calls to android.util.Log and replaces them with LibCat logic.

    Important Notes:

    • If your project uses Kotlin, ensure you exclude 'kotlin' in the aspectjx configuration to avoid 'zip file is empty' errors.
    • You can use exclude to specify packages/classes you do NOT want to intercept (e.g., androidx.appcompat, android.support).
    • Alternatively, you can use include to specify only the packages/classes you want to intercept.
    apply plugin: 'android-aspectjx'
    
    android {
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    
    buildscript {
        repositories {
            jcenter()
            google()
        }
        dependencies {
            classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10'
        }
    }
    
    aspectjx {
        // If using Kotlin, exclude it to prevent 'zip file is empty' error
        exclude 'kotlin'
    
        // Add packages/classes you don't want to intercept
        exclude 'androidx.appcompat'
        exclude 'android.support'
    
        // OR: Add 'include' for specific packages/classes you want to intercept
    }
    
    dependencies {
        implementation 'com.elvishew:xlog-libcat:1.0.0'
    }
  7. Save third-party library logs to a file

    master

    You can redirect logs from third-party libraries/modules within the same app to your FilePrinter by configuring LibCat after XLog has been initialized.

    LibCat.config(true, filePrinter);
  8. Migrate from Android Log to XLog

    master

    XLog provides a compatibility API that mimics android.util.Log. You can replace android.util.Log with com.elvishew.xlog.XLog.Log to maintain existing code structure.

    Note: For better performance, it is recommended to use XLog directly rather than the compatibility API.

    Automated Migration (Linux/Cygwin)

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

    Automated Migration (Mac)

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

    master

    Use FilePrinter.Builder to save logs to a file with custom strategies:

    • .Builder(String path): Specify the directory path.
    • .fileNameGenerator(Generator): Custom file name generation (default: ChangelessFileNameGenerator("log")).
    • .backupStrategy(Strategy): Strategy for file rotation (default: FileSizeBackupStrategy(1024 * 1024)).
    • .cleanStrategy(Strategy): Strategy for cleaning old logs (default: NeverCleanStrategy()).
    • .flattener(Flattener): Custom flattener (default: DefaultFlattener).
    • .writer(Writer): Custom writer (default: SimpleWriter).
    Printer filePrinter = new FilePrinter.Builder("<path-to-logs-dir>")
        .fileNameGenerator(new DateFileNameGenerator())
        .backupStrategy(new NeverBackupStrategy())
        .cleanStrategy(new FileLastModifiedCleanStrategy(MAX_TIME))
        .flattener(new MyFlattener())
        .writer(new MyWriter())
        .build();