log4j Example - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Sunday, November 05, 2017

log4j Example


Apache Log4j is a Java-based logging utility. This is a comprehensive guide to integrate log4j in to a java project quickly & easily.

Anyway it is a really simple & straight forward task indeed.

1. Add log4j maven dependency to pom.xml file

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
</dependency>

2. Create a folder named 'resources' under 'main' folder





3. Create a new file in resources folder named ‘log4j.properties’

4. Add the logging metadata settings in ‘log4j.properties’

# Root logger option
log4j.rootLogger=info, stdout, file

# Redirect log messages to console
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.SSS} [%thread] %-5p %c %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File
=lcf4j.log
log4j.appender.file.MaxFileSize
=100MB
log4j.appender.file.MaxBackupIndex
=10
log4j.appender.file.layout
=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern
=%d{yyyy:MM:dd HH:mm:ss.SSS} [%thread] %-5p %c %m%n

5. Settings in ‘log4j.properties’

·        %d{yyyy:MM:dd HH:mm:ss.SSS} – you can set a custom date time format here
·        %thread – Thread which is executing when the logging is happening
·        %-5p – the log level, INFO, DEBUG, ERROR & etc
·        %c – Class to which the log message belongs to
·        %m%n – log message and to make a new line at the end

6. Add the logger in Java classes which need logging

final static Logger logger = Logger.getLogger(App.class);

7. Logging output

2017:11:03 23:54:08.459 [mainhread] INFO  com.devdummy.App Hello World!

8. Checkout/ Download Source Code

References

1. https://logging.apache.org/log4j/2.x/
2. https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html

No comments:

Post a Comment