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
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
Gradle configuration
compile group: 'log4j', name: 'log4j', version: '1.2.17'
log4j.properties configuration
The log4j.properties 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).
log4j.properties 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: log4j.appender.myfile=org.apache.log4j.RollingFileAppender # path to logs (in Windows use c:\\my-app.log): log4j.appender.myfile.File=/tmp/my-app.log # Log to file only up to 500KB: log4j.appender.myfile.MaxFileSize=500KB # Keep at most 3 backup files: log4j.appender.myfile.MaxBackupIndex=3 # Layout of messages for the appender: log4j.appender.myfile.layout=org.apache.log4j.PatternLayout 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 log4j.properties 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(FileLogging.java:19) at com.farenda.loggers.log4j.FileLogging.main(FileLogging.java:12)
References:
- See Log4j Console Appender configuration example
- Read Log4j 1.2 manual for detailed description of Log4j
- See PatternLayout for description of layout format