Preface:
Log4j is a widely used Java log component. We can easily use it to output log information to the console, files, databases, and other storage media, or even output it to any storage media in the form of stream extension.
Problems to be Solved in this article:
How to use relative paths in the log4j. properties file?By default, we can only configure the absolute path in log4j. properties. In this way, the system deployment and the migration of the open environment will cause great inconvenience. We need to change the path. Therefore, we can use the following method to implement the relative path in log4j. properties:
1. Implement a Servlet
/**
* Log4j Initialization
* @ Author xiongchun
* @ Since 2011-04-26
*/
Public class log4jinitservlet extends httpservlet {
/**
* Servlet Initialization
*/
Public void Init (servletconfig config) throws servletexception {
String root = config. getservletcontext (). getrealpath ("/");
String log4jlocation = config. getinitparameter ("log4jlocation ");
System. setproperty ("webroot", root );
If (g4utils. isnotempty (log4jlocation )){
Propertyconfigurator. Configure (root + log4jlocation );
}
}
}
2. Load the servlet in Web. xml
<! -- Configure log4j -->
<Servlet>
<Servlet-Name> log4jinit </servlet-Name>
<Servlet-class> org. eredlab. g4.rif. util. log4jinitservlet </servlet-class>
<Init-param>
<Param-Name> log4jlocation </param-Name>
<Param-value> WEB-INF/classes/log4j. properties </param-value>
</Init-param>
<Load-on-startup> 0 </load-on-startup>
</Servlet>
3. The relative path can be used in log4j. properties as follows:
# Rlogfile
Log4j. appender. rlogfile = org. Apache. log4j. rollingfileappender
Log4j. appender. rlogfile. layout = org. Apache. log4j. patternlayout
Log4j. appender. rlogfile. layout. conversionpattern = % d % P [% C]-<% m> % N
Log4j. appender. rlogfile. File =$ {Webroot}/Logs/eredg4.log
Log4j. appender. rlogfile. maxfilesize = 2048kb
Log4j. appender. rlogfile. maxbackupindex = 10
Annotation:After writing it, I found that this method uses absolute paths, but it uses dynamic methods to obtain absolute paths to achieve the effect similar to relative paths.