Home » Log4j Logging in Files

Log4j Logging in Files

by Online Tutorials Library

Log4J – Logging in Files

Log4j provides org.apache.log4j.FileAppender class to write your logging information into a file.

FileAppender Parameters

FileAppender has the following configurable parameters:

Parameter Description
immediateFlush The default value of this flag is true, which means the output stream to the file being flushed with each append operation.
encoding We can use any character – encoding. By default, encoding is the platform-specific encoding scheme.
threshold The level of the threshold for this appender.
Filename Log file’s name.
fileAppend The default value is true, which means the logging information is appended to the end of the same file.
bufferedIO This flag defines whether we need buffered writing enabled. The default value is false.
bufferSize If buffered I/O is enabled or true, it indicates the buffer size. By default, it is set to 8kb.

Let’s see one example for FileAppender:

Log4j.properties

Example.java

Output:

Hello this is a debug message  Hello this is an info message  

If you wish to have an XML configuration file equivalent to the above log4j.properties file, then below is the content:

Logging in Multiple Files

We can also write multiple messages into multiple files for certain reasons, for example, if the file size reached a certain threshold.

To write your information about logging into multiple files, you have to use org.apache.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.

There is only one important parameter in addition to the ones mentioned above for FileAppender:

DatePattern: This indicates when to rollover the file and the naming convention to be followed. By default, rollover is performed at midnight per day.

DatePattern is used to control the rollover schedule using one of the following patterns:

DatePattern Description
‘.’ yyyy-MM Rollover at the end of per month and the beginning of the next month.
‘.’ yyyy-MM-dd Rollover at midnight per day. It is the default value.
‘.’ yyyy-MM-dd-a Rollover is performed at mid day and midnight of each day.
‘.’ yyyy-MM-dd-HH Rollover at the top of every hour.
‘.’ yyyy-MM-dd-HH-mm Rollover every minute.
‘.’ yyyy-ww Rollover is performed on the first day of each week depending upon the locale.

Let’s see a sample configuration file log4j.properties to generate log files rolling over at midday and midnight of each day:


You may also like