Log4j configuration details

From: http://blog.csdn.net/zhshulin/article/details/37937365

Log4J's configuration file (Configuration File) is used to set the level, storage and layout of the logger. It can be accessed in key=value format Setting or setting information in xml format. Through configuration, you can create a Log4J runtime environment.

1. Configuration
file The basic format of the Log4J configuration file is as follows:
#Configure root Logger
log4j.rootLogger  =   [ level ]   ,  appenderName1 ,  appenderName2 ,  …

#Configure log information output destination Appender
log4j.appender.appenderName  =  fully.qualified.name.of.appender.class
  log4j.appender.appenderName.option1  =  value1
  …
  log4j.appender.appenderName.optionN = valueN

#Configure the format (layout) of the log information
log4j.appender.appenderName.layout  =  fully.qualified.name.of.layout.class
  log4j.appender.appenderName.layout.option1  =  value1
  …
  log4j.appender.appenderName.layout.optionN = valueN


Where [level] is the log output level, there are 5 levels:
FATAL       0  
ERROR      3  
WARN       4  
INFO          6  
DEBUG      7



Appender is the log output destination. The appenders provided by Log4j are as follows:
org.apache.log4j.ConsoleAppender (console),
org.apache.log4j.FileAppender(file),
org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
org.apache.log4j.WriterAppender (send log information to any specified place in stream format)


Layout : The log output format. The layouts provided by Log4j are as follows:
 
org.apache.log4j.HTMLLayout (layout in HTML table),
org.apache.log4j.PatternLayout (the layout pattern can be specified flexibly),
org.apache.log4j.SimpleLayout (contains the level and info string of the log info),
org.apache.log4j.TTCCLayout (including log generation time, thread, category, etc.)


Print parameters : Log4J uses a print format similar to the printf function in C language to format log information, as follows:

    
       %m prints the message specified in the code
  %p output priority, ie DEBUG, INFO, WARN, ERROR, FATAL
  %r The number of milliseconds it took to output the log information since the application was started
  %c The category to which the output belongs, usually the full name of the category in which it belongs
  %t output the name of the thread that generated the log event
  %n output a carriage return line feed, "/r/n" on Windows platform, "/n" on Unix platform
  %d Output the date or time of the log time point, the default format is ISO8601, you can also specify the format after it, for example: %d{yyy MMM dd HH:mm:ss ,SSS}, the output is similar to: October 18, 2002 22:10:28, 921  
  %l Output where the log event occurred, including the category name, the thread in which it occurred, and the number of lines in the code. Example: Testlog4.main(TestLog4.java: 10 )


2. Initialize the Logger in the code:

1) Call the BasicConfigurator.configure() method in the program: add a ConsoleAppender to the root logger, and set the output format to "%-4r [%t] %-5p %c %x through PatternLayout - %m%n", and the default level of the root logger is Level.DEBUG.
2) The configuration is placed in a file, the file name is passed through command line parameters, and it is parsed and configured through PropertyConfigurator.configure(args[x]);
3) The configuration is placed in a file, the file name and other information are passed through environment variables, and the default initialization process of log4j is used to parse and configure;
4) The configuration is placed in a file, and the file name and other information are passed through the application server configuration, using a special servlet to complete the configuration.

3. Set the log output level for different Appenders:

When debugging the system, we often pay attention to only the log output of abnormal level, but usually all levels of output are placed in a file, if the level of log output is BUG! ? Then go find it slowly.
At this time, we may wonder how good it would be to output the exception information to a file alone. Of course, Log4j already provides such a function, we only need to modify the Appender's Threshold in the configuration to achieve it, such as the following example:

[Configuration file]
### set log levels ###
log4j.rootLogger = debug ,  stdout ,  D ,  E

### 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 =  %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n

### Output to log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG ## Output logs above DEBUG level
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### Save exception information to a separate file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/error.log ## Exception log file name
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR ## Only output logs above ERROR level!!!
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n


[used in code]
public   class  TestLog4j  {
     public   static   void  main(String[] args)  {
        PropertyConfigurator.configure( " D:/Code/conf/log4j.properties " );
        Logger logger = Logger.getLogger (TestLog4j. Class);
        logger.debug( " debug " );
        logger.error( " error " );
    }
}


Run it to see if the exception information is saved in a separate file error.log log4j.properties Use 1. Parameter meaning description Type of output level ERROR, WARN, INFO, DEBUG ERROR is a serious error, mainly a program error WARN It is a general warning, such as session loss. INFO is the information to be displayed in general, such as login and logout DEBUG is the debugging information of the program. Configure log information output destination log4j.appender.appenderName = fully.qualified.name.of.appender.class 1. org.apache.log4j.ConsoleAppender (console) 2.org.apache.log4j.FileAppender (file) 3.org.apache.log4j.DailyRollingFileAppender ( generates a log file daily) 4.org.apache.log4j.RollingFileAppender (file When the size reaches the specified size, a new file is generated) 5.org.apache.log4j.WriterAppender (send log information to any specified place in stream format) configure the format of log information log4j.appender.appenderName.layout = fully. qualified.name.of.layout.class


 

















