log4j use variables to configure log output file locations

Source: Internet
Author: User
Tags log4j

Configuration log file relative path in http://sharep.blog.51cto.com/539048/143734 log4j

2009-03-30 18:52:55 Tags: log4j leisure career

This article is written more comprehensive, turn around, is to share it, at the same time thank Javaeye on the Zengjinliang, OH method One, the solution is to use the relative path to replace the absolute path, in fact, log4j Fileappender itself has such a mechanism, such as: Log4j.appender.logfile.file=${workdir}/logs/app.log
where "${workdir}/" is a variable that is replaced by the value "Workdir" in the system property. In this way, we can use System.setproperty ("Workdir", Workdir) before log4j load the configuration file, and set the root path, which can be done through an initial servlet.

Method Two, you can use the server environment variables
The log4j configuration file supports the server's VM environment variable, in a format similar to ${catalina.home}
Log4j.appender.r=org.apache.log4j.rollingfileappender
Log4j.appender.r.file=${catalina.home}/logs/logs_tomcat.log
log4j.appender.r.maxfilesize=10kb
The ${catalina.home} is not an environment variable for Windows systems, and this environment variable does not need to be set in the Windows System environment variable. The reason for this is that you can look at the Tomcat\bin\catalina.bat (Startup,shutdown are calling this) with-dcatalina.home= "%catalina_home%" inside itself. Inherit this idea, so you can also set a parameter-dmylog.home= "D:/abc/log" to the corresponding server Java-initiated VM parameters

