Simple encapsulation of log4j with Java classes

Source: Internet
Author: User

 

In the past, debugging information was required for a project using Java. out. println, although I have known log4j for a long time, but I have not studied it carefully. It is generally simple. property file to configure, but recently carefully looked at the log4j source file, found that people Apache has long been not recommended to use. property is preferred. XML, So I studied it again. for xml configuration, please note here.

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <! Doctype log4j: Configuration System "log4j. DTD"> </P> <p> <log4j: configuration xmlns: log4j = "http://jakarta.apache.org/log4j/"> </P> <p> <! -- Created by David Hsing <DavidHsing@163.com>, on Oct.20 2009, PM --> </P> <p> <! -- <Br/> % C full name of the class to which the output log information belongs <br/> % d date or time of the time point of the output log. The default format is iso8601, you can also specify a format later, for example, % d {yyyy-mm-dd hh: mm: SS}. The output is similar: 20:08:08 <br/> % F Class Name of the class to which the output log information belongs <br/> % L location of the output log event, the statement that outputs the log information is in the row number of the class in which it is located <br/> % m the information specified in the output code, such as log (Message) message in <br/> % N outputs a carriage return line break, "RN" for Windows, and "N" for Unix <br/> % P output priority, debug, info, warn, error, and fatal. If it is output by calling debug (), it is debug, <br/> % R the number of milliseconds it takes to output log information from application startup to output <br/> % t the name of the thread that generates the log event <br/> --> </P> <p> <! -- Appender: leleappender --> <br/> <appender name = "log4j. consoleappender "class =" org. apache. log4j. consoleappender "> <br/> <layout class =" org. apache. log4j. patternlayout "> <br/> <Param name =" conversionpattern "value =" % d {yyyy-mm-dd hh: mm: SS} [%-5 p] [% T] % c {2} (% F: % L) -% m % N "/> <br/> </layout> <br/> </appender> </P> <p> <! -- Appender: fileappender --> <br/> <appender name = "log4j. fileappender "class =" org. apache. log4j. fileappender "> <br/> <Param name =" file "value =" $ {log4jlogpath}/apprunlog. log "/> <br/> <Param name =" APPEND "value =" true "/> <br/> <Param name =" encoding "value =" UTF-8 "/> <br/> <layout class = "org. apache. log4j. patternlayout "> <br/> <Param name =" conversionpattern "value =" % d {yyyy-mm-dd hh: mm: SS} [%-5 p] [% T] % C {2} (% F: % L) -% m % N "/> <br/> </layout> <br/> </appender> </P> <p> <category name =" org. apache. log4j. XML "> <br/> <priority value =" debug "/> <br/> </Category> </P> <p> <! -- ===================================================== =========================================== --> </P> <p> <! -- Logger level: Debug, info, warn, error, fatal, all, off --> </P> <p> <! -- Output internal SQL --> <br/> <logger name = "Java. SQL. connection "> <br/> <level value =" debug "/> <br/> </logger> <br/> <logger name =" Java. SQL. preparedstatement "> <br/> <level value =" debug "/> <br/> </logger> </P> <p> <! -- Set the overall default Log Level --> <br/> <root> <br/> <level value = "Warn"/> <br/> <appender-ref =" log4j. consoleappender "/> <br/> <appender-ref =" log4j. fileappender "/> <br/> </root> </P> <p> <! -- ===================================================== ========================================= --> </P> <p> </log4j: configuration> <br/>

 

This XML is created, but because XML needs to be configured during runtime, and log4j can only be configured once, the simplest way is to encapsulate it again, write a class to configure and provide logger:

 Package XXX. utilities; </P> <p> Import Java. io. *; <br/> Import Org. apache. log4j. *; <br/> Import Org. apache. log4j. helpers. *; <br/> Import Org. apache. log4j. SPI. *; <br/> Import Org. apache. log4j. XML. *; </P> <p>/** <br/> * General log4j encapsulation class <br/> * the external class calls log4jlogger. getlogger () <br/> * @ author David Hsing <br/> */<br/> public class log4jlogger <br/>{< br/>/** <br/> * the default configuration file of the class is log4j. XML, Location: <br/> * Web: $ {WEB-I NF}/config/log4j. XML <br/> * jar: $ {jarpath}/config/log4j. XML <br/> */<br/> protected static final string this_class_path = (utilclass. getjarclasspath (log4jlogger. class )! = NULL &&! Utilclass. getjarclasspath (log4jlogger. Class). Trim (). Equals (""))? Utilclass. getjarclasspath (log4jlogger. Class): "."; <br/> Public static final string default_config_file = utilclass. isrunningonweb ()? Utilclass. getwebrootpath () + "/WEB-INF/config/log4j. XML ": this_class_path +"/config/log4j. XML "; // $ NON-NLS-1 $ // $ NON-NLS-2 $ <br/> Public static final string default_log_savepath = utilclass. isrunningonweb ()? Utilclass. getwebrootpath () + "/WEB-INF/log": this_class_path + "/log "; // $ NON-NLS-1 $ // $ NON-NLS-2 $ <br/> Public static final string default_fileappender_name = "log4j. fileappender "; // $ NON-NLS-1 $ </P> <p> // optional </P> <p> static <br/>{< br/> If (! Islog4jconfigured () <br/>{< br/> system. setproperty ("log4jlogpath", default_log_savepath); <br/> If (! Resetconfiguration () <br/>{< br/> loglog. Error ("log4jlogger. Static: Initialize log4j in static method faild! '"); <Br/>}</P> <p> protected log4jlogger () {}</P> <p> // logs </P> <p> @ suppresswarnings ("unchecked") <br/> Public static logger getlogger (final class clsclass) <br/>{< br/> If (! Islog4jconfigured ()&&! Resetconfiguration () <br/>{< br/> loglog. Error ("log4jlogger. getlogger (): Initialize log4j with class faild! "); <Br/> return NULL; <br/>}< br/> return logmanager. getlogger (clsclass. getname (); <br/>}</P> <p> Public static logger getlogger (final string sclassname) <br/>{< br/> If (! Islog4jconfigured ()&&! Resetconfiguration () <br/>{< br/> loglog. Error ("log4jlogger. getlogger (): Initialize log4j with string faild! "); <Br/> return NULL; <br/>}< br/> return logmanager. getlogger (sclassname); <br/>}</P> <p> Public static logger getlogger (final string sclassname, final loggerfactory lfloggerfactory) <br/>{< br/> If (! Islog4jconfigured ()&&! Resetconfiguration () <br/>{< br/> loglog. Error ("log4jlogger. getlogger (): Initialize log4j with loggerfactory faild! "); <Br/> return NULL; <br/>}< br/> return logmanager. getlogger (sclassname, lfloggerfactory); <br/>}</P> <p> Public static logger getrootlogger () <br/>{< br/> return logmanager. getrootlogger (); <br/>}</P> <p> // configure </P> <p>/** <br/> * set the log output path of the log4j fileappender file <br/> * @ Param sappendername: log4j. fileappender name in XML, default Default_fileappender_name <br/> * @ Param spathname: You can use log4jlogger. default_log_savepath + "/app20091110.log" in the form of using the relative path <br/> * @ return Boolean <br/> */<br/> synchronized public static Boolean setfileappenderpath (string sappendername, string spathname) <br/>{< br/> If (sappendername! = NULL &&! Sappendername. Trim (). Equals ("") & spathname! = NULL &&! Spathname. trim (). equals ("") <br/>{< br/> spathname = spathname. trim (); <br/> appender l4jappender = logmanager. getloggerrepository (). getrootlogger (). getappender (sappendername); <br/> If (l4jappender! = NULL & (l4jappender instanceof fileappender) <br/>{< br/> fileappender l4jfileappender = (fileappender) l4jappender; <br/> l4jfileappender. setfile (spathname); <br/> l4jfileappender. activateoptions (); <br/> return true; <br/>}< br/> return false; <br/>}</P> <p> // logs </P> <p>/** <br/> * set the log output path of the log4j fileappender file <Br/> * @ Param sappendername: log4j. the fileappender name in XML. Default Value: default_fileappender_name <br/> * @ Param spathname: log4jlogger can be used. default_log_savepath + "/app20091110.log" in the form of using relative paths <br/> * @ Param bappend: whether the log is in append mode <br/> * @ return Boolean <br/> */<br/> synchronized public static Boolean setfileappenderpath (string sappendername, string spathname, Boolean bappend) <br/>{< br/> If (sappendern Ame! = NULL &&! Sappendername. Trim (). Equals ("") & spathname! = NULL &&! Spathname. trim (). equals ("") <br/>{< br/> spathname = spathname. trim (); <br/> appender l4jappender = logmanager. getloggerrepository (). getrootlogger (). getappender (sappendername); <br/> If (l4jappender! = NULL & (l4jappender instanceof fileappender) <br/>{< br/> fileappender l4jfileappender = (fileappender) l4jappender; <br/> try <br/>{< br/> l4jfileappender. setfile (spathname, bappend, l4jfileappender. getbufferedio (), l4jfileappender. getbuffersize (); <br/>}< br/> catch (ioexception ioex) <br/>{< br/> loglog. error ("log4jlogger. setfileappenderpath (): ioexception: pathname = '"+ spathname +" '", Ioex); <br/> return false; <br/>}< br/> l4jfileappender. activateoptions (); <br/> return true; <br/>}< br/> return false; <br/>}< br/> // configure </P> <p>/** <br/> * determines whether log4j is initialized <br/> * Based on System. getproperty ("log4jlogpath"); <br/> */<br/> synchronized public static Boolean islog4jconfigured () <br/> {<br/> string s Log4jlogpath = system. getproperty ("log4jlogpath"); // $ NON-NLS-1 $ <br/> return (slog4jlogpath! = NULL &&! Slog4jlogpath. trim (). equals ("")); <br/>}</P> <p> // reset </P> <p>/** <br/> * reset to default configuration <br/> */ <br/> synchronized public static Boolean resetconfiguration () <br/>{< br/> file feconfigfile = new file (default_config_file); <br/> If (feconfigfile. exists () & feconfigfile. isfile () & feconfigfile. canread () <br/>{< br/> If (default_config_file.trim (). tolowercase (). endswith (". XML ") // $ NON-NLS-1 $ <br/>{< br/> domconfigurator. configure (default_config_file); <br/>}< br/> else if (default_config_file.trim (). tolowercase (). endswith (". properties ") // $ NON-NLS-1 $ <br/>{< br/> propertyconfigurator. configure (default_config_file); <br/>}< br/> return true; <br/>}< br/> return false; <br/>}< br/>

 

In this way, you do not need to configure it during the call. You can directly obtain the logger and output it.

Note that it is best to put. XML in the same directory of the Java class (you can also specify the path in the above class ).

Code:

Package xxx; </P> <p> Import Org. apache. log4j. *; </P> <p> public class testlog4j <br/> {<br/> protected static logger l4jlogger = log4jlogger. getlogger (testlog4j. class); </P> <p> // test code <br/> l4jlogger. error ("here is the log4j test of David Hsing. "); <Br/>}< br/>

 

In this way, you can run normally.

However, the above XML is just an example. If you really want to study it, there is still a lot of content, such as output to different places by event level. In short, log4j is a very powerful and efficient stuff, it is worth studying carefully.

 

Appendix:

How to configure log4j properties:

Log4j. rootlogger = info, consoleappender </P> <p> # leleappender <br/> log4j. appender. leleappender = org. apache. log4j. leleappender <br/> log4j. appender. leleappender. threshold = warn <br/> log4j. appender. leleappender. target = system. out <br/> log4j. appender. leleappender. encoding = UTF-8 <br/> log4j. appender. leleappender. layout = org. apache. log4j. patternlayout <br/> log4j. appender. leleappender. layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS} [%-5 p] [% T] % c {2} (% F: % L) -% m % n </P> <p> # output internal SQL <br/> log4j. logger. java. SQL. connection = leleappender <br/> log4j. logger. java. SQL. preparedstatement = leleappender

 

 

References:

1. Apache logging project homepage: http://logging.apache.org

2. http://wiki.apache.org/logging-log4j/Log4jXmlFormat

Related Article

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.