1.org.apache.log4j.HTMLLayout (layout in HTML form),
2.org.apache.log4j.PatternLayout (layout patterns can be flexibly specified ), 3.org.apache.log4j.SimpleLayout (
level of log information included ) and information string),
4.org.apache.log4j.TTCCLayout (contains log generation time, thread, category, etc.)
console option
Threshold=DEBUG: Specifies the lowest level of log message output.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
Target=System.err: By default: System.out, specifies the output console
FileAppender option
Threshold=DEBUF: specifies the lowest level of output for log messages.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specifies that messages are output to the mylog.txt file.
Append=false: The default value is true, which means adding the message to the specified file, and false means overwriting the content of the specified file with the message.
RollingFileAppender option
Threshold=DEBUG: Specifies the minimum level of output of log messages.
ImmediateFlush=true: The default value is true, which means that all messages will be output immediately.
File=mylog.txt: Specifies that messages are output to the mylog.txt file.
Append=false: The default value is true, which means adding the message to the specified file, and false means overwriting the content of the specified file with the message.
MaxFileSize=100KB: The suffix can be KB, MB or GB. When the log file reaches this size, it will be automatically rolled, that is, the original content will be moved to the mylog.log.1 file.
MaxBackupIndex=2: Specifies the maximum number of rolling files that can be generated.
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %d{yyyy-MM-dd HH:mm:ssS} %c %m%n
The meaning of several symbols in the log information format:
-X Number: X information is left-aligned when outputting;
%p: The priority of output log information, that is, DEBUG, INFO, WARN, ERROR, FATAL,
%d: The date or time of the output log time point, the default format is ISO8601, or it can be used in its After specifying the format, for example: %d{yyy MMM dd HH:mm:ss,SSS}, the output is similar to: October 18, 2002 22:10:28, 921
%r: The output from the application startup to the output of the log information costs The number of milliseconds
%c: The category to which the log information belongs, usually the full name of the class in which it belongs
%t: The thread name that generates the log event is
output %l: The location where the log event occurs, equivalent to %C.%M( %F:%L), including the category name, the thread in which it occurred, and the number of lines in the code. Example: Testlog4.main (TestLog4.Java:10)
%x: Output the NDC (Nested Diagnostic Context) associated with the current thread, especially for multi-client multi-threaded applications like Java servlets.
%%: output a "%" character
%F: output the name of the file where the log message is generated
%L: output the line number in the code
%m: output the message specified in the code, the specific log information generated
%n: output a Carriage return line feed, "/r/n" for Windows platform, "/n" for Unix platform Output log information line feed
You can add modifiers between % and pattern characters to control the minimum width, maximum width, and text size Alignment. Such as:
1)%20c: Specify the name of the output category. The minimum width is 20. If the name of the category is less than 20, it will be right-aligned by default.
2)%-20c: Specify the name of the output category. The minimum width is 20. If the name of the category is less than 20, the "-" sign specifies left alignment.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the name of the category is greater than 30, the extra characters on the left will be truncated, but if it is less than 30, there will be no spaces.
4)%20.30c: If the name of the category is less than 20, it will be filled with spaces and right-aligned. If the name of the category is longer than 30 characters, it will be truncated from the output characters farther from the left.
2. File configuration Sample1
log4j.rootLogger=DEBUG,A1,R
#log4j.rootLogger=INFO,A1,R
# ConsoleAppender output
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org. apache.log4j.
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n
# File output one file a day, the output path can be Customized, generally in the root path
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=blog_log.txt
log4j.appender.R.MaxFileSize=500KB
log4j.appender.R.MaxBackupIndex=10
log4j .appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [% p] - %m%n
file configuration Sample2
The Log4J configuration file given below implements a full set of functions such as outputting to the console, files, rolling back files, sending log emails, outputting to database log tables, and custom labels.
log4j.rootLogger=DEBUG,CONSOLE,A1,im
#DEBUG,CONSOLE,FILE,ROLLING_FILE,MAIL,DATABASE
log4j.addivity.org.apache=true
################## #
# Console Appender
###################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n
#####################
# File Appender
#####################
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=file.log
log4j.appender.FILE.Append=false
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
# Use this layout for LogFactor 5 analysis
########################
# Rolling File
########################
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=ERROR
log4j.appender.ROLLING_FILE.File=rolling.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.ROLLING_FILE.MaxFileSize=10KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=1
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
####################
# Socket Appender
####################
log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender
log4j.appender.SOCKET.RemoteHost=localhost
log4j.appender.SOCKET.Port=5001
log4j.appender.SOCKET.LocationInfo=true
# Set up for Log Facter 5
log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n
########################
# Log Factor 5 Appender
########################
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000
########################
# SMTP Appender
#######################
log4j.appender.MAIL=org.apache.log4j.NET.SMTPAppender
log4j.appender.MAIL.Threshold=FATAL
log4j.appender.MAIL.BufferSize=10
[email protected]
log4j.appender.MAIL.SMTPHost=mail.hollycrm.com
log4j.appender.MAIL.Subject=Log4J Message
[email protected]
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
########################
# JDBC Appender
#######################
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DATABASE.URL=jdbc:MySQL://localhost:3306/test
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
log4j.appender.DATABASE.user=root
log4j.appender.DATABASE.password=
log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n')
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=SampleMessages.log4j
log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'
log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
###################
#customAppender
###################
log4j.appender.im=net.cybercorlin.util.logger.appender.IMAppender
log4j.appender.im.host=mail. cybercorlin.Net
log4j.appender.im.username = username
log4j.appender.im.password = password
log4j.appender.im.recipient = [email protected]
log4j.appender.im.layout=org.apache.log4j.PatternLayout
log4j .appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
3. Advanced use
Experimental purpose:
1. Put FATAL level errors Write to 2000NT log
2. WARN, ERROR, FATAL level errors send email to notify
the administrator 3. Other level errors are directly output in the background
Experimental steps:
output to 2000NT log
1. Copy NTEventLogAppender.dll in the Log4j archive to WINNT/
2. Write the configuration file log4j.properties in the SYSTEM32 directory
# In 2000 system log output
log4j.logger.NTlog=FATAL, A8
# APPENDER A8
log4j.appender.A8=org.apache.log4j.nt.NTEventLogAppender
log4j.appender.A8.Source=JavaTest
log4j.appender.A8.layout= org.apache.log4j.PatternLayout
log4j.appender.A8.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
3. Calling code:
Logger logger2 = Logger.getLogger("NTlog "); //same name as set in the configuration file
logger2.debug("debug!!!");
logger2.info("info!!!");
logger2.warn("warn!!!");
logger2.error("error!!!");
//Only this error will be written to the 2000 log
logger2.fatal("fatal!!!");
Send email to notify the administrator:
1. First download JavaMail and JAF,
  http ://java.sun.com/j2ee/ja/javamail/index.html
  http://java.sun.com/beans/glasgow/jaf.html
