How to output log files in log4j2 based on classes?

In log4j2, log messages can be directed to different files based on the class name. To do this, one must first define one or more Loggers in the log4j2 configuration file, specifying their names and the files to output to.

Here is an example configuration file content of log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="FileAppender1" fileName="logs/app1.log">
            <PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n" />
        </File>
        <File name="FileAppender2" fileName="logs/app2.log">
            <PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.example.app1" level="debug" additivity="false">
            <AppenderRef ref="FileAppender1" />
        </Logger>
        <Logger name="com.example.app2" level="debug" additivity="false">
            <AppenderRef ref="FileAppender2" />
        </Logger>
        <Root level="error">
            <AppenderRef ref="FileAppender1" />
        </Root>
    </Loggers>
</Configuration>

In the configuration file above, two FileAppenders are defined to output to two different files (app1.log and app2.log). Two Loggers are then defined to correspond to two different classes (com.example.app1 and com.example.app2), each specifying which FileAppender to use.

Therefore, when the logs in these two classes are printed, they will be output to the corresponding files based on the class name. Additionally, a Root Logger is defined to output all other logs that are not specified with a FileAppender to the file corresponding to FileAppender1.

Please note that the log4j2.xml configuration file must be placed in the classpath for log4j2 to locate and load it.

bannerAds