Used to do the project to log4j, today to do a project and want to use this, are configured, want to write the log to the local file to save, used to write local documents to the C:/log.txt, just have time on the Internet to check the next better way:
method One: replace absolute path with relative path
The main is to expand the Log4j Rollingfileappender class, the other fileappender the same reason. The extension method is to overwrite the Setfile method with a subclass, which is called when the log4j reads the configuration file to generate Appender.
, the path in the configuration file is passed in so that I can add a root path to the path in front of my mind. This method can be used to determine the date of generation by log4j.properties the Log4j.appender.A1.File property in relative paths.
The location of the log relative to the Web application root directory.
method Two: Using server environment variables
is to set the log path relative to the ${catalina.home} with the existing environment variables such as ${catalina.home} in the server VM, the log can only be placed in the server subdirectory, and if the other server is used, change the corresponding environment
Amount This method platform porting is not convenient.
method Three: load the File property implementation relative path through the servlet initialization init () method
is to extend the Actionservlet class, override its init () method, load the log4j.properties position parameters in the new method, and freely configure the log4j configuration file name and location. You can also freely configure the log4j log file relative to the current
The path used.
Summing up the above three methods, it is advisable to approach three, but still cumbersome, to write a servlet, write a lot of code.
The following method is more practical I think we can try:
Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.File=.. Webapps//bjjjpcdemo//logs//log.txt
#log4j. Appender.file.File=. /webapps/bjjjpcdemo/logs/log.txt
Log4j.appender.file.layout=org.apache.log4j.patternlayout
Log4j.appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n
I tested that the default generated log file was in the server's Bin directory (I'm using tomcat), so I passed the relative path . webapps//project name//log directory//log file (or. /webapps/the project name/log directory/log file, you can automatically create log directories and log files in your project.
If you save it as a Web page, you can access it as a Web page, even better, as follows:
Log4j.appender.file=org.apache.log4j.fileappender
Log4j.appender.file.File=.. Webapps//bjjjpcdemo//logs//police.html
#log4j. Appender.file.File =.. /webapps/bjjjpcdemo/logs/police.html
log4j.appender.file.layout= Org.apache.log4j.HTMLLayout
Log4j.appender.file.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-% m%n