使用 代码 配置 Log4j2

依赖

    implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.0")
    implementation("org.apache.logging.log4j:log4j-core:2.17.0")

代码

import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.config.ConfigurationFactory
import org.apache.logging.log4j.core.config.Configurator


object Main {

    init {
        val builder = ConfigurationFactory.newConfigurationBuilder()
        val console = builder.newAppender("stdout", "Console")
        val std = builder.newLayout("PatternLayout").apply {
            addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %logger{36} %-5level: %msg%n%throwable")
        }
        console.add(std)
        builder.add(console)
        builder.add(builder.newRootLogger(Level.ALL).apply { add(builder.newAppenderRef("stdout")) })
        Configurator.initialize(builder.build())
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val logger = LogManager.getLogger("主函数")
        logger.info("测试")
    }
}

运行结果

image

posted @ 2021-12-26 12:25  博麗靈夢  阅读(120)  评论(0编辑  收藏  举报