Search code examples
javaloggingslf4j

How to configure slf4j to be able writing both to console and file?


At the moment I'm using log4j, but many Java technologies use slf4j (hibernate for example). I'd like to configure log4j instead of slf4j. Here is my log4j file:

log4j.rootLogger=trace, stdout, file

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.encoding=UTF-8
log4j.appender.stdout.target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n

log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.encoding=UTF-8
log4j.appender.file.append=false
log4j.appender.file.file=myproject.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n

Could anyone show me a configuration file appropriate for it ? P.S. How can I log from Servlets ? As they're based in war in tomcat webapps. Where do they write their log in this case?


Solution

  • slf4j is a logging facade for java which can be used with different logging frameworks such as log4j,logback etc. The advantage it provides is you can change underlying frameworks(just jars and configuration files) without touching the code in case you want to switch to a different one in the future.

    to use slf4j over log4j you would still need log4j properties and some jars such as slf4j-api-1.6.1.jar, slf4j-log4j12-1.6.1.jar and log4j-1.2.16.jar (assume you already have this)

    refer this tutorial. hope it helps.