Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

log4j example configuration file logger

In this post we show Log4j example configuration that logs messages to a configured log file, and creates backups when needed.

log4j 1.2 project dependency

Add log4j 1.2 dependency to your project if you don’t have it already:

Maven configuration


Gradle configuration

compile group: 'log4j', name: 'log4j', version: '1.2.17' configuration

The file has to be on classpath (or WEB-INF/classpath for webapps) during run-time, so put it inside src/main/resources directory (for Maven and Gradle). defines:

  • what loggers are used (rootLogger),
  • where they output messages (appenders),
  • in what format (layout),
  • and on what level (DEBUG, INFO, etc.)

Below we define a logger that will print by default every DEBUG message into RollingFileAppender (named myfile), that will not be bigger than 500 KB. It the amount of logs will grow above 500KB log4j RollingFileAppender will create a backup file and move old logs there. It will create up to 3 backup files.

# Root logger logs DEBUG messages into 'myfile' appender
log4j.rootLogger=DEBUG, myfile

# myfile (arbitrary name) defined as File Appender:
# path to logs (in Windows use c:\\my-app.log):
# Log to file only up to 500KB:
# Keep at most 3 backup files:

# Layout of messages for the appender:
log4j.appender.myfile.layout.conversionPattern=%d [%t] %-5p %c - %m%n

Java File Logging application example

The below program logs DEBUG and ERROR into a log file configured in the above configuration:

package com.farenda.loggers.log4j;

import org.apache.log4j.Logger;

public class FileLogging {

    private static final Logger logger
            = Logger.getLogger(FileLogging.class);

    public static void main(String[] args) {
        FileLogging app = new FileLogging();
        app.compute("File logger");

    private void compute(String value) {
        logger.debug("Processing: " + value);

        try {
            value.length() / 0;
        } catch (Exception e) {
            logger.error("Uh! Oh!", e);

When you run the above code, it will write to /tmp/my-app.log file the following messages:

2016-11-03 17:05:52,910 [main] DEBUG com.farenda.loggers.log4j.FileLogging - Processing: File logger
2016-11-03 17:05:52,915 [main] ERROR com.farenda.loggers.log4j.FileLogging - Uh! Oh!
java.lang.ArithmeticException: / by zero
        at com.farenda.loggers.log4j.FileLogging.compute(
        at com.farenda.loggers.log4j.FileLogging.main(


Share with the World!