log4j.properties File Example

In log4j tutorial, we saw how to use log4j xml based configuration. But log4j.xml is verbose, so log4j framework provide option to read configuration from properties file too.

Since properties file don’t have any defined schema to validate, we have to be more careful with it. Today we will see how XML configurations can be converted to properties based configuration.

Root Logger

Root logger is used when there is no match with a logger. It’s defined like below in XML.

It can be defined in properties file as below.

The first value in comma separated list is the root logging level value. All other values are appenders.

Log4j Appenders

We can have multiple appenders in log4j. Below are two appenders, one for console logging and another to file.

In log4j.properties file, they will be defined as below.

So the format for log4j properties file appender is log4j.appender.{appender_name}.{appender_config}. Notice that the appenders configurations such as MaxFileSize, MaxBackupIndex are same as in XML configuration file.

Log4j loggers

Just like appenders, we can have multiple loggers. For example of xml based configuration;

They will be defined in properties file as log4j.logger.{logger_name}. The values contain logging level and list of appenders to use.

Log4j logger additivity

Additivity usage is shown in above logger xml configuration, it’s the attribute of logger element. Below is the way to use it in log4j properties file configuration as log4j.additivity.{logger_name}.

Based on above, below is my final log4j.properties file.

Log4j PropertyConfigurator

PropertyConfigurator is used to configure log4j settings. It’s optional if the file name is log4j.properties and it’s in the project classpath. We have to configure it before using the logger.

Here is a simple program showing how to configure and use log4j logging.

When it’s executed, you will get below in console log.

At the same time, you will see logs getting generated in main.log file as below.

Notice that debug and info logger are not getting printed because the minimum logging level is set as WARN. That’s all for log4j properties file example usage. Happy Logging!

By admin

Leave a Reply