Log4j2

參考資料:(http://javabruce.blogspot.com/2016/03/log4j2.html)

下載點:(http://logging.apache.org/log4j/2.x/download.html)

範例:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2Example {

    private static final Logger LOG = LogManager.getLogger(Log4j2Example.class.getName());
    public static void main(String[] args) {
        LOG.debug("This will be printed on debug");
        LOG.info("This will be printed on info");
        LOG.warn("This will be printed on warn");
        LOG.error("This will be printed on error");
        LOG.fatal("This will be printed on fatal");

        LOG.info("Appending string: {}.", "Hello, World");

    }

}

設定檔 log4j2.xml 放在classpath

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>

    <File name="MyFile" fileName="D:/Brian/log.txt">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="Console" />
        <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>

File的屬性 fileName 設定路徑

Root 內要有配置 AppenderRef 的屬性 ref 要記錄log的名稱。

Last updated