Log4j2 Tips (For WebApp)

Environment

JDK 1.6.0.45
Log4j2 2.3
Tomcat 7
Servlet 2.5

Maven Dependency

Log4j2 (2.3) 基本Lib
org.apache.logging.log4j
log4j-core
log4j-api
log4j-web

如果其他Lib有使用到Log4j 1.x, 需加上
org.apache.logging.log4j
log4j-1.2-api

如果有使用cxf Logging, 需加上
org.apache.logging.log4j
log4j-slf4j-impl

web.xml

<context-param>
 <param-name>log4jConfiguration</param-name>
 <param-value>classpath:config/log4j2-xxx.xml</param-value>
</context-param>

<listener>
 <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

log4j2-xxx.xml : Daily Rolling, Zip File

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Configuration status="info" name="MyService">
 
 <Properties>
  <Property name="baseDir">./logs</Property>
 </Properties>
 
 <Appenders>
  <Console name="Console" target="SYSTEM_OUT">
   <PatternLayout pattern="%d{DEFAULT} %-5level [%logger{36}][Line:%L] - %msg%n" />
  </Console>

  <RollingRandomAccessFile name="mylog" fileName="${baseDir}/mylog.log" filePattern="${baseDir}/mylog.log.%d{yyyyMMdd}.gz">
   <PatternLayout pattern="%d{DEFAULT} %-5level [%logger{36}][Line:%L] - %msg%n" />
   <Policies>
    <TimeBasedTriggeringPolicy />
   </Policies>
  </RollingRandomAccessFile>
 </Appenders>

 <Loggers>
  <Logger name="com.mypackage.ws" level="debug"/>
  <Logger name="org.apache.cxf.services" level="debug"/>
 
  <!-- Turn on to trace bug -->
  <Logger name="org.apache.cxf" level="off"/>
  <Logger name="org.springframework" level="off"/>
  <Logger name="org.springframework.jdbc" level="off"/>

  <Root level="debug">
   <AppenderRef ref="Console" />
   <AppenderRef ref="mylog" />
  </Root>
 </Loggers>
</Configuration>

Reference

http://logging.apache.org/log4j/2.x/manual/index.html

http://logging.apache.org/log4j/2.x/maven-artifacts.html

https://logging.apache.org/log4j/2.x/manual/appenders.html

http://do.whileloop.org/2014/02/14/log4j-rolling-file-appenders-in-windows/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s