Log4j2的XML和properties配置方式

1、把log4j2相关的jar包导入到WEB-INF的lib目录下
log4j-api-2.6.2.jar
log4j-core-2.6.2.jar
2、在src目录下添加log4j2的配置文件
(1)log4j2.xml配置文件,以下是一个把日志输出到控制台和保存在文件中的配置文件


<Configuration status="warn" name="MyApp">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">    
            <ThresholdFilter level="debug"/>    
            <PatternLayout pattern="%m%n"/>    
        Console>    
        <File name="log" fileName="e:\\test1.log" append="true">
            <ThresholdFilter level="error"/>
            <PatternLayout pattern="%d-%m%n"/>    
        File>  
    appenders>

    <loggers>
        <root level="debug">
            <appender-ref ref="Console">appender-ref>
            <appender-ref ref="log">appender-ref>
        root>
    loggers>
Configuration>

如果需要复杂一些的请参考:http://www.cnblogs.com/hanfight/p/5721855.html

(2)log4j2.properties配置文件,功能同上

status = warn
name = MyApp

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n

appender.rolling.type = File
appender.rolling.name = log
appender.rolling.append = true
appender.rolling.fileName = e:\\test1.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d-%m%n

rootLogger.level = debug
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.log.ref = log

如果需要复杂的请参考:
http://logging.apache.org/log4j/2.x/manual/configuration.html#Properties

注:.properties这种方式用的比较少,链接中的注释也比较少,请参考(1)中的文档,对照着理解和编写。

3、输出log日志并记录成文件

//1.定义Logger对象,用Logger.getLogger(Class clazz):
public static Logger log4jDemo1 = LogManager.getLogger(LogListener.class.getName());

//2.定义Logger对象,用LogManager.getLogger(Class clazz):
//public static Logger log4jDemo2 = LogManager.getLogger(LogListener.class);

//3.定义Logger对象,用LogManager.getLogger(String name):
//public static Logger log4jDemo3 = LogManager.getLogger(LogListener.class.getName());

//4.定义Logger对象,将3中的name变成具体的字符串:
//public static Logger log4jDemo4 = LogManager.getLogger("common.LogListener");

log4jDemo1.debug("我是debug");
log4jDemo1.error("我是error");
log4jDemo1.log(Level.ERROR, "我是Level.ERROR ");

你可能感兴趣的:(JavaWeb后台)