log4j use and detailed configuration instructions

Source: Internet
Author: User
Tags html form xml example truncated log4j
first, a simple introduction to the use of log4j steps

The whole is divided into the following steps: 1, the introduction of Log4j-*.*jar, the JAR package 2, add a configuration file (Log4j.xml or Log4j.properties), 3, the Packaging Log tool class in the business use. This is the traditional use of the steps, but we can directly with the Lombok wrapped Log tool class, the specific steps:


1.1 Introducing Jar packs

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactid>lombok</ artifactid>
            <version>1.16.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            < Version>1.7.6</version>
        </dependency>

1.2 Add configuration file

Configuration files We can use Log4j.xml or log4j.properties, if both exist, the default load is Log4j.xml configuration. Add the configuration file directly below the Classpath (for example, the resources path).


Log4j.xml Example One:

<?xml version= "1.0" encoding= "GBK"?> <! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" > <log4j:configuration xmlns:log4j= "http://jakarta.apache.org/" log4j/"> <!--output log to console Consoleappender--> <appender name=" console "class=" Org.apache.lo G4j. Consoleappender "> <param name=" Threshold "value=" info "></param> <layout class=" org.a  
        Pache.log4j.TTCCLayout "> <param name=" Conversionpattern "value=" Ttcclayout "></param> </layout> </appender> <!--output log to file per day a file--> <appender name= "Dailyrollingfil E "class=" Org.apache.log4j.DailyRollingFileAppender "> <param name=" Threshold "value=" info "&GT;&LT;/PARAM&G  
        T <param name= "Immediateflush" value= "true" ></param> <param name= "File" value= "c:/logs/dailyrolling File.log "></param> <param name=" Datepattern "value=". yyyY-mm-dd '. Log ' "></param> <layout class=" Org.apache.log4j.PatternLayout "> <param n Ame= "Conversionpattern" value= "[%d{yyyy-mm-dd hh:mm:ss\}%-5p] [%t] {%c:%l}-%m%n" ></param> </layout&  
    Gt </appender> <!--output log to file size to a specified size to produce a new file--> <appender name= "Railyfile" class= "  
        Org.apache.log4j.RollingFileAppender "> <param name=" File "value=" C:/logs/railyfile.log "></param> <param name= "Immediateflush" value= "true"/> <param "name=" Threshold "info" value= m> <param name= "Append" value= "true" ></param> <param name= "maxfilesize" value= "30KB" ></param> <param name= "Maxbackupindex" value= "></param> <layout class=" org . apache.log4j.PatternLayout "> <param name=" Conversionpattern "value=" [%d{yyyy-mm-dd hh:mm:ss\}%-5p] [ %t] {%c:%l}-%m%n "></param> </layout> </appender> <!--output log to file--> <appender Name= "File" class= "Org.apache.log4j.FileAppender" > <param name= "file" value= "C:/logs/file.log" ></pa ram> <param name= "Threshold" value= "info" ></param> <layout class= "ORG.APACHE.LOG4J.P" Atternlayout "> <param name=" Conversionpattern "value=" [%d{yyyy-mm-dd hh:mm:ss\}%-5p] [%t] {%c:%L}-%m% N "></param> </layout> </appender> <!--define the global log output level, but the configuration at the output destination  
        The specific output-level priority configured in is higher than the global-defined priority. If the <param name= "Threshold" value= "info" &GT;&LT;/PARAM&GT is defined in Railyfile, then the information above the info level will be exported-->       
        T <priority value= "Debug"/> <appender-ref ref= "console"/> <appender-ref ref= "Dai Lyrollingfile "/> <appender-ref ref=" Railyfile "/> <appenDer-ref ref= "file"/> </root> </log4j:configuration>    


