为什么使用 slf4j + logback
logbak定位于log4j的替代者,logback同样支持slf4j,方便被替换。在Android平台上,我在使用log4中遇到tag混乱的问题。相比log4j,logback-android的jar更小巧。
下载jar包
前往 https://github.com/tony19/logback-android ,下载获得 logback-android-1.1.1-4.jar slf4j-api-1.7.6.jar
导入到工程中
将上面的两个jar文件放入项目中的libs中,并添加项目引用。
配置日志文件的位置
注意下面代码中的 configureLogbackDirectly 方法,它接收一个文件路径参数,指示存放日志文件的目录,还有一个是生成的日志文件的前缀。我下面配置了“每天生成一个新的日志文件”。
package vir56k.logdemo;
import android.os.Environment;
import org.slf4j.LoggerFactory;
import java.io.File;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.android.LogcatAppender;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
/**
* Created by zhangyunfei on 15/9/21.
*/
public class LogConfigurator {
public static void confifure() {
final String LOG_DIR = Environment.getExternalStorageDirectory() + File.separator + "logback";
final String PREFIX = "log";
configureLogbackDirectly(LOG_DIR, PREFIX);
}
private static void configureLogbackDirectly(String log_dir, String filePrefix) {
// reset the default context (which may already have been initialized)
// since we want to reconfigure it
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<ILoggingEvent>();
rollingFileAppender.setAppend(true);
rollingFileAppender.setContext(context);
// OPTIONAL: Set an active log file (separate from the rollover files).
// If rollingPolicy.fileNamePattern already set, you don't need this.
//rollingFileAppender.setFile(LOG_DIR + "/log.txt");
TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
rollingPolicy.setFileNamePattern(log_dir + "/" + filePrefix + "_%d{yyyyMMdd}.txt");
rollingPolicy.setMaxHistory(7);
rollingPolicy.setParent(rollingFileAppender); // parent and context required!
rollingPolicy.setContext(context);
rollingPolicy.start();
rollingFileAppender.setRollingPolicy(rollingPolicy);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
encoder.setContext(context);
encoder.start();
rollingFileAppender.setEncoder(encoder);
rollingFileAppender.start();
LogcatAppender logcatAppender = new LogcatAppender();
logcatAppender.setContext(context);
logcatAppender.setEncoder(encoder);
logcatAppender.setName("logcat1");
logcatAppender.start();
// add the newly created appenders to the root logger;
// qualify Logger to disambiguate from org.slf4j.Logger
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.TRACE);
root.addAppender(rollingFileAppender);
root.addAppender(logcatAppender);
// print any status messages (warnings, etc) encountered in logback config
//StatusPrinter.print(context);
}
}
使用方法
先声明和创建实例
private static final Logger logger = LoggerFactory.getLogger(MainActivity.class);
写入日志
logger.debug("debug Some log message. Details: {}", "debug 输出");
logger.info("info Some log message. Details: {}", "debug 输出");
logger.error("error Some log message. Details: {}", "debug 输出");
代码混淆注意
请在你的混淆设置里加入下面这些:
-keep class ch.qos.** { *; }
-keep class org.slf4j.** { *; }
-keepattributes *Annotation*
示例代码下载地址
https://github.com/vir56k/demo/tree/master/logBackDemo
参考资料:
https://github.com/tony19/logback-android
https://github.com/tony19/logback-android/wiki/Appender-Notes