简体   繁体   中英

How to Write Java server logs to separate log file

Right now we are using a customized logger method for our application but now we have a stand alone code for which we need to write to a separate log file. We have little idea about log4j. I just want to know where to change properties if any so that i don't disturb the existing logger application as well as we write our logs into new log file.

First define a file appender:

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=/mylogfile.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n

Then point your package to use this appender:

log4j.logger.mypackage=LOGFILE
log4j.additivity.mypackage=false

The last line is important if you do not want your package to inherit the global appender. Doing so will result in the log messages from mypackage also printed at the default appender.

in log4j you can direct log entries to separate files based upon pacakge name.

log4j.logger.your.package1= LOG,STDOUT

log4j.additivity.your.package1=false

log4j.logger.your.package2= DEBUG, STDOUT

log4j.additivity.your.package2=false

I use XML configuration.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="logfile" class="org.apache.log4j.FileAppender">
    <param name="file" value="app.log"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d-%5p(%F:%L)-%m%n"/>
    </layout>
</appender>
<appender name="myLogfile" class="org.apache.log4j.FileAppender">
    <param name="file" value="myFile.log"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d-%5p(%F:%L)-%m%n"/>
    </layout>
</appender>
<logger name="org.myApp">
    <level value="INFO"/>
    <appender-ref ref="myLogfile" />
</logger>
<root>
    <level value="ERROR" />
    <appender-ref ref="logfile" />
</root>
</log4j:configuration>

只需使用FileAppender并在构造函数中指定一个新文件名即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM