I am trying to write logs in different files. I want to be able to write into different files from different methods. Say if there is an exception in Method A it writes in File A...if there is an exception in Method B write in File B. I read help on google, but they all suggest the debug, trace etc etc levels. My messages are all error messages, just the methods are different. I am using properties file for log4j. This is what it lo开发者_开发知识库oks like:
log4j.rootLogger=ERROR, ROOT
log4j.appender.ROOT=org.apache.log4j.RollingFileAppender
log4j.appender.ROOT.File=(**my_path**)\EmailIntegration.log
log4j.appender.ROOT.MaxFileSize=1000KB
log4j.appender.ROOT.MaxBackupIndex=5
log4j.appender.ROOT.layout=org.apache.log4j.PatternLayout
log4j.appender.ROOT.layout.ConversionPattern=[%d] %t %c %-5p - %m%n
log4j.logger.com.webage.ejbs=INFO
- Define your
log4j.rootLogger
. - Configure your rootLogger to an appender.
- Define what root logger must the class log to.
Example (my root logger is stdout
, infoout
, debugout
, errorout
).
#---This is the configuration file for Log4J---
log4j.threshold=ALL
log4j.rootLogger=ALL, stdout, infoout, debugout, errorout
Then I defined each logger (e.g. infoout
)
#--Log settings for infoout
log4j.appender.infoout=org.apache.log4j.RollingFileAppender
log4j.appender.infoout.file=C:/Logs/Music4Point0.info.log
log4j.appender.infoout.MaxFileSize=10240KB
log4j.appender.infoout.MaxBackupIndex=10
log4j.appender.infoout.layout=org.apache.log4j.PatternLayout
log4j.appender.infoout.layout.ConversionPattern=%d{dd-MMM-yyy HH:mm:ss,SSS} [%t] %-5p %c - %m%n
log4j.appender.infoout.Threshold=INFO
Now, I said that all org.hibernate.*
classes must log to DEBUG
threshold and infoout
logger.
log4j.logger.org.hibernate=DEBUG, infoout
log4j.additivity.org.hibernate=false
That's how you configure log4J to setup your custom logging.
The finest level of control in log4j is at class level. Anyway, you have two options:
First option, the simplest one, is to define special loggers for each method:
log4j.logger.LoggerForMethodA=ERRROR, APPENDERFORMETHODA
log4j.logger.LoggerForMethodB=ERRROR, APPENDERFORMETHODB
And in your class, use the appropiate logger on your methods.
The second option, the powerful one, is to switch to the xml configuration format, where you can define filters for each appender I think this is your best option. Check out the explanation on the XML configuration format, and how to use filters in log4j. That way you define one appender per file, and use the filter to guarantee that the exception goes to the proper file. Also take a look at the javadocs for the Filter, Logging Event and LocationInfo
精彩评论