Javase use log4j personalization control log __java

Source: Internet
Author: User
Tags throwable log4j

Use log4j to personalize control logs in Javase, as required:

1. Log the log above the warning level to the error log.

2. Log the normal info information into the info log.

3. Log the debug information into trace log.

4.log information as detailed as possible, and the format is easy to read, the key content includes: Package name, class name, method name, call parameters, exception information, error line number, and so on.

A maximum of 10 log files are retained for each type, and the oldest log is deleted when more than 10 files are logged, and the log file name format is: "*_0.log", "*_1.log" ... "*_9.log". Single log file maximum capacity 10MB.

The log4j configuration file Log4j.xml is as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?> <! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" > <log4j:configuration xmlns:log4j= "http://jakarta.apache.org/" log4j/"debug=" false "threshold=" null "> <!--this are final xml4j that confirms Xml4j.dtd--> class = "Com.log4j.test.TestLoggingRollingFileAppender" name= "error" > <param name= "Threshold" value= "WARN"/> < param name= "File" value= "/var/opt/test/log/test_error0_0.log"/> <param name= "Append" value= "true" ;p Aram Name= "MaxFileSize" value= "10MB"/> <param name= "Maxbackupindex" value= ""/> <layout "class=" org. Apache.log4j.PatternLayout "> <param name=" Conversionpattern "value="%d{yyyy-mm-dd-' T ' HH:mm:ss. SSSZ} | ${host} | %x | %-15t | %-5p | %c | %m%n "/> </layout> <filter class=" Org.apache.log4j.varia.LevelRangeFilter "> <param na Me= "Levelmin" value= "WARN"/> <param name= "LEvelmax "value=" FATAL "/> </filter> </appender> <appender class=" Com.log4j.test.TestLoggingRolli Ngfileappender "name=" info "> <param name=" threshold "value=" info "/> <param" File "Name=" value= /test/log/test_info0_0.log "/> <param name=" Append "value=" true "/> <param" name= "MaxFileSize" value= "10M
      B "/> <param name=" Maxbackupindex "value=" "/> <layout" class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpattern" value= "%d{yyyy-mm-dd-' T ' HH:mm:ss." SSSZ} | ${host} | %x | %-15t | %-5p | %c | %m%n "/> </layout> <filter class=" Org.apache.log4j.varia.LevelRangeFilter "> <param na Me= "Levelmin" value= "info"/> <param name= "Levelmax" value= "info"/> </filter> </appen der> <appender class= "Com.log4j.test.TestLoggingRollingFileAppender" Name= "Trace" > <param name= "Thresho" LD "value=" DEBUG "/> <parAm Name= "File" value= "/var/opt/test/log/test_trace0_0.log"/> <param name= "Append" value= "true"/> M name= "MaxFileSize" value= "10MB"/> <param name= "maxbackupindex" value= "/> <layout class=" Org.apach E.log4j.patternlayout "> <param name=" Conversionpattern "value="%d{yyyy-mm-dd-' T ' HH:mm:ss. SSSZ} | ${host} | %x | %-15t | %-5p | %c | %m%n "/> </layout> </appender> <logger additivity=" true "Name=" Com.log4j.test "> <lev El value= "info"/> <appender-ref ref= "error"/> <appender-ref ref= "info"/> Ref ref= "Trace"/> </logger> <root> <level value= "INFO"/> <appender-ref ref= "error"/&gt
    ; <appender-ref ref= "info"/> <appender-ref ref= "Trace"/> </root> </log4j:configuration>

Because the log4j default rollingfileappender scrolling log feature file name format is: "*.log1", "*.log2" and other unmet requirements "*_0.log", "*_1.log" ... "*_9.log" format, Therefore, the custom scrolling logging class implements the custom log ordinal format as follows:

The following configuration in the Log4j.xml configuration file specifies the directory and name format of the log file:

<param name= "File" value= "/var/opt/test/log/test_error0_0.log"/> <param name=

"file" value= "/var/opt/ Test/log/test_info0_0.log "/>

<param name=" File "value="/var/opt/test/log/test_trace0_0.log "/>
Using the following custom log file to scroll the Append class, you can implement the logging file naming format: "*_0.log", "*_1.log" ... "*_9.log", and log4j when logging, the file number of the current record is always 0_0:

Class Testloggingrollingfileappender extends Rollingfileappender {private static final String File_name_postfix = "_

    0.log ";
    Public Testloggingrollingfileappender () {super ();
        Public Testloggingrollingfileappender (Layout Layout, String filename, Boolean append) throws IOException {
    Super (layout, filename, append); Public Testloggingrollingfileappender (Layout Layout, String filename) throws IOException {super (Layout, fi
    Lename); }//rewrite log4j rollingfileappender scrolling log method, log file is full, automatically write new file, log4j default file name rule is: *.log0, *.log1 ...//change log filename rule to: *_0.log, * _1.log ...
        This method automatically invokes public void rollover () {File target by log4j when each log file is full;

        File file;
            if (QW!= null) {Long size = (countingquietwriter) qw). GetCount ();
        Loglog.debug ("Rolling over count=" + size);

        } loglog.debug ("maxbackupindex=" + maxbackupindex);
        Boolean renamesucceeded = true;
        The number of log files configured is greater than 0if (Maxbackupindex > 0) {///get the oldest log filename, the oldest log file is the most important number = new file (filename.substring 0, fi
            Lename.length ()-file_name_postfix.length ()) + ' _ ' + Maxbackupindex + ". Log"); Delete the oldest log file, does not necessarily exist the oldest file, only the log file number is equal to the maximum number of log files configured to delete the oldest logfile if (File.exists ()) {renamesucceeded = File.de
            Lete (); ///Add the log filename's ordinal number plus 1, such as *_2.log to *_3.log, that is, the newest log will be recorded in the log file with the smallest ordinal number for (int i = maxBackupIndex-1; I >= 1 && Amp renamesucceeded; i--) {//get log filename File = new file (filename.substring (0, Filename.length ()-File_name_postfix.length ()
                + ' _ ' + i + ". Log"); if (file.exists ()) {//Add the log filename's ordinal number to 1, the smallest ordinal number is 2 target = new file (filename.substring 0, Filename.leng
                    Th ()-file_name_postfix.length ()) + ' _ ' + (i + 1) + ". Log");
                    Loglog.debug ("Renaming file" + file + "to" + target);
                renamesucceeded = File.renameto (target); }
            ////Name the most recently filled log file as serial number 1 if (renamesucceeded) {//named *_1.log file tar

                get = new File (filename.substring (0, Filename.length ()-file_name_postfix.length ()) + ' _ ' + 1 + '. log ');
                This.closefile ();
                File = new file (fileName);
                Loglog.debug ("Renaming file" + file + "to" + target);
                renamesucceeded = File.renameto (target);
                        Log file rename failed, reopen log file continue to append log if (!renamesucceeded) {try {
                    This.setfile (FileName, True, Bufferedio, buffersize); catch (IOException e) {if (e instanceof interruptedioexception) {T
                        Hread.currentthread (). interrupt ();
                    Loglog.error ("Setfile + FileName +", true) call failed. ", e); All lo in}}}//g files are renamed successfully if (renamesucceeded) {try {///close all scrolling log files This.setfile (FileName, False,
            Bufferedio, buffersize); The catch (IOException e) {if (e instanceof interruptedioexception) {Thread.currentthr
                EAD (). interrupt ();
            Loglog.error ("Setfile (" + FileName + ", false) call failed.", e); }
        }
    }
}
In this log file scrolling rename method, because the log file number of the current record always starts at 0, the log file ordinal is added to 1 sequentially to achieve the serial number scrolling.

Define your own log class, read the Log4j.xml configuration file, call the log4j corresponding log method, and implement a custom format log.

public class testlog{private static final String Logger_name = "Com.log4j.test"; private static final String Log_path = "/etc/opt/log4j_test/conf/" private static final string log_conf_name = "log4j.
    XML ";
    private static final String Error_log_entry_separator = ",";
    private static final String empty_string = new string ();

    private static Logger log = null;  Initialize and load Log configuration static{try {//First load log4j profile from specified location on server file = new
            File (Log_path + log_conf_name);
            if (file.exists ()) {domconfigurator.configure (constants.rac3gp_conf_dir + log_conf_name); ///If the log4j profile does not exist at the specified location on the server, load the log4j configuration file in the jar package else{inputstream in = thread.current
                Thread (). Getcontextclassloader (). getResourceAsStream (Log_conf_name);
 New Domconfigurator (). Doconfigure (In, Logmanager.getloggerrepository ()); C} catch (Exception e) {           System.err.println ("Loading log4j configuration failed, ErrorMsg:" + e.getmessage ());
        Log = Logger.getlogger (Logger_name);
    Log.trace ("Log initializing ...");
    public static void Logaudit (String message) {log.info (message);
    public static void Logtrace (String message) {log.debug (message); public static void Logerror (Object location, string method, String errormessage) {Logerror (locatio
    N, method, NULL, errormessage); public static void Logerror (Object location, string method, Exception exp, string errormessage) {Strin
        G ClassName = Location.getclass (). GetName ();
        if (errormessage = = null) {errormessage = "";
        String errormsg = ClassName + "" + Method + ":" + errormessage;

        StringBuffer msg = new StringBuffer (errormsg); IF (exp!= null) {msg.append (constants.nl). Append (Constants.nl). Append (Getstacktrace (exp));
        } else{Msg.append (Getstacktrace (New Bulkcmexception ()));
    Log.error (msg);
    public static void Logerror (Object location, string method, Exception exp, string sessionId, String errormessage)
        {String msg = sessionId + Error_log_entry_separator + errormessage;
    Logerror (location, method, exp, msg); private static String Getstacktrace (Throwable t) {if (t = = null) {return empt
        y_string;
            try {stringwriter LOCALSW = new StringWriter ();
            PrintWriter LOCALPW = new PrintWriter (LOCALSW);
            T.printstacktrace (LOCALPW);
        return localsw.tostring ();
        catch (Throwable u) {return empty_string; The public static void Loginfo (Object location, String message) {string className = Location.getClass (). GetName ();
        String msg = className + ":" + message;
    Log.info (msg);
    public static void Loginfo (String message) {log.info (message); }
}
In your application, you can implement custom log logging requirements by simply calling the log logging method of the Log class.

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.