1. Log4j2的导入
首先到http://logging.apache.org/log4j/2.x/download.html 上下载最新的log4j2的jar包,然后再eclipse中加入log4j-api-2.0-beta2.jar和log4j-core-2.0- beta2.jar,需要注意的是不要将所有jar都导入工程造成不必要的混乱。
2. 测试用例
log4j 2.0的使用非常简单,只要用LogManager的getLogger函数获取一个logger,就可以使用logger记录日志,代码如下:
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- public class HelloLog4j {
- private static Logger logger = LogManager.getLogger("HelloLog4j");
- public static void main(String[] args) {
- MyApplication myApplication = new MyApplication();
- logger.entry();
- logger.info("Hello, World!");
- myApplication.doIt();
- logger.error("Hello, World!");
- logger.exit();
- }
- }
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- public class MyApplication {
- static Logger logger = LogManager.getLogger(MyApplication.class.getName());
- public boolean doIt() {
- logger.entry(); //Log entry to a method
- logger.error("Did it again!"); //Log a message object with the ERROR level
- logger.exit(); //Log exit from a method
- return false;
- }
- }
运行程序,输出结果为:
- 16:10:28.672 [main] ERROR MyApplication - Did it again!
- 16:10:28.672 [main] ERROR HelloLog4j - Hello, World!
注意到,输出的log都是在ERROR level上的,log4j定义了8个级别的log(除去OFF和ALL,可以说分为6个级别),优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL。如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。从我们实验的结果可以看出,log4j默认的优先级为ERROR或者WARN(实际上是ERROR)。
3. 配置文件
log4j是apache的一个开源项目,在写这篇博客的时候已经发布了2.0的beta版本,首先需要注意的是,log4j 2.0与以往的1.x有一个明显的不同,其配置文件只能采用.xml, .json或者 .jsn。在默认情况下,系统选择configuration文件的优先级如下:(classpath为scr文件夹)
- classpath下名为 log4j-test.json 或者log4j-test.jsn文件
- classpath下名为 log4j2-test.xml
- classpath下名为 log4j.json 或者log4j.jsn文件
- classpath下名为 log4j2.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration status="OFF">
- <appenders>
- <Console name="Console" target="SYSTEM_OUT">
- <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
- </Console>
- </appenders>
- <loggers>
- <root level="trace">
- <appender-ref ref="Console"/>
- </root>
- </loggers>
- </configuration>
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration status="OFF">
- <appenders>
- <Console name="Console" target="SYSTEM_OUT">
- <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
- </Console>
- </appenders>
- <loggers>
- <logger name="com.relin.HelloLog4j" level="error" additivity="false">
- <appender-ref ref="Console"/>
- </logger>
- <root level="trace">
- <appender-ref ref="Console"/>
- </root>
- </loggers>
- </configuration>
此时,HelloLog4j则会在error级别上输出log,而其他类则会在trace级别上输出log。需要注意的是 additivity选项,如果设置为true(默认值)则HelloLog4j的log会被打印两次,第二次打印是由于HelloLog4j同时也满足root里面定义的trace
4. 其他特征
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration status="error">
- <appenders>
- <Console name="Console" target="SYSTEM_OUT">
- <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
- <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
- </Console>
- <File name="log" fileName="target/test.log" append="false">
- <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
- </File>
- <RollingFile name="RollingFile" fileName="logs/app.log"
- filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
- <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
- <SizeBasedTriggeringPolicy size="500 MB" />
- </RollingFile>
- </appenders>
- <loggers>
- <root level="trace">
- <appender-ref ref="RollingFile"/>
- <appender-ref ref="Console"/>
- </root>
- </loggers>
- </configuration>
扩展组件
1,ConsoleAppender
输出结果到System.out或是System.err。
2,FileAppender
输出结果到指定文件,同时可以指定输出数据的格式。append=“false”指定不追加到文件末尾
3,RollingFileAppender
自动追加日志信息到文件中,直至文件达到预定的大小,然后自动重新生成另外一个文件来记录之后的日志。
过滤标签
1,ThresholdFilter
用来过滤指定优先级的事件。
2,TimeFilter
设置start和end,来指定接收日志信息的时间区间。
按天存储日志文件配置方法
自定义日志配置文件路径
public void init() throws ServletException { String configRoot = this.getInitParameter("configRoot"); String log4j2Config = configRoot + File.separator + this.getInitParameter("log4j2Config"); File file = new File(log4j2Config); try { LoggerContext context =(LoggerContext)LogManager.getContext(false); context.setConfigLocation(file.toURI()); //重新初始化Log4j2的配置上下文 context.reconfigure(); } catch (MalformedURLException e) { e.printStackTrace(); } //todo: 这里拿到的logger,已经是按新配置文件初始化的了 logger = LogManager.getLogger(DefaultInitServlet.class); }
相应的,只要在web.xml配置这个InitServlet,并提供configRoot和log4j2Config两个路径即可(也可以不要配置configRoot,而是通过System.getProperty("user.dir")来获取应用的运行目录,对tomcat而言,这个目录就是tomcat/bin,其他如命令行的应用,就是bat/sh的所在目录)
web.xml
引用
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>test.InitServlet</servlet-class>
<load-on-startup>0</load-on-startup>
<init-param>
<!-- 配置文件根目录 -->
<param-name>configRoot</param-name>
<param-value>d://config</param-value>
</init-param>
<init-param>
<!-- log4j2配置文件相对路径 -->
<param-name>log4j2Config</param-name>
<param-value>log4j2/log4j2.xml</param-value>
</init-param>
</servlet>
不同级别日志输出到不同日志文件
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="off" monitorInterval="1800"> <Properties> <Property name="log-path">d://logs</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36}.%M()/%L - %msg%xEx%n"/> </Console> <File name="app_debug" fileName="${log-path}/app/debug.log" append="false"> <Filters> <ThresholdFilter level="info" onMatch="DENY" onMismatch="NEUTRAL"/> <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="NEUTRAL"/> </Filters> <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/> </File> <File name="app_info" fileName="${log-path}/app/info.log" append="false"> <Filters> <ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> </Filters> <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/> </File> <File name="app_error" fileName="${log-path}/app/error.log" append="false"> <Filters> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/> </Filters> <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36}.%M()/%L - %msg%xEx%n"/> </File> </Appenders> <Loggers> <Logger name="com.test.app" level="trace" additivity="false"> <appender-ref ref="Console"/> <appender-ref ref="app_debug"/> <appender-ref ref="app_info"/> <appender-ref ref="app_error"/> </Logger> </Loggers> </configuration>
主要是要理解ThresholdFilter的onMatch/onMismatch的三个选项值:ACCEPT/DENY/NEUTRAL,其实,根据字面意思,也很好理解。
重要的是,如果有多个ThresholdFilter,那么Filters是必须的,同时在Filters中,首先要过滤不符合的日志级别,把不需要的首先DENY掉,然后再ACCEPT需要的日志级别,这个次序不能搞颠倒。
log4j2指定日志文件路径到工程路径
http://logging.apache.org/log4j/2.x/manual/lookups.html
System Properties Lookup
As it is quite common to define values inside and outside the application by using System Properties, it is only natural that they should be accessible via a Lookup. As system properties are often defined outside the application it would be quite common to see something like:
- <Appenders>
- <File name="ApplicationLog" fileName="${sys:logPath}/app.log"/>
- </Appenders>
2、直接随web项目路径:
Web Lookup
The WebLookup allows applications to retrieve variables that are associated with the ServletContext. In addition to being able to retrieve various fields in the ServletContext, WebLookup supports looking up values stored as attributes or configured as initialization parameters. The following table lists various keys that can be retrieved:
Key | Description |
---|---|
attr.name | Returns the ServletContext attribute with the specified name |
contextPath | The context path of the web application |
effectiveMajorVersion | Gets the major version of the Servlet specification that the application represented by this ServletContext is based on. |
effectiveMinorVersion | Gets the minor version of the Servlet specification that the application represented by this ServletContext is based on. |
initParam.name | Returns the ServletContext initialization parameter with the specified name |
majorVersion | Returns the major version of the Servlet API that this servlet container supports. |
minorVersion | Returns the minor version of the Servlet API that this servlet container supports. |
rootDir | Returns the result of calling getRealPath with a value of "/". |
serverInfo | Returns the name and version of the servlet container on which the servlet is running. |
servletContextName | Returns the name of the web application as defined in the display-name element of the deployment descriptor |
Any other key names specified will first be checked to see if a ServletContext attribute exists with that name and then will be checked to see if an initialization parameter of that name exists. If the key is located then the corresponding value will be returned.
- <Appenders>
- <File name="ApplicationLog" fileName="${web:rootDir}/app.log"/>
- </Appenders>
转:http://blog.csdn.net/lrenjundk/article/details/8178875
转:http://blog.163.com/m15876524871_1/blog/static/196818147201410652443288/