In this post, we will look at setting up Log4J2 File Appender with Spring Boot. Apart from console logging, we also want our logs to be pushed to files. This helps in arranging logs by date or size and also archival depending on the application requirements.

We have already looked at basic Spring Boot Log4J2 Setup and also, we have looked Spring Boot Log4J2 Configuration examples in previous posts. If you are new to Spring Boot, I have a detailed post about Spring Boot Microservices that you can refer.

1 – Adding Log4J2 File Appender Configuration

The easiest way to enable logging to file is to add the FileAppender in the log4j2.xml file of your application. In case you are using YAML or JSON file for your Log4J2 configuration, then the FileAppender configuration has to be added there.

See below:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </Console>
        <File name="FileAppender" fileName="app.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.progressivecoder.loggingdemo" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </Root>
    </Loggers>
</Configuration>

As you can see, in the above file, we have the ConsoleAppender and the FileAppender in the Appenders section. Also, using the filename property, we provide the filename where we want the logs to be written. In this case, it is app.log. Next, we specify the PatternLayout for the logs in the file.

Finally, in the Loggers section, we add both the appenders to our Logger. This basically means that the logs will be written both to the console as well as the file.

2 – Log4J2 RollingFileAppender Setup

Many times a single log file can become problematic. Over time, all the logs are written to this file and it might become too big in size. Therefore, it is good choice to have some mechanism to split the log files into parts. This helps us manage the logs in a better way.

Below is how we can add a RollingFileAppender to our Log4J2 setup.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </Console>
        <File name="FileAppender" fileName="app.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </File>
        <RollingFile name="RollingFileAppender"
                     fileName="logging-demo-app.log"
                     filePattern="logging-demo-app-%d{dd-MM-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <!-- rollover on startup, daily and when the file reaches
                    5 KiloBytes -->
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy
                        size="5 KB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.progressivecoder.loggingdemo" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="RollingFileAppender" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="RollingFileAppender" />
        </Root>
    </Loggers>
</Configuration>

Some important points about the RollingFileAppender are as follows:

  • We provide the filename property for the file where current logs will go. The filePattern property describes how the filenames will be for the splitted files. For example, in this case, we use a pattern that adds the date into the filename to help identify the logs easily.
  • The PatternLayout property helps specify the pattern of the log entries.
  • Next section is the Policies. Here, we can specify different policies for our log files. For example, the SizeBasedTriggeringPolicy specifies the file size limit of each file.
  • Also, the TimeBasedTriggeringPolicy specifies that the rolling policy should be time-based. As an example, it should create a new series of log files every day. This is controlled by the filePattern property.
  • Finally, the DefaultRolloverStrategy specifies the max number of files before we perform a rollover of the logs.

3 – Conclusion

With this we have successfully setup File Appender and Rolling File Appender using Log4J2. This makes our logging setup even more robust and makes it easy to manage the logs our application will generate.

The code for this is available on Github.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *