Configure the relative path of log4j

Source: Internet
Author: User

The following method 3 is not detailed. I use listener, after you set <load-on-startup> 0 </load-on-startup> to start servlet or after the log configuration file, you can use listener to start the servlet before the configuration file.

Turn: http://hi.baidu.com/suofang/blog/item/6cf2befbd1ff07234f4aea90.html

It took me one morning to solve the Relative Path Problem of log4j log files in struts. There are three methods to configure the relative path of log4j log files on the Internet (For details, refer to the reference materials in this article ):

Method 1 mainly extends the rollingfileappender class of log4j. The same applies to other fileappender classes. The extension method is to overwrite the setfile method with a subclass. This method is called when log4j reads the configuration file and generates an appender.
Set the path in the file so that I can add the root path before the path according to my own ideas. In this method, you can use the relative path in log4j. properties to freely configure the log4j. appender. a1.file attribute to determine whether the generated log is relative to the Web application root.
Directory location.

Method 2: Use the existing environment variables in the server Vm, such as $ {Catalina. home} to set relative to $ {Catalina. the Log Path of home}. Logs can only be placed in the server subdirectory. If other servers are used, change the corresponding environment variable. This method is inconvenient for platform migration.

The third method is to extend the actionservlet class and overwrite its Init () method. In the new method, the parameters at the log4j. properties location are loaded. You can freely configure the name and storage location of the log4j configuration file. You can also configure the path of the log4j log file to the current application. Details
The Code is as follows:

* ********* WBB. bysxxglxt. util. extendedactionservlet ********************
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 the path

System. Out. println (logfile );
Props. setproperty ("log4j. appender. a1.file", logfile );
Propertyconfigurator. Configure (props); // load log4j configuration information
} Catch (ioexception e ){
E. printstacktrace ();
}
Log.info ("initializing, end my init ");
Super. INIT (); // struts is applied. This method cannot be saved. actionservlet overwrites this method with many important operations.
}
}

* ********************** Application Web. key part of XML ***************************

<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 method of the slash line of the relative path in the log4j parameter, and it is best to rename the log4j attribute file if it is placed in the Web-INF/classes directory or web-INF directory, before the servlet is loaded, the server automatically searches for log4j in the Web-INF directory and web-INF/classes directory when Tomcat is started. properties file, automatically loaded if any. After the log4j attribute file is loaded, because the value of log4j. appender. a1.file in this attribute file uses a relative path, an error occurs when the configuration is automatically loaded:
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 is automatically started so early. Although the log4j attribute file is correctly set and loaded in the extended actionservlet, this error is still unpleasant, therefore, only the log4j attribute file name can be changed or its storage location cannot be automatically loaded. However, there are two warnings:
Log4j: warn no appenders cocould be found for logger (Org. Apache. commons. digester. digester. Sax ).
Log4j: Warn please initialize the log4j system properly.
If you have a better solution, I hope you can post it here and study it together.

* ******************** Log4j. properties *****************************

### Set the logger level ###
Log4j. rootlogger = debug, stdout, A1

### Appender. stdout output to the console ###
Log4j. appender. stdout = org. Apache. log4j. leleappender
Log4j. appender. stdout. Target = system. Out
Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout
Log4j. appender. stdout. layout. conversionpattern = [% 5 p] [bysxxglxt] % d {yyyy-mm-dd hh: mm: SS }: %-4r [%-5 p] [% T] (% F, % L)-% m % N

### Appender. A1 output to the log file ###
Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a1.file = WEB-INF // logs // bysxxglxt. Log
# Note the method of writing the above Log File relative to the application root directory path
Log4j. appender. a1.datepattern = '. 'yyyy-mm-dd'. Log'
Log4j. appender. a1.append = true
# Output logs at or above the debug level
Log4j. appender. a1.threshold = debug
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = [% 5 p] [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.