Andrey Yaskulsky
Andrey Yaskulsky

Reputation: 2516

log4j - INFO to console and ERRORS to file

I want to redirect all messages with error level to file and messages with info level to console. Here is my log4j.properties:

log4j.rootLogger=INFO, stdout
log4j.logger.java.lang.Exception=ALL, java.lang.Exception

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

log4j.appender.java.lang.Exception=org.apache.log4j.RollingFileAppender
log4j.appender.java.lang.Exception.File=\\clientexceptionlog.txt
log4j.appender.java.lang.Exception.MaxFileSize=2048KB
log4j.appender.java.lang.Exception.layout=org.apache.log4j.PatternLayout
log4j.appender.java.lang.Exception.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

But seems like it doesn't work as I expect: clientexceptionlog.txt is always empty. What I'm doing wrong? Thanks!

Upvotes: 2

Views: 3707

Answers (1)

ConcurrentHashMap
ConcurrentHashMap

Reputation: 5084

You may work with the Treshold option. Doing it that way, you can set the rootLogger to both, stdout and your file appender (I named it myAppender in the following code snippet):

log4j.rootLogger=INFO, stdout, myAppender

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

log4j.appender.myAppender=org.apache.log4j.RollingFileAppender
log4j.appender.myAppender.Threshold=WARN
log4j.appender.myAppender.File=\\clientexceptionlog.txt
log4j.appender.myAppender.MaxFileSize=2048KB
log4j.appender.myAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.myAppender.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

What does it do? It sends everything with a loglevel INFO or higher to stdout and myAppender. While stdout will output all (including higher loglevels like WARN and ERROR) the myAppender will filter out everything that is lower than WARN (due to log4j.appender.myAppender.Threshold=WARN).

BTW: Don't use java.lang.Exception as name for the appender. That may confuse any one reading this configuration (including me!)

Upvotes: 5

Related Questions