Log4j.xml Example Two: (You can print the console warn/error level log red to differentiate the info level)

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" > <log4j:configuration xmlns:log4j= ' http://jakarta.apache.org/ log4j/' > <!--warn,error,fatal levels are displayed in red. Debug,info, default color--> <appender name= "Console-warn" class= "Org.apache.log4j.ConsoleAppender" > <para M name= "target" value= "System.err"/> <layout class= "Org.apache.log4j.PatternLayout" > <para
        M name= "Conversionpattern" value= "[%d{yyyy-mm-dd hh:mm:ss,sss}%-5p] [%t]%c{2\}%l-%m%n"/> </layout> <filter class= "Org.apache.log4j.varia.LevelRangeFilter" > <param name= "levelmin" value= "Warn"/&
            Gt <param name= "Levelmax" value= "fatal"/> <param name= "Acceptonmatch" value= "false"/> </fi lter> </appender> <appender name= "Console-info" class= "Org.apache.log4j.ConsoleAppender" > & Lt;param name= "target" value= "SYSTEM.OUT "/> <layout class=" org.apache.log4j.PatternLayout "> <param name=" Conversionpattern "Valu E= "[%d{yyyy-mm-dd hh:mm:ss,sss}%-5p] [%t]%c{2\}%l-%m%n"/> </layout> <filter class= "Org.ap Ache.log4j.varia.LevelRangeFilter "> <param name=" levelmin "value=" Debug "/> <param name = "Levelmax" value= "info"/> <param name= "Acceptonmatch" value= "false"/> </filter> &L t;/appender> <appender name= "Activexappender" class= "Org.apache.log4j.DailyRollingFileAppender" > ;p Aram Name= "File" value= ". /log/tacserviceprovider/tacserviceprovider.log "/> <param name=" Datepattern "value=" '. Yyyy-mm-dd '. Log ' "/> <layout class=" org.apache.log4j.PatternLayout "> <param name=" Conversio 
    Npattern "Value=" [%d{yyyy-mm-dd hh:mm:ss,sss}%-5p] [%t]%c{2\}%l-%m%n "/> </layout> </appender> <root> <priority value= "Debug"/> <appender-ref ref= "Console-warn"/> T;appender-ref ref= "Console-info"/> <appender-ref ref= "Activexappender"/> </root> </log4j:co
 Nfiguration>


log4j.properties Example One:

#配置全局日志级别, with output location items
log4j.rootlogger=info, console, Rollingfile
#控制台日志配置项
log4j.appender.console= Org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.patternlayout
log4j.appender.console.layout.conversionpattern=%d [%t]%-5p%c---%m%n
#RollingFile日志配置项
Log4j.appender.rollingfile=org.apache.log4j.rollingfileappender
log4j.appender.rollingfile.file= Example.log
log4j.appender.rollingfile.maxfilesize=100kb
log4j.appender.rollingfile.maxbackupindex=1
Log4j.appender.rollingfile.layout=org.apache.log4j.patternlayout
log4j.appender.rollingfile.layout.conversionpattern=%p%t%c-%m%n
#指定特定包下的日志级别
Log4j.logger.com.acfun=warn


log4j.properties Example II: (most fully configured, you can extract the required parts)

#OFF, Systemout,logfile,logdailyfile,logrollingfile,logmail,logdb,all Log4j.rootlogger =ALL,systemOut,logFile, 
Logdailyfile,logrollingfile,logmail,logdb #输出到控制台 log4j.appender.systemOut = Org.apache.log4j.ConsoleAppender 
Log4j.appender.systemOut.layout = Org.apache.log4j.PatternLayout 
Log4j.appender.systemOut.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd hh:mm:sss}][%l]%n%m%n 
Log4j.appender.systemOut.Threshold = DEBUG Log4j.appender.systemOut.ImmediateFlush = TRUE Log4j.appender.systemOut.Target = System.out #输出到文件 log4j.appender.logFile = Org.apache.log4j.FileAppender Log4j.appe Nder.logFile.layout = Org.apache.log4j.PatternLayout Log4j.appender.logFile.layout.ConversionPattern = [%-5p][%-22d {YYYY/MM/DD HH:mm:ssS}] 
[%l]%n%m%n log4j.appender.logFile.Threshold = DEBUG Log4j.appender.logFile.ImmediateFlush = TRUE Log4j.appender.logFile.Append = TRUE Log4j.appender.logFile.File =.. /struts2/webroot/log/file/log4j_struts.log log4j.appender.logFile.Encoding = UTF-8 #按DAtepattern output to file Log4j.appender.logDailyFile = Org.apache.log4j.DailyRollingFileAppender 
Log4j.appender.logDailyFile.layout = Org.apache.log4j.PatternLayout 
Log4j.appender.logDailyFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd hh:mm:sss}][%l]%n%m%n 
Log4j.appender.logDailyFile.Threshold = DEBUG Log4j.appender.logDailyFile.ImmediateFlush = TRUE Log4j.appender.logDailyFile.Append = TRUE Log4j.appender.logDailyFile.File =.. /struts2/webroot/log/dailyfile/log4j_struts Log4j.appender.logDailyFile.DatePattern = '. ' yyyy-mm-dd-hh-mm '. Log ' log4j.appender.logDailyFile.Encoding = UTF-8 #设定文件大小输出到文件 log4j.appender.logRollingFile = Org. 
Apache.log4j.RollingFileAppender log4j.appender.logRollingFile.layout = org.apache.log4j.PatternLayout 
Log4j.appender.logRollingFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/mm/dd hh:mm:sss}][%l]%n%m%n 
Log4j.appender.logRollingFile.Threshold = DEBUG Log4j.appender.logRollingFile.ImmediateFlush = TRUE Log4j.appender.logRollingFile.Append =TRUE log4j.appender.logRollingFile.File =.. 
/struts2/webroot/log/rollingfile/log4j_struts.log log4j.appender.logRollingFile.MaxFileSize = 1MB Log4j.appender.logRollingFile.MaxBackupIndex = log4j.appender.logRollingFile.Encoding = UTF-8 #用Email发送日志 Log4j.ap 
Pender.logmail = Org.apache.log4j.NET.SMTPAppender Log4j.appender.logMail.layout = org.apache.log4j.HTMLLayout 
Log4j.appender.logMail.layout.LocationInfo = TRUE Log4j.appender.logMail.layout.Title = Struts2 Mail LogFile Log4j.appender.logMail.Threshold = DEBUG Log4j.appender.logMail.SMTPDebug = FALSE Log4j.appender.logMail.SMTPHost = smtp.163.com Log4j.appender.logMail.From = xly3000@163.com log4j.appender.logMail.To = xly3000@gmail.com # 
Log4j.appender.logMail.Cc = xly3000@gmail.com #log4j. appender.logMail.Bcc = xly3000@gmail.com 
Log4j.appender.logMail.SMTPUsername = xly3000 Log4j.appender.logMail.SMTPPassword = 1234567 Log4j.appender.logMail.Subject = log4j Log Messages #log4j. appender.logMail.BufferSize = 1024 #log4j. Appender.logMail.SMTPAuth = TRUE #将日志登录到MySQL数据库 Log4j.appender.logDB = Org.apache.log4j.jdbc.JDBCAppender L 
Og4j.appender.logDB.layout = Org.apache.log4j.PatternLayout Log4j.appender.logDB.Driver = Com.mysql.jdbc.Driver 
Log4j.appender.logDB.URL = jdbc:mysql://127.0.0.1:3306/xly Log4j.appender.logDB.User = root Log4j.appender.logDB.Password = 123456 LOG4J.APPENDER.LOGDB.SQL = INSERT intot_log4j (project_name,create_date,level, Category,file_name,thread_name,line,all_category,message) VALUES (' Struts2 ', '%d{yyyy-mm-ddhh:mm:ss} ', '%p ', '%c ', ' %F ', '%t ', '%l ', '%l ', '%m '


