Log4j 2.3简易教程 - log4j2.xml

时间:2022-05-27 23:14:46

Log4j版本:2.3
操作系统:Ubuntu 13.04
JDK版本:1.7.0_75

小例子:
在Main类中,使用log4j日志功能。

package main;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {
public static void main(String args[]){
Logger Log = LogManager.getLogger(Main.class.getName());
Log.info("this is the info");
Log.warn("this is the warn info");
Log.error("this is the error info");
Log.fatal("this is the fatal info");
Log.trace("enter Main.test()");
//new Main().test();
Log.trace("exit Main.test()");
}
}

如果我直接这样运行的话,输出结果为:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
22:22:01.774 [main] ERROR main.Main - this is the error info
22:22:01.775 [main] FATAL main.Main - this is the fatal info
最上面是一条错误信息,说没有log4j2配置文件,然后使用了默认的配置,日志仅仅把error及以上级别的信息输出到控制台。

然后在官网上发现,log4j2配置有四种方式

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

  • Through a configuration file written in XML, JSON, or YAML.
  • Programmatically, by creating a ConfigurationFactory and Configuration implementation.
  • Programmatically, by calling the APIs exposed in the Configuration interface to add components to the default configuration.
  • Programmatically, by calling methods on the internal Logger class.

我使用的是第一种方法,即配置log4j2.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN"> <!-- 这个status是控制系统信息的输出级别 -->
<Appenders>
<Console name="Console" target="SYSTEM_OUT"> <!-- 将日志信息从控制台输出 -->
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" filename="./mylog.log" append="true"> <!-- 将日志信息写入日志文件 -->
<PatternLayout pattern="%d %p %C{1.} [%t] %m%n"/>
</File>
</Appenders>
<Loggers>
<!-- Root level 是设置全局的信息显示级别,这里设置为error表示:error及以上的信息将被输出
信息的级别大小为:debug < info < warn < error < fatal -->

<Root level="trace">
<AppenderRef ref="Console"/> <!-- 仅有上述的Appenders配置还不够,这里还不能少,少了就不会在控制台输出 -->
<AppenderRef ref="File"/> <!-- 仅有上述的Appenders配置还不够,这里还不能少,少了就不会写入文件,但会创建文件 -->
</Root>
<!-- 可以专门为某个类指定信息级别,例如为main包下的Main类指定信息级别为trace -->
<!-- <Logger name="main.Main" level="trace" /> -->
</Loggers>
</Configuration>


值得一提的是,log4j2.xml应该放在src目录下,否则系统会提示找不到配置文件。


节点这里配置了name和target,其他还有如下属性

http://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/ConsoleAppender.html


layout - The layout to use (required).
filter - The Filter or null.
targetStr - The target (“SYSTEM_OUT” or “SYSTEM_ERR”). The default is “SYSTEM_OUT”.
follow - If true will follow changes to the underlying output stream.
name - The name of the Appender (required).
ignore - If “true” (default) exceptions encountered when appending events are logged; otherwise they are propagated to the caller.


Appender用得比较多的还有FileAppender,FileAppender的属性有如下

http://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/FileAppender.html


fileName - The name and path of the file.
append - “True” if the file should be appended to, “false” if it should be overwritten. The default is “true”.
locking - “True” if the file should be locked. The default is “false”.
name - The name of the Appender.
immediateFlush - “true” if the contents should be flushed on every write, “false” otherwise. The default is “true”.
ignore - If “true” (default) exceptions encountered when appending events are logged; otherwise they are propagated to the caller.
bufferedIo - “true” if I/O should be buffered, “false” otherwise. The default is “true”.
bufferSizeStr - buffer size for buffered IO (default is 8192).
layout - The layout to use to format the event. If no layout is provided the default PatternLayout will be used.
filter - The filter, if any, to use.
advertise - “true” if the appender configuration should be advertised, “false” otherwise.
advertiseUri - The advertised URI which can be used to retrieve the file contents.
config - The Configuration


以下是官方给出的一个log4j2.xml严格语法的样本:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug" strict="true" name="XMLConfigTest"
packages="org.apache.logging.log4j.test">

<Properties>
<Property name="filename">target/test.log</Property>
</Properties>
<Filter type="ThresholdFilter" level="trace"/>

<Appenders>
<Appender type="Console" name="STDOUT">
<Layout type="PatternLayout" pattern="%m MDC%X%n"/>
<Filters>
<Filter type="MarkerFilter" marker="FLOW" onMatch="DENY" onMismatch="NEUTRAL"/>
<Filter type="MarkerFilter" marker="EXCEPTION" onMatch="DENY" onMismatch="ACCEPT"/>
</Filters>
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n"/><!-- class and line number -->
<Filters>
<Filter type="MarkerFilter" marker="FLOW" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<Filter type="MarkerFilter" marker="EXCEPTION" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout">
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</Layout>
</Appender>
<Appender type="List" name="List">
</Appender>
</Appenders>

<Loggers>
<Logger name="org.apache.logging.log4j.test1" level="debug" additivity="false">
<Filter type="ThreadContextMapFilter">
<KeyValuePair key="test" value="123"/>
</Filter>
<AppenderRef ref="STDOUT"/>
</Logger>

<Logger name="org.apache.logging.log4j.test2" level="debug" additivity="false">
<AppenderRef ref="File"/>
</Logger>

<Root level="trace">
<AppenderRef ref="List"/>
</Root>
</Loggers>

</Configuration>

总结:
简单使用log4j有3步:

  1. 配置log4j2.xml文件,并放到src(即CLASSPATH)目录下
  2. 创建Log对象
Logger Log = LogManager.getLogger(Main.class.getName());//这个Main类指的是当前类
  1. 调用方法操作
        Log.info("this is the info");
Log.warn("this is the warn info");
Log.error("this is the error info");
Log.fatal("this is the fatal info");
Log.trace("enter Main.test()");
Log.trace("exit Main.test()");