Log4j more comprehensive configuration (reproduced)

This article is reproduced in http://nlslzf.iteye.com/blog/390891

1. Introduction
Log4j is an open source project of Apache. By using Log4j, we can control the destination of log information delivery to consoles, files, GUI components, and even socket servers, NT event recorders, and UNIX Syslog daemons. process, etc.; we can also control the output format of each log; by defining the level of each log information, we can control the log generation process in more detail.
Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information. The priority of the log information from high to low is ERROR, WARN, INFO, DEBUG, which are used to specify the importance of the log information; the output destination of the log information specifies whether the log will be printed to the console or a file; and the output Format controls the display of log information.

Second, the configuration file
In fact, you can also not use the configuration file at all, but configure the Log4j environment in the code. However, using configuration files will make your application more flexible.
Log4j supports two configuration file formats, one is an XML format file and the other is a properties format file. Below we introduce how to use the properties format as a configuration file:
Example:
log4j.rootLogger=INFO, 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

1. Configure the root Logger, the syntax is:
log4j.rootLogger = [ level ] , appenderName, appenderName, …
where level is the priority of logging, divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define. Log4j recommends using only four levels, the priority from high to low is ERROR, WARN, INFO, DEBUG. With the level defined here, you can control the switch to the corresponding level of log information in the application. For example, if the INFO level is defined here, all DEBUG level log information in the application will not be printed.
appenderName is to specify where the log information is output. You can specify multiple output destinations at the same time.

2. Configure the log information output destination Appender, the syntax is:
log4j.appender.appenderName = fully.qualified.name.of.appender.class
log4j.appender.appenderName.option1 = value1

log4j.appender.appenderName.option = valueN
Among them, 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 (generate a new file when the file size reaches the specified size),
org.apache.log4j.WriterAppender (send log information to any specified place in stream format)
(1).ConsoleAppender option
Threshold =WARN: 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.
Target=System.err: The default is: System.out, specify the output console
(2). FileAppender option
Threshold=WARN: Specify the lowest level of output 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.
(3).DailyRollingFileAppender option
Threshold=WARN: Specifies the lowest 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.
DatePattern='.'yyyy-ww: The file is rolled once a week, that is, a new file is generated every week. Of course, you can also specify months, weeks, days, hours and minutes. That is, the corresponding format is as follows:
  1)'.'yyyy-MM: monthly
  2)'.'yyyy-ww: weekly
  3)'.'yyyy-MM-dd: daily
  4)'.'yyyy-MM-dd -a: twice a day
  5)'.'yyyy-MM-dd-HH: every hour
  6)'.'yyyy-MM-dd-HH-mm: every minute
(4).RollingFileAppender option
Threshold=WARN: specify log The lowest level of output for 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.

3. Configure the layout of log information, the syntax is:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
...
log4j.appender.appenderName.layout.option = valueN
Among them, the layouts provided by Log4j are as follows:
org.apache.log4j.HTMLLayout (layout in HTML form),
org .apache.log4j.PatternLayout (can flexibly specify the layout pattern),
org.apache.log4j.SimpleLayout (contains the level and information string of log information),
org.apache.log4j.TTCCLayout (contains log generation time, thread, categories, etc.)

4. Output format settings
In the configuration file, you can set the log output format through log4j.appender.A1.layout.ConversionPattern.
Parameters:
%p: Priority of output log information, namely DEBUG, INFO, WARN, ERROR, FATAL,
%d: Date or time of output log time point, the default format is ISO8601, and the format can also be specified later, for example: % d{yyy MMM dd HH:mm:ss,SSS}, the output is similar: October 18, 2002 22:10:28, 921
%r: Output the number of milliseconds it took to output the log information since the application was started
%c: Output The category to which the log information belongs, usually the full name of the category
%t: output the name of the thread that generated the log event
%l: Output the location of the log event, which is equivalent to the combination of %C.%M (%F:%L), including the category name, the thread where it occurred, and the number of lines in the code. Example: Testlog4.main(TestLog4.java:10)
%x: Output the NDC (Nested Diagnostic Environment) 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 was 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 left-hand character.