Method III, load the file property implementation relative path through the servlet initialization init () method
Implementation: To do a servlet, when the system loading, the properties of the file read to a properties file. That file's property value (I'm using a relative directory) to get rid of (preceded by the system's root directory), Let's set the properties object to Propertyconfig so that the log settings are initialized. You don't have to configure it in the later use.
Generally in our development project process, log4j log output path fixed to a folder, so if I change an environment, the log path needs to be modified, more inconvenient, at present I used dynamic change log path method to implement relative path to save log files
(1). Mount the initialization class at the start of the project:
public class Log4jinit extends HttpServlet {
static Logger Logger = Logger.getlogger (Log4jinit.class);
Public Log4jinit () {
}

public void init (ServletConfig config) throws servletexception {
String prefix = Config.getservletcontext (). Getrealpath ("/");
String file = Config.getinitparameter ("log4j");
String filePath = prefix + file;
Properties Props = new properties ();
try {
FileInputStream istream = new FileInputStream (FilePath);
Props.load (IStream);
Istream.close ();
Toprint (Props.getproperty ("Log4j.appender.file.File"));
String logFile = prefix + props.getproperty ("Log4j.appender.file.File");/set Path
Props.setproperty ("Log4j.appender.file.File", logFile);
Propertyconfigurator.configure (props)//Mount log4j configuration information
catch (IOException e) {
Toprint ("Could not read configuration file [" + FilePath + "].");
Toprint ("Ignoring configuration file [" + FilePath + "].");
Return
}
}

public static void Toprint (String content) {
SYSTEM.OUT.PRINTLN (content);
}
}
In fact, the log4j configuration file log4j.properties, as the default name, can be placed anywhere in the classpath that the JVM can read, usually in the Web-inf/classes directory. When the log4j configuration file is no longer the default name, you need to load and give the parameters separately, as above "ropertyconfigurator.configure (props);//Mount log4j configuration Information"

(2). Configuration in the Web.xml
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Note: The above load-on-startup is set to 0 so that the servlet is loaded when the Web container is started. The log4j.properties file is placed in the properties subdirectory of the root, or it can be placed in a different directory. The. properties file should be stored centrally so that it is easy to manage.
(3) In log4j.properties You can configure Log4j.appender.file.File as the relative path for the current application.


The above is the online log4j log file relative path configuration of three methods (I can find on the three kinds), analysis:

Method one mainly expands the log4j Rollingfileappender class, other fileappender same reason. The extension method is to use a subclass to overwrite the Setfile method, which is called when the log4j reads the configuration file to generate Appender, and the incoming is the matching
The path in the file so that I can add a root path to the path in front of my own mind. This method can be used to configure the Log4j.appender.A1.File property with relative paths freely in log4j.properties to determine the generated log relative to the Web application root
The location of the directory.

The second method is to set the log path relative to the ${catalina.home} by using the environment variables already existing in the server VM, such as ${catalina.home}, and the log can only be placed in the server subdirectory, and if the other server is used, the corresponding environment variable should be changed. This method platform porting is not convenient.

The third 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 path of the log4j log file relative to the current application. Details
Fine code is as follows:

Program code
Package wbb.bysxxglxt.util;

Import org.apache.struts.action.*;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.commons.logging.Log;
Import javax.servlet.ServletException;
Import java.util.Properties;
Import Java.io.InputStream;
Import Org.apache.log4j.PropertyConfigurator;
Import Java.io.FileInputStream;
Import java.io.IOException;

public class Extendedactionservlet extends Actionservlet {
Private log = Logfactory.getlog (This.getclass (). GetName ());

Public Extendedactionservlet () {}

public void Init () throws Servletexception {
Log.info (
"Initializing, my myactionservlet init this System ' s Const Variable");
String prefix = this.getservletconfig (). Getservletcontext (). Getrealpath (
"/");
String file = This.getservletconfig (). Getinitparameter ("log4j");
String filePath = prefix + file;
Properties Props = new properties ();
System.out.println (prefix);
System.out.println (file);
System.out.println (FilePath);

try {
FileInputStream Log4jstream = new FileInputStream (FilePath);
Props.load (Log4jstream);
Log4jstream.close ();
String logFile = prefix +
Props.getproperty ("Log4j.appender.A1.File"); Set path

System.out.println (LogFile);
Props.setproperty ("Log4j.appender.A1.File", logFile);
Propertyconfigurator.configure (props); Mount log4j configuration information
catch (IOException e) {
E.printstacktrace ();
}
Log.info ("Initializing, End I Init");
Super.init ();//struts applied, this method cannot be saved, there are many important actions in this method that Actionservlet covered
}
}


Application Web.xml Key Parts ***************************


Program code
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>wbb.bysxxglxt.util.ExtendedActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>log4j</param-name>
<param-value>properties\log4j.properties</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


Note the log4j of the backslash line in the relative path in the parameter, and the Log4j property file is best renamed in a directory such as web-inf/classes directory or Web-inf, because before this servlet is loaded, servers, such as Tomcat, automatically search for log4j.properties files in the Web-inf directory and web-inf/classes directories, if they are automatically loaded. After the Log4j property file is loaded, an automatic load configuration error occurs because the Log4j.appender.A1.File value in the property file is in a relative path:
Log4j:error Setfile (null,true) call failed.
Java.io.filenotfoundexception:web-inf\logs\bysxxglxt.log (the system cannot find the specified path.) )
I don't know why log4j start automatically so early. Although the Log4j property file is correctly set and loaded in the actionservlet of the extension that is later loaded, the error of the report is still strange, so only change the name of the Log4j property file or change its location so that it cannot automatically load, but there are still two warnings:
Log4j:warn No Appenders could is found for logger (org.apache.commons.digester.Digester.sax).
Log4j:warn Please initialize the log4j system properly.
This is a kind of self-deception, if you have a better solution, hope to be posted here, we study together.

log4j.properties*****************************
### Set Logger level ###

Program code
Log4j.rootlogger=debug,stdout,a1

### appender.stdout output to console ###
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.target=system.out
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern= [%5p] [BYSXXGLXT]%d{yyyy-mm-dd HH:mm:ss}:%-4r [%-5p] [%t] (%F,%L)-%m %n

### Appender. A1 output to log file ###
Log4j.appender.a1=org.apache.log4j.dailyrollingfileappender
Log4j.appender.a1.file=web-inf\\logs\\bysxxglxt.log
# #注意上面日志文件相对应用根目录路径的写法
Log4j.appender.a1.datepattern= '. ' Yyyy-mm-dd '. Log '
Log4j.appender.a1.append=true
# # Output A log above the debug level
Log4j.appender.a1.threshold=debug
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
log4j.appender.a1.layout.conversionpattern= [%5p] [BYSXXGLXT]%d{yyyy-mm-dd HH:mm:ss}:%-4r [%t] (%f,%l)-%m%n

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.