Multiple log files with log4j

2019-03-16 02:45发布

问题:

I am creating a solution for my application log, which have various types of logging (user, application, etc...), wanted to save each type of log in a separate file.

This is possible with log4j or some other API? How could I do that?

If you deem interesting, I edit the question and put the codes, but I do not think it's worth, they are still very basic.

Thanks in advance.

回答1:

Of cource, use different FileAppenders Example from internet:

log4j.rootLogger=DEBUG

# AdminFileAppender - used to log messages in the admin.log file.
log4j.appender.AdminFileAppender=org.apache.log4j.FileAppender

log4j.appender.AdminFileAppender.File=admin.log

log4j.appender.AdminFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AdminFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n

# ReportFileAppender - used to log messages in the report.log file.
log4j.appender.ReportFileAppender=org.apache.log4j.FileAppender

log4j.appender.ReportFileAppender.File=report.log

log4j.appender.ReportFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ReportFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.vaannila.admin=WARN,AdminFileAppender 
log4j.logger.com.vaannila.report=DEBUG,ReportFileAppender 

Now you can log to admin.log Logger.getLogger("com.vaannila.admin").log("To admin log") and to report log Logger.getLogger("com.vaannila.report").log("To report log")



回答2:

Log4j provides for Loggers and Appenders. The way to do this is to have an Appender for each file you want. They set up an appropriate set of Loggers that point to the appropriate Appender(s). Loggers are usually set up using package names. If this will work for you, code in package x goes to file y, just do that. Otherwise, create Loggers per output file and have the code choose the appropriate logger. You can also have Loggers and send the information to multiple Appenders, so you can set these up as appropriate.

See korifey's post for an example of how to set this up.



标签: java log4j