The "Hello World" example from SLF4J is not working for me. I guess this is because I added slf4j-log4 to my classpath. Should I configure log4j directly for the hello world to work?
log4j:WARN No appenders could be found for logger (HelloWorld). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Update: I added log4j initialization, and it still doesn't work:
public static void main(String[] params) { org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender()); Logger logger = org.slf4j.LoggerFactory.getLogger(TestBase.class); logger.info("Hello World"); }
And I'm getting:
log4j:ERROR No output stream or file set for the appender named [null].
So essentially, SLF4J does not replace log4j; they both work together. It removes the dependency on log4j from your application and makes it easy to replace it in the future with the more capable library.
Conclusion. So essentially, SLF4J does not replace Log4j, Both work together. SLF4j removes the tight coupling between the application and logging frameworks. It makes it easy to replace with any other logging framework in the future with a more capable library.
If you want to use slf4j simple
, you need these jar
files on your classpath:
If you want to use slf4j
and log4j
, you need these jar
files on your classpath:
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With