How to get SLF4J "Hello World" working with log4j?
If you want to use slf4j simple
, you need these jar
files on your classpath:
- slf4j-api-1.6.1.jar
- slf4j-simple-1.6.1.jar
If you want to use slf4j
and log4j
, you need these jar
files on your classpath:
- slf4j-api-1.6.1.jar
- slf4j-log4j12-1.6.1.jar
- log4j-1.2.16.jar
No more, no less. Using slf4j simple
, you'll get basic logging to your console at INFO
level or higher. Using log4j
, you must configure it accordingly.
Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.
-
Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency>
-
Configure log4j.properties
log4j.rootLogger=TRACE, 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'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
-
Java example
public class Slf4jExample { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(Slf4jExample.class); final String message = "Hello logging!"; logger.trace(message); logger.debug(message); logger.info(message); logger.warn(message); logger.error(message); } }
you need to add 3 dependency ( API+ API implementation + log4j dependency)
Add also this
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
# And to see log in command line , set log4j.properties
# Root logger option
log4j.rootLogger=INFO, file, 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
#And to see log in file , set log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
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} %-5p %c{1}:%L - %m%n