log4j - Logging in Files



Apache log4j provides various Appender objects, each of which can be used to log data in files as per customized needs.

File Appenders

Following are most commonly Use Cases:

XML Based Configuration

Following is a sample XML Based configuration of a FileAppender

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="logFile" packages="">
   <Appenders>
      <File name="logFile" fileName="logs/app.log">
      <PatternLayout>
         <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
      </File>
   </Appenders>
   <Loggers>
      <Root level="error">
         <AppenderRef ref="logFile"/>
      </Root>
   </Loggers>
</Configuration>

We're using Appenders tag to contain a File tag to define the File Appender which is further writing to a log file app.log using PatternLayout.

Properties Based Configuration

Following is a sample properties Based configuration of a FileAppender

log4j2.properties

appender.0.type = File
appender.0.name = logFile
appender.0.fileName = logs/app.log
appender.0.layout.type = PatternLayout
appender.0.layout.pattern = %d %p %c{1.} [%t] %m%n

rootLogger.level = ERROR
rootLogger.appenderRef.0.ref = FILE
Advertisements