1.3 using log4j

Because we combine the Lombok, we can use it to wrap the log tool directly. Just call the annotation "@Slf4j" above the class, and then you can use Log.info ("") in the class and so on.

Instance:

Import lombok.extern.slf4j.Slf4j;

/**
 * Created by Wangzhipeng on 2017/6/11.
 * *
@Slf4j public
class Testlog4j {public
  static void Main (string[] args) {
    log.info ("Hello World");
  }
}

second, the key to explain the meaning of the log4j configuration

2.1 First a copy of the main configuration item description

1. Configure Root Logger


Syntax: Log4j.rootlogger = [level], appenderName1, appenderName2,...

Level: Defines the global log output levels, but the specific output level priority configured in the output destination configuration is higher than the globally defined priority, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or the level you define. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG.

Appendername: is to specify where the log information is exported. You can specify multiple output destinations at the same time. For example: LOG4J.ROOTLOGGER=INFO,A1,B2,C3


2, the type of output level


Off, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, all

Off to the highest level log information is turned off

FATAL is a serious event error that may cause application abort

Error is a critical error, mostly a program bug.

WARN as a general warning, such as session loss

Info for general information to be displayed, such as login logout

Debug is debugging information for the program

TRACE is a finer-grained event information than debug

All to lowest level, all levels of log will open


3, configuration 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 (Generate a log file every day)

4.org.apache.log4j.rollingfileappender (a new file is generated when the file size reaches a specified size)

5.org.apache.log4j.writerappender (send log information to any specified place in streaming format)

4, configuration log Information format


Log4j.appender.appenderName.layout =fully.qualified.name.of.layout.class

1.org.apache.log4j.htmllayout (layout in HTML form),

2.org.apache.log4j.patternlayout (You can specify layout patterns flexibly),

3.org.apache.log4j.simplelayout (The level and information string that contains the log information),

4.org.apache.log4j.ttcclayout (contains information about the time, thread, category, and so on that the log was generated)

5, console options


Threshold=debug: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.

Target=system.err: By default: System.out, specify output console

Fileappender Options

THRESHOLD=DEBUF: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.

File=mylog.txt: Specifies the message output to the Mylog.txt file.

Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.

Rollingfileappender Options

Threshold=debug: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be immediately exported.

File=mylog.txt: Specifies the message output to the Mylog.txt file.

Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.

MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches that size, it scrolls automatically, moving the original content to the Mylog.log.1 file.

maxbackupindex=2: Specifies the maximum number of scrolling files that can be produced.

log4j.appender.a1.layout.conversionpattern=%-4r%-5p%d{yyyy-mm-ddhh:mm:sss}%c%m%n

6. The meaning of several symbols represented in the log Information format:


-X: Left-aligned when x information is output;

%p: Output log information priority, i.e. Debug,info,warn,error,fatal,

%d: the date or time of the output log point of time, the default format is ISO8601, or the format can be specified thereafter, for example:%d{yyymmm dd hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28,921

%r: The number of milliseconds to output from the application boot to the output of this log information

%c: The class that the output log information belongs to, usually the full name of the class in which it is located

%t: Output The name of the thread that generated the log event

%l: The location of the output log event, equivalent to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main (testlog4.java:10)

%x: The NDC (nested diagnostics environment) associated with the current line threads relative, especially in multiple client multi-threaded applications such as Java Servlets.

Percent%: output a "%" character

%F: The name of the file where the output log message was generated

%l: line number in output code

%M: The message specified in the output code, the resulting log specific information

%n: Output a carriage return line break, Windows platform is "/r/n", UNIX platform is "/n" Output log message Wrapping

You can control the minimum width, the maximum width, and the alignment of text by adding modifiers between% and pattern characters.

Such as:

1)%20c: Specifies the name of the output category, the minimum width is 20, and if the category name is less than 20, the default is right-aligned.

2)%-20c: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.

3)%.30c: Specifies the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more characters truncated, but less than 30 words will not have spaces.

4)%20.30c: If the name of the category is less than 20, the space is filled and right-aligned, and if its name is longer than 30 characters, it is truncated from the character that is farther from the left.


2.2 A comprehensive configuration note (if the above main configuration items do not have what you need to see the instructions below)

################################################################################
#① configures the root logger with the following syntax:
#
#log4j. Rootlogger = [Level],appendername,appendername2,...
#level是日志记录的全局优先级 (below the configured priority in the configuration of the output destination below), divided into Off,trace,debug,info,warn,error,fatal,all
# #Log4j建议只使用四个级别, priority from low to High is debug,info,warn,error
#通过在这里定义的级别, you can control the switch to the corresponding level of log information in your application
#比如在这里定义了INFO级别, all debug-level log information in the application will not be printed
#appenderName就是指定日志信息输出到哪个地方. Multiple output purposes can be specified at the same time
################################################################################
################################################################################
#② Configuration log information output destination Appender, its syntax is:
#
#log4j. Appender.appendername = Fully.qualified.name.of.appender.class
#log4j. Appender.appenderName.optionN = Valuen
#
#Log4j提供的appender有以下几种:
#1) Org.apache.log4j.ConsoleAppender (output to console)
#2) Org.apache.log4j.FileAppender (output to file)
#3) org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
#4) Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches a specified size)
#5) Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
#
#1) consoleappender Option Properties
#-threshold = DEBUG: Specifies the lowest level of output for log messages
#-immediateflush = true: The default value is true, all messages are immediately exported
#-target = System.err: Default value System.out, output to console (Err is red, out is black)
#
#2) fileappender Option Properties
#-threshold = INFO: Specifies the lowest level of output for log messages
#-immediateflush = true: The default value is true, all messages are immediately exported
#-file = C:\log4j.log: Specify message output to C:\log4j.log file
#-append = false: Default value True, append message to specified file, FALSE to overwrite the specified file contents
#-encoding = UTF-8: You can specify a file encoding format
#
#3) dailyrollingfileappender Option Properties
#-threshold = WARN: Specifies the lowest level of output for log messages
#-immediateflush = true: The default value is true and all messages are immediately exported
#-file = C:\log4j.log: Specify message output to C:\log4j.log file
#-append = false: The default value is true to append the message to the specified file, FALSE to overwrite the specified file contents
#-datepattern= '. ' YYYY-WW: Scrolls the file once a week, that is, a new file is generated each week. You can also use the following parameters:
#              '.' YYYY-MM: Monthly
#              '.' YYYY-WW: Weekly
#              '.' YYYY-MM-DD: Every day
#              '.' Yyyy-mm-dd-a: two times a day
#              '.' YYYY-MM-DD-HH: Per hour
#              '.' YYYY-MM-DD-HH-MM: Per minute
#-encoding = UTF-8: You can specify a file encoding format
#
#4) rollingfileappender Option Properties
#-threshold = ERROR: Specifies the lowest level of output for log messages
#-immediateflush = true: The default value is true and all messages are immediately exported
#-file = c:/log4j.log: Specify message output to C:/log4j.log file
#-append = false: The default value is true to append the message to the specified file, FALSE to overwrite the specified file contents

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.