references mail.jar and activation.jar in the project.
2. Write configuration file
# Send logs to email
log4j.logger.MailLog=WARN,A5
# APPENDER A5
log4j.appender.A5=org.apache.log4j.net.SMTPAppender
log4j.appender.A5.BufferSize=5
log4j.appender [email protected]
[email protected]
log4j.appender.A5.Subject=ErrorLog
log4j.appender.A5.SMTPHost=smtp.263.net
log4j.appender.A5 .layout=org.apache.log4j.PatternLayout
log4j.appender.A5.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
3. Calling code:
//Send the log to mail
Logger logger3 = Logger.getLogger("MailLog");
logger3.warn("warn!!!");
logger3.error("error!!!");
logger3.fatal("fatal!!!");
outputs all types of errors in the background:
1. Write a configuration file
# Output
log4j.logger.console=DEBUG, A1
# APPENDER A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout .ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
2. Calling code
Logger logger1 = Logger.getLogger("console");
logger1.debug("debug!!!");
logger1.info("info!!!");
logger1.warn("warn!!!");
logger1.error("error!!!");
logger1.fatal("fatal!!!");

All configuration files: log4j.properties
#
Log4j.logger.console=DEBUG, A1
# APPENDER A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j. PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
#
Log4j.logger.NTlog=FATAL, A8
# APPENDER A8
log4j. appender.A8=org.apache.log4j.nt.NTEventLogAppender
log4j.appender.A8.Source=JavaTest
log4j.appender.A8.layout=org.apache.log4j.PatternLayout
log4j.appender.A8.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
# Send log to email
log4j.logger.MailLog=WARN,A5
# APPENDER A5
log4j.appender.A5=org.apache.log4j.net.SMTPAppender
log4j.appender.A5.BufferSize=5
[email protected]
[email protected]
log4j.appender.A5.Subject=ErrorLog
log4j.appender.A5.SMTPHost=smtp.263.net
log4j.appender.A5.layout=org.apache.log4j.PatternLayout
log4j.appender.A5.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n


全部代码:Log4jTest.java

import org.apache.log4j.*;   
 //import org.apache.log4j.nt.*;   
 //import org.apache.log4j.net.*;   
 /**  
  * @author yanxu  
  */   
 public class Log4jTest   
 {   
  public static void main(String args[])   
  {   
   PropertyConfigurator.configure("log4j.properties");   
   // output in the background   
   Logger logger1 = Logger.getLogger("console");   
   logger1.debug("debug!!!");   
   logger1.info("info!!!");   
   logger1.warn("warn!!!");   
   logger1.error("error!!!");   
   logger1.fatal("fatal!!!");  
// output in NT syslog   
   Logger logger2 = Logger.getLogger("NTlog");   
   //NTEventLogAppender nla = new NTEventLogAppender();   
   logger2.debug("debug!!!");   
   logger2.info("info!!!");   
   logger2.warn("warn!!!");   
   logger2.error("error!!!");   
   //Only this error will be written to the 2000 log   
   logger2.fatal("fatal!!!");  
//Send the log to mail   
   Logger logger3 = Logger.getLogger("MailLog");   
   //SMTPAppender sa = new SMTPAppender();   
   logger3.warn("warn!!!");   
   logger3.error("error!!!");   
   logger3.fatal("fatal!!!");   
  }   
 }  


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326509098&siteId=291194637