文件Appender无法正常工作logback-android

时间:2017-05-10 11:25:08

标签: android logging logback

我正在使用logback-android和SLF4J。我正在以编程方式设置日志记录配置:

object LoggingConfiguration {
    private const val LOGCAT_PATTERN = "[%thread] %logger{32} | %msg%n"
    private const val FILE_PATTERN =
            "%date{ISO8601} %-5level [%thread] %logger{32} | %msg%n"
    private const val LOG_DIR = "logs"
    private const val FILE_SIZE = "1MB"
    private const val NUM_FILES = 5

    private val logger = LoggerFactory.getLogger(javaClass)

    @JvmStatic var logDirPath: String? = null
        private set
    var logFilePath: String? = null
        private set

    /**
     * Configure logging to append to logcat and create rolling log files.

     * @param context Application context. It is used to construct the path
     *                where the log files will be stored.
     *
     * @param tag A top level label for your log messages. It is used both as
     *            the logcat tag and as the log file name. If null, then a
     *            tag is derived from the package name of the context.
     *
     * @param logLevel String representation of a log level, as understood
     *                 by logback. Commonly used values are "WARN", "INFO",
     *                 "DEBUG" and "VERBOSE". For the full list, see
     *                 [ch.qos.logback.classic.Level]. If null, then
     *                 "DEBUG" is used.
     */
    @JvmStatic @JvmOverloads
    fun configure(context: Context, tag: String? = null, logLevel: String? = null) {
        val label = tag ?: ClassNameOnlyAbbreviator().abbreviate(context.packageName)

        val logDirPath = File(context.filesDir, LOG_DIR).absolutePath
        val logFilePath = String.format("%s/%s.log", logDirPath, label)
        val logFilePathPattern =
                String.format("%s/%s.%%i.log", logDirPath, label)

        val logcatTag = label
        val logbackLevel = Level.toLevel(logLevel)

        configureLogback(logbackLevel, logcatTag, logFilePath, logFilePathPattern)
        this.logDirPath = logDirPath
        this.logFilePath = logFilePath

        logger.info("Logging configured to append to logcat and file")
        logger.info("Log level: {} (parsed from string '{}')", logbackLevel, logLevel)
        logger.info("Logcat tag: {} ", logcatTag)
        logger.info("Log file path: {}", logFilePath)
    }

    private fun configureLogback(logLevel: Level, logcatTag: String,
                                 logFilePath: String, logFilePathPattern: String) {
        val loggerContext = LoggerFactory.getILoggerFactory() as LoggerContext
        loggerContext.reset()

        val rollingFileAppender = makeRollingLogFileAppender(logFilePath,
                logFilePathPattern, loggerContext)
        val logcatAppender = makeLogcatAppender(logcatTag, loggerContext)

        val rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as LogbackLogger

        StatusPrinter.print(loggerContext)
        rootLogger.apply {
            level = logLevel
            addAppender(rollingFileAppender)
            addAppender(logcatAppender)
        }
    }

    private fun makeRollingLogFileAppender(
            filePath: String, filePathPattern: String, context: LoggerContext):
            RollingFileAppender<ILoggingEvent> {
        val appender = RollingFileAppender<ILoggingEvent>().apply {
            this.context = context
            file = filePath
        }

        appender.encoder = PatternLayoutEncoder().apply {
            this.context = context
            pattern = FILE_PATTERN
            start()
        }

        appender.triggeringPolicy = SizeBasedTriggeringPolicy<ILoggingEvent>().apply {
            maxFileSize = FILE_SIZE
            start()
        }

        appender.rollingPolicy = FixedWindowRollingPolicy().apply {
            this.context = context
            minIndex = 1
            maxIndex = NUM_FILES
            fileNamePattern = filePathPattern
            setParent(appender)
            start()
        }

        return appender.apply {
            start()
        }
    }

    private fun makeLogcatAppender(tag: String, context: LoggerContext): LogcatAppender {
        val encoder = PatternLayoutEncoder().apply {
            this.context = context
            pattern = LOGCAT_PATTERN
            start()
        }

        val tagEncoder = PatternLayoutEncoder().apply {
            this.context = context
            pattern = tag
            start()
        }

        return LogcatAppender().apply {
            this.context = context
            this.encoder = encoder
            this.tagEncoder = tagEncoder
            start()
        }
    }
}

我从configure(context: Context, tag: String? = null, logLevel: String? = null)调用Application.onCreate()方法。

我在LogCat中获取所有日志,但只记录文件中的特定类。我不确定我做错了什么。我用相同的配置创建了另一个项目,但是那里没有出现同样的问题。

我尝试了各种配置和logback.xml方法,但我无法将其写入文件。

0 个答案:

没有答案