安卓 log日誌架構

來源:互聯網
上載者:User

標籤:格式化   priority   null   setname   path   code   conf   dep   evel   

◆elvishew/xLog

 

架構特性介紹

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

xLog支援數組、object、XML、JSON等資料格式列印,支援Log儲存本地,支援log層級控制。及格式化列印配置。

代碼部分

整合到項目:

S1.添加依賴 compile ‘com.elvishew:xlog:1.4.0‘或匯入library源碼庫;

S2.初始化log;

S3.調用log;

 

API

初始化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.LogPrinter consolePrinter = new ConsolePrinter();             // Printer that print the log to console using System.outPrinter 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);log列印: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);

參考:

    https://github.com/elvishew/xLog

◆orhanobut/logger

 

架構特性介紹

Simple, pretty and powerful logger for android

支援基本資料列印、對象列印、XML/JSON列印、格式化列印,最新版本已移除LOG層級控制。

代碼部分

整合到項目:

S1.添加依賴 compile ‘com.orhanobut:logger:2.1.1‘或匯入library源碼庫;

S2.初始化logger;

S3.調用logger;

 

API

初始化FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()  .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true  .methodCount(0)         // (Optional) How many method line to show. Default 2  .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5  .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat  .tag("My custom tag")   // (Optional) Global tag for every log. Default PRETTY_LOGGER  .build();Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));Logger.addLogAdapter(new AndroidLogAdapter() {  @Override public boolean isLoggable(int priority, String tag) {    return BuildConfig.DEBUG;  }});FormatStrategy formatStrategy = CsvFormatStrategy.newBuilder()  .tag("custom")  .build();  Logger.addLogAdapter(new DiskLogAdapter(formatStrategy));log列印:Logger.d("debug");Logger.e("error");Logger.w("warning");Logger.v("verbose");Logger.i("information");Logger.wtf("wtf!!!!");Logger.d("hello %s", "world");Logger.d(MAP);Logger.d(SET);Logger.d(LIST);Logger.d(ARRAY);Logger.json(JSON_CONTENT);Logger.xml(XML_CONTENT);

參考:

    https://github.com/orhanobut/logger

 

pengwei1024/LogUtils

 

架構特性介紹

支援直接列印資料集合,如List、Set、Map、數組等

全域配置log輸出

個人化Tag

準確顯示調用方法、行,快速定位所在檔案位置

支援android系統對象Intent、Bundle列印

提供release-no-op版本

支援日誌寫入檔案

代碼部分

整合到項目:

S1.匯入library源碼庫;

    compile ‘com.apkfuns.logutils:library:1.5.1.1‘

    compile files(‘libs/okio-1.13.0.jar‘)

S2.初始化logutils;

S3.調用log方法;

API:

初始化LogUtils.getLogConfig()                .configAllowLog(true)                .configTagPrefix("MyAppName")                .configShowBorders(true)                .configFormatTag("%d{HH:mm:ss:SSS} %t %c{-5}")# 支援寫入日誌到檔案 LogUtils.getLog2FileConfig().configLog2FileEnable(true)                // targetSdkVersion >= 23 需要確保有寫sdcard許可權                .configLog2FilePath("/sdcard/專案檔夾/logs/")                .configLog2FileNameFormat("%d{yyyyMMdd}.txt")                 .configLogFileEngine(new LogFileEngineFactory());   log列印:// 輸出字串LogUtils.d("12345");// 輸出參數LogUtils.d("12%s3%d45", "a", 0);// 輸出異常LogUtils.d(new NullPointerException("12345"));// 輸出對象Person person = new Person();person.setAge(11);person.setName("pengwei");person.setScore(37.5f);LogUtils.d(person);// 對象為空白LogUtils.d(null);// 輸出json(json預設debug列印)String json = "{‘a‘:‘b‘,‘c‘:{‘aa‘:234,‘dd‘:{‘az‘:12}}}";LogUtils.json(json);// 列印資料集合List<Person> list1 = new ArrayList<>();for(int i = 0; i < 4; i++){    list1.add(person);}LogUtils.d(list1);// 列印數組double[][] doubles = {{1.2, 1.6, 1.7, 30, 33},                {1.2, 1.6, 1.7, 30, 33},                {1.2, 1.6, 1.7, 30, 33},                {1.2, 1.6, 1.7, 30, 33}};LogUtils.d(doubles);// 自訂tagLogUtils.tag("我是自訂tag").d("我是列印內容");// 其他用法LogUtils.v("12345");LogUtils.i("12345");LogUtils.w("12345");LogUtils.e("12345");LogUtils.wtf("12345");

參考:

    https://github.com/pengwei1024/LogUtils

安卓 log日誌架構

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.