RollingFile Appender in log4j2.xml

  • February 19, 2020

There are several Appenders in log4j2 that you can use to send application logs to a specified location. Use File Appender to pick the application logs and store it in a file specified at some location.

You need to follow certain steps to customize log4j2.xml to implement File Appender. It starts with creating a simple Mule application. The following is example application:

RollingFile Appender1

The scheduler configuration will be like the following:

RollingFile Appender2

The first logger component before a transform message component will look like the following:

RollingFile Appender3

The transform message component will be configured as shown below:

RollingFile Appender4

The first logger component after a transform message is configured as shown below:

RollingFile Appender5

The second logger after a transform message is configured as shown below:

RollingFile Appender6

How to configure log4j2.xml file

When you create any MuleSoft project, the default location of log4j2.xml is under the src/main/resources directory.

The configuration of log4j2.xml will be:

RollingFile Appender7
RollingFile Appender8

In the above screenshot of log4j2.xml, we’ve defined two properties:

  1. fileSize: the size of the log file
  2. numberOfFiles: the maximum number of log files that can be created at specified location
    RollingFile Appender9

The RollingFile Appender can be defined using three properties:

  1. name: unique name assigned to RollingFile Appender
  2. fileName: name of the log file to be created
  3. filePattern: name pattern of the file to be created
  4. RollingFile Appender10

%i is defined to assign a number to a log file. For example, mule-testapp-1, mule-testapp-2…….

You can define a trigger based on file size using SizeBasedTriggeringPolicy. If there’s a limit set using this policy, then a new file will get created after reaching this limit.

RollingFile Appender11

DefaultRolloverStrategy is used to set a limit on the number of files and overwrite the same number of files again and again. It means that initially, only 10 files will be created in the specified location. Those 10 files will get overwritten again. In the above example, we have two RollingFile Appenders, one for the INFO level and another for the ERROR level.

RollingFile Appender12

Both appenders will write the files in different locations.

RollingFile Appender13
RollingFile Appender14

Once you complete all the changes and start running the application, log files will be written at specified locations.

RollingFile Appender15
RollingFile Appender16

Initially the first 10 log files will be written.

RollingFile Appender17

Those files will get overwritten again.

RollingFile Appender18

— By Manish Prabhu