Android Logback 使用配置

  • Android Logback 使用配置
compile 'org.slf4j:slf4j-api:1.7.21'
compile 'com.github.tony19:logback-android-core:1.1.1-6'
compile('com.github.tony19:logback-android-classic:1.1.1-6') {
     // workaround issue #73
     exclude group: 'com.google.android', module: 'android'
}
  • 代码中添加配置
/**
 * Logback 配置
 * Created by davy on 16/9/21.
 */
public class LogbackConfigurator {

    final static String PREFIX = "logs";

    public static void configure(Context context) {
        final String LOG_DIR = context.getExternalFilesDir("").getAbsolutePath() + File.separator + "logback";
        configureLogbackDirectly(LOG_DIR, PREFIX);
    }

    public static void configureLogbackDirectory(String logDir) {
        configureLogbackDirectory(logDir, PREFIX);
    }

    public static void configureLogbackDirectory(String logDir, String filePrefix) {

        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        context.reset();

        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 rollingFileAppender = new RollingFileAppender();
        rollingFileAppender.setAppend(true);
        rollingFileAppender.setContext(context);

        TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
        rollingPolicy.setFileNamePattern(logDir + File.separator + filePrefix + "_%d{yyyyMMdd}.txt");
        rollingPolicy.setMaxHistory(7);
        rollingPolicy.setParent(rollingFileAppender);  // parent and context required!
        rollingPolicy.setContext(context);
        rollingPolicy.start();

        rollingFileAppender.setRollingPolicy(rollingPolicy);
        rollingFileAppender.setEncoder(encoder);
        rollingFileAppender.start();

        LogcatAppender logcatAppender = new LogcatAppender();
        logcatAppender.setContext(context);
        logcatAppender.setEncoder(encoder);
        logcatAppender.setName("logcat");
        logcatAppender.start();

        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);
    }
}

你可能感兴趣的:(Android Logback 使用配置)