Search code examples
javalogginglog4jaudit-logging

Log4j doesn't create audit log file


I want to track audit logs to separate file audit.log

I have the following configuration for log4j

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Audit logs
log4j.appender.A2=org.apache.log4j.FileAppender
log4j.appender.A2.File=/home/michal/audit.log
log4j.appender.A2.Append=true
log4j.appender.A2.encoding=UTF-8
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} - AUDIT - %m%n

In my code I'm calling

private static final Logger logger = Logger.getLogger("A2");
logger.info("audit test");

But audit log file is not created. When I put A2 level to rootLogger, the file is created but it is full of logs from stdout target.


Solution

  • A2 is an appender not a logger. You need to add a line to your log4j configuration to define a logger that writes to your appender and then you can write to that in your java code.

    In your config

    log4j.logger.audit=INFO, A2
    

    and in your java code

    private static final Logger logger = Logger.getLogger("audit");