log4j's configuration

2019-08-05 13:49发布

问题:

I want to config my logging system based on slf4j and log4j. I want to log all messages from com.A class. And only those messages.

so I wrote in my config file

log4j.rootLogger=FATAL, All
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=com.A
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.conversionPattern=%m%n

My runner (com.Start class) contains

PropertyConfigurator.configure("log4j.properties");

But when I start application I get

log4j:ERROR A "com.A" object is not assignable to a "org.apache.log4j.Appender" variable.
log4j:ERROR The class "org.apache.log4j.Appender" was loaded by 
log4j:ERROR [sun.misc.Launcher$AppClassLoader@d9f9c3] whereas object of type 
log4j:ERROR "com.A" was loaded by [sun.misc.Launcher$AppClassLoader@d9f9c3].
log4j:ERROR Could not instantiate appender named "A1".
log4j:WARN No appenders could be found for logger (com.Start).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Where's my error?

Thanks.

回答1:

Your configuration file isn't properly written.
Appender shouldn't be the class/package deceleration but a type of appender you would like to output messages to (leave it blank if you wish to output to the default appender)
The file should look more like:

log4j.rootLogger=FATAL 
log4j.logger.com.A=DEBUG


回答2:

Is your file formatted incorrectly? What you posted looks broken. I put in some linebreaks:

log4j.rootLogger=FATAL, All 
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=com.A
log4j.appender.Console=org.apache.log4j.ConsoleAppender 
log4j.appender.Console.layout=org.apache.log4j.PatternLayout 
log4j.appender.Console.layout.conversionPattern=%m%n

Also this line seems wrong:

log4j.appender.A1=com.A

It needs to specify the name of a real appender class, like

log4j.appender.A1=org.apache.log4j.ConsoleAppender