3. Use in the program
Before using Log4j in the program, first import commons-logging.jar and logging-log4j-1.2.9.jar into the classpath, and put log4j.properties in the src root directory. It's ready to use next.

1. Get the logger
Using Log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:
public static Logger getLogger( String name ),
get the logger by the specified name, and create a new logger for this name if necessary. Name generally takes the name of this class, for example:
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () ) ;
Note: It is recommended to use commons-logging combined with log4j for logging
private static Log logger = LogFactory.getLog(Yourclass. class);

2. Inserting logging information (formatting logging information)
When the last two necessary steps are completed, you can easily insert logging statements with different priority levels wherever you want to log. The syntax is as follows:
Logger.debug ( Object message ) ;
Logger.info ( Object message ) ;
Logger.warn ( Object message ) ;
Logger.error ( Object message ) ;

Fourth, the more comprehensive configuration of Log4j
The simplicity of LOG4J's configuration makes it more and more popular in more and more applications: the Log4J configuration file 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. . It is enough to choose one or two to use.

Java code   Favorite code
  1. log4j.rootLogger=DEBUG,CONSOLE,A1,im     
  2. log4j.addivity.org.apache = true    
  3. # apply to console     
  4. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender     
  5. log4j.appender.Threshold=DEBUG     
  6. log4j.appender.CONSOLE.Target=System.out     
  7. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout     
  8. log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n     
  9. #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     
  10. #Apply to file     
  11. log4j.appender.FILE=org.apache.log4j.FileAppender     
  12. log4j.appender.FILE.File=file.log     
  13. log4j.appender.FILE.Append=false    
  14. log4j.appender.FILE.layout=org.apache.log4j.PatternLayout     
  15. log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n     
  16. # Use this layout for LogFactor 5 analysis     
  17. # apply to file rollback     
  18. log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender     
  19. log4j.appender.ROLLING_FILE.Threshold=ERROR     
  20. log4j.appender.ROLLING_FILE.File=rolling.log  //File location, you can also use variables ${java.home}, rolling.log     
  21. log4j.appender.ROLLING_FILE.Append= true //true: add false: override      
  22. log4j.appender.ROLLING_FILE.MaxFileSize=10KB  //The maximum size of the file     
  23. log4j.appender.ROLLING_FILE.MaxBackupIndex= 1 //Number of backups      
  24. log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout     
  25. log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n     
  26.     
  27. #Apply to socket     
  28. log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender     
  29. log4j.appender.SOCKET.RemoteHost=localhost     
  30. log4j.appender.SOCKET.Port=5001    
  31. log4j.appender.SOCKET.LocationInfo=true    
  32. # Set up for Log Facter 5    
  33. log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout     
  34. 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     
  35.     
  36. # Log Factor 5 Appender     
  37. log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender     
  38. log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000    
  39. # send log to email     
  40. log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender     
  41. log4j.appender.MAIL.Threshold=FATAL     
  42. log4j.appender.MAIL.BufferSize=10    
  43. log4j.appender.MAIL.From=web@www.wuset.com     
  44. log4j.appender.MAIL.SMTPHost=www.wusetu.com     
  45. log4j.appender.MAIL.Subject=Log4J Message     
  46. log4j.appender.MAIL.To=web@www.wusetu.com     
  47. log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout     
  48. log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n     
  49. # for database     
  50. log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender     
  51. log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test     
  52. log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver     
  53. log4j.appender.DATABASE.user=root     
  54. log4j.appender.DATABASE.password=     
  55. log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES (’[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n’)     
  56. log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout     
  57. log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n     
  58.     
  59. log4j.appender.A1 = org.apache.log4j.DailyRollingFileAppender     
  60. log4j.appender.A1.File=SampleMessages.log4j     
  61. log4j.appender.A1.DatePattern=yyyyMMdd-HH’.log4j’     
  62. log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout     
  63. #customAppender     
  64. log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender     
  65. log4j.appender.im.host = mail.cybercorlin.net     
  66. log4j.appender.im.username = username     
  67. log4j.appender.im.password = password     
  68. log4j.appender.im.recipient = corlin@cybercorlin.net     
  69. log4j.appender.im.layout=org.apache.log4j.PatternLayout     
  70. log4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n   

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327068995&siteId=291194637