The use of log4j and log4j2 in spring MVC. MD

Source: Internet
Author: User
Tags syslog rsyslog log4j

Directory

    • First, log4j configuration
    • Second, LOG4J2 configuration

Project has been on the line for a long time, the project is using the log4j 1.x version, the original log can also be normal record, but operation and maintenance complained that your log is too large, catalina.out log output is infinite, so that some applications appear server storage alarm, so we recommend:

"Application log must be connected to the company unified log platform, if also stored in the local server, unified in the container root directory of a separate folder, folder name with the log word, log files by date or size archive, a single log file more than 20M files need to be compressed at the same time, By default, only the last one months of the log are retained, and the code implements automatic cleanup. ”

Summarize Log Management requirements:

    1. Log written to the Unified logging platform (Elk log platform);
    2. Local log files need to be archived by date or size;
    3. A single log file, such as more than 20M, needs to be compressed at archive time;
    4. Automatic cleanup log, the default retention of nearly one months log;
    5. Turn off catalina.out log output;

In view of the above requirements, I found that the log4j 1.x version is not available, and the Log4j 2.x version just can be very good to meet:

    1. Tomcat standard deployment cannot turn off Catalina.out log output through log4j configuration;
    2. Unable to automatically clean up the log, save only nearly one months log;
    3. Unable to automatically compress log files with more than 20M in the archive;

Remark: Do not upgrade log4j, how to solve the above problem?
1. Turn off Catalina.out log output via tomcat configuration.

# 直接找到Tomcat下bin/catalina.sh文件中以下代码片段:if [ -z "$CATALINA_OUT" ] ; then  CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out# 将上面的内容修改成下面内容即可:if [ -z "$CATALINA_OUT" ] ; then  CATALINA_OUT=/dev/null # 输入到/dev/null黑洞

2. Log cleanup and compression by writing server scripts and timed tasks;

The above two methods can achieve the same purpose, but the operation of the students are not willing to do so, to provide you with a Web container, the other best your program to achieve their own:)

LOG4J2 is an upgraded version of log4j, log4j2 in addition to meet the above needs, heard the performance is also better, the old project log4j upgrade to LOG4J2 cost is also low.

First, log4j configuration

Official Document: Http://logging.apache.org/log4j/1.2/apidocs

1. Maven Package Introduction
    <dependency>      <groupId>org.slf4j</groupId>      <artifactId>slf4j-api</artifactId>      <version>1.7.19</version>    </dependency>    <dependency>      <groupId>org.slf4j</groupId>      <artifactId>slf4j-log4j12</artifactId>      <version>1.7.19</version>    </dependency>    <dependency>      <groupId>log4j</groupId>      <artifactId>log4j</artifactId>      <version>1.2.17</version>    </dependency>
2. log4j.properties configuration file

LOG4J has agreed that its configuration file is under the path of the default load class, that is, the root path of classpath, so if it is eventually published under the Classpath root path, you do not need to specify a path when you use it.

# # # set log Levels # # #log4j. Rootlogger=debug,stdout,debug,error,rsyslog#log4j.rootlogger=debug,debug,error,rsyslog # # # config root logger: Set the lowest level of logging # # #log4j. category.org.springframework=errorlog4j.category.org.apache= infolog4j.logger.org.hibernate=error### output to console # # #log4j. appender.stdout= org.apache.log4j.consoleappenderlog4j.appender.stdout.target=system.outlog4j.appender.stdout.layout= ORG.APACHE.LOG4J.PATTERNLAYOUTLOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=[%P][%D{YYYY-MM-DD HH:mm:ss}][%t]% L%m%n### output to log file # # #log4j. Appender.debug=org.apache.log4j.dailyrollingfileappenderlog4j.appender.debug.file = ${ Catalina.home}/msp-logs/info.loglog4j.appender.debug.datepattern= '. ' yyyy-mm-ddlog4j.appender.debug.append=truelog4j.appender.debug.threshold=debuglog4j.appender.debug.layout= ORG.APACHE.LOG4J.PATTERNLAYOUTLOG4J.APPENDER.DEBUG.LAYOUT.CONVERSIONPATTERN=[%P][%D{YYYY-MM-DD HH:mm:ss}][%t]%l %m%n### error Output to log file # # #log4j. Appender.error=org.apache.log4j.dailyrollingfileappenderlog4j.appender.erroR.file = ${catalina.home}/msp-logs/error.loglog4j.appender.error.datepattern= '. ' yyyy-mm-ddlog4j.appender.error.append=truelog4j.appender.error.threshold=errorlog4j.appender.error.layout= Org.apache.log4j.patternlayoutlog4j.appender.error.layout.conversionpattern=[%p][%d{yyyy-mm-dd HH:mm:ss}]%l%m%n #appender the Rsyslog port is not configurable, use the default: 514log4j.appender.rsyslog= Org.apache.log4j.net.syslogappenderlog4j.appender.rsyslog.sysloghost=11.4.74.26log4j.appender.rsyslog.facility =local1log4j.appender.rsyslog.facilityprinting=truelog4j.appender.rsyslog.header= truelog4j.appender.rsyslog.layout= Org.apache.log4j.patternlayoutlog4j.appender.rsyslog.layout.conversionpattern=weixin-msp%d [%-5p] [%t]-%m%n
3. Web. XML configuration

The Web. XML configuration file adds the log4j listener, where the Webapprootkey configuration can write the corresponding log to the corresponding item, the default value is "Webapp.root", preferably defined, and the value is filled in arbitrarily, otherwise it conflicts when Tomcat deploys multiple projects.

<!-- log4j配置 --><!-- 配置文件如放默认路径,log4jConfigLocation可不配 --><context-param>    <param-name>log4jConfigLocation</param-name>    <param-value>WEB-INF/log4j.properties</param-value></context-param><context-param>    <param-name>log4jRefreshInterval</param-name>    <param-value>600000</param-value></context-param><context-param>    <param-name>webAppRootKey</param-name>    <param-value>webName.root</param-value></context-param><listener>    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class></listener>
Second, LOG4J2 configuration 1. Maven Package Introduction
        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-api</artifactId>            <version>1.7.21</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-api</artifactId>            <version>2.3</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-core</artifactId>            <version>2.3</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-slf4j-impl</artifactId>            <version>2.3</version>        </dependency>
2. Log4j2.xml configuration file
<?xml version= "1.0" encoding= "UTF-8"?><!--status Specify log4j itself (log4j2 this program) print the level of the log--><configuration status= "WARN" packages= "> <Appenders> <!--output to console configuration--<console name=" Console "target=        "System_out" > <patternlayout charset= "utf-8" pattern= "%d{yyyy-mm-dd HH:mm:ss}%class{36} [%p]%m%n"/> </Console> <!--output to log file configuration--<rollingfile name= "ErrorFile" Filename= "${sys:catalina.base}/ Logs/error.log "filepattern=" ${SYS:CATALINA.BASE}/LOGS/ERROR.LOG.%D{YYYYMMDD} "> <patternlayout charset = "Utf-8" pattern= "%d{yyyy-mm-dd HH:mm:ss}%class{36} [%p]%m%n"/> <Policies> <timebasedtriggerin Gpolicy modulate= "true"/> </Policies> </RollingFile> <rollingfile name= "Infofile" f Ilename= "${sys:catalina.base}/wx-logs/info.log" filepattern= "${sys:catalina.base}/wx-logs/info.log.%d{ YYYYMMDD} "> <patternLayout charset= "Utf-8" pattern= "%d{yyyy-mm-dd HH:mm:ss}%class{36} [%p]%m%n"/> <Policies> <timebasedtriggeringpolicy modulate= "true"/> </Policies> </RollingFile> &lt ;! --Output to log platform configuration log4j2 write log platform does not recognize AppName, I hope that facility=auth can be distinguished from other systems--<syslog name= "Syslog" format= "RFC5424" hos t= "11.4.74.26" port= "514" protocol= "UDP" appname= "Weixin-vue-api" includemdc= "true" facility = "USER" enterprisenumber= "18060" newline= "true" messageid= "Audit" mdcid= "MDC" id= "APP" Conne cttimeoutmillis= "reconnectiondelaymillis=" > <LoggerFields> <keyvaluepair key= "Thread" value= "%t"/> <keyvaluepair key= "priority" value= "%p"/> <keyvaluepai R key= "category" Value= "%c"/> <keyvaluepair key= "Exception" value= "%ex"/> <keyva Luepair key= "Message"Value= "%m"/> </LoggerFields> </Syslog> </Appenders> <!--log level: All < Trac E < Debug < Info < Warn < Error < Fatal < off.--> <Loggers> <!--only apps defined logger and introduced Ender,appender will take effect--<logger name= "error" level= "error" additivity= "false" > <!--Logger child nodes to specify        The log output to which appender, if not specified, will inherit from root by default. If specified, it will be output in the specified Appender and root appender, at which point we can set logger additivity= "false" to output only in custom Appender--and Lt Appenderref ref= "SYSLOG"/> <appenderref ref= "ErrorFile"/> </Logger> <!--Root used to refer to The root log of the project, without specifying logger separately, will be output uniformly to root--<root level= "Info" additivity= "false" > <appenderref ref= "SYSLOG"/> <appenderref ref= "Infofile"/> </Root> </loggers></configuration&gt ;
3. How to use
import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;// 普通使用private static final Logger LOGGER = LogManager.getLogger(HelloController.class);LOGGER.error("error log.");  // 会命中log4j2配置的Root项// 高级使用LogManager.getLogger("LoggerName01").error(error log.); 会命中log4j2配置的LoggerName01项LogManager.getLogger("LoggerName02").error(error log.); 会命中log4j2配置的LoggerName02项
4. By talent log file
        <RollingFile name="error_appender" fileName="${sys:catalina.base}/wx-logs/error.log" filePattern="${sys:catalina.base}/wx-logs/error-%d{yyyy-MM-dd}.log">            <PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss} [%thread] %m%n"/>            <Policies>                <TimeBasedTriggeringPolicy modulate="true" interval="1"/>            </Policies>        </RollingFile>
5. Split the log file by size
        <RollingFile name="error_appender" fileName="${sys:catalina.base}/wx-logs/error.log" filePattern="${sys:catalina.base}/wx-logs/error-%d{yyyy-MM-dd}-%i.log.gz">            <PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss} [%thread] %m%n"/>            <SizeBasedTriggeringPolicy size="100 MB" />        </RollingFile>

The use of log4j and log4j2 in spring MVC. MD

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.