Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing audit logs using log4j

Tags:

java

log4j

I have an application that needs to write logs of two different types: application log and audit log. Application log is used for debug purpose whereas audit log is to record the operations performed. Both logs will be in different files and each file should have only those logs as mentioned (means audit log file cannot have application log and vice versa).

How this can be implemented using log4j?
I know one way to implement this is by defining custom log level in log4j. Is there any other/better way to do?

like image 550
Newbie Avatar asked Sep 25 '12 08:09

Newbie


2 Answers

I have had the same use case. In your log4j.xml you can define two different loggers and an appender for each one. An example therefore:

<logger name="LOGGER_1" additivity="false">
    <appender-ref ref="LOGGER_FILE_1"/>
</logger>

<appender name="LOGGER_FILE_1" class="org.jboss.logging.appender.RollingFileAppender">
   <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
   <param name="File" value="${jboss.server.log.dir}/loggerFile1.log"/>
   <param name="Append" value="true"/>
   <param name="MaxFileSize" value="20MB"/>
      <param name="MaxBackupIndex" value="5"/>

      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
      </layout>
</appender>

In your Java-Code you can create a Logger with "Logger.getLogger("LOGGER_1")" which will write the log-outputs to the defined file.

like image 64
AnarchoEnte Avatar answered Oct 15 '22 11:10

AnarchoEnte


I don't think you need a new level. Rather, you need a particular Logger (or set of Loggers).

Normally you instantiate these with the class/package name. However for audit purposes you could simply instantiate a new Logger with the name "Audit" (or similar) and then configure appropriately using the standard mechanisms.

like image 39
Brian Agnew Avatar answered Oct 15 '22 10:10

Brian Agnew