廖雪峰Java3异常处理-2断言和日志-4使用Log4j

1.Log4j

Log4j是目前最流行的日志框架。有两个版本

  • 1.x:Log4j
  • 2.x:Log4j2

Log4j下载地址https://www.apache.org/dyn/closer.lua/logging/log4j/2.11.1/apache-log4j-2.11.1-bin.tar.gz,建议选择清华的镜像
导入log4j-api-2.11.1.jar,log4j-core-2.11.1.jar,log4j-jcl-2.11.1.jar即可

Commons Logging可以自动使用Log4j:
Commons Logging如果在classpath中发现了log4j,就会使用log4j

  • 始终使用Commons Logging接口来写入日志
  • 开发阶段无需引入Log4j
  • 使用Log4j只需要把正确的配置文件和相关jar包放入classpath
  • 使用配置文件可灵活修改日志,无需修改代码

2.示例

Person.java

public class Person {
    String name;
    public Person(String name){
        if (name == null){
            throw new IllegalArgumentException("name is null");
        }
        this.name = name;
    }
    public String hello(){
        return "Hello, "+this.name;
    }
}

Main.java

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Main {
    static final Log log = LogFactory.getLog(Main.class);
    public static void main(String[] args){
        log.info("program start...");
        String name= "小明" ;
        log.info("create person: "+name);
        Person p = new Person(name);
        log.info("call hello(): "+ p.hello());
        try{
            new Person(null);
        }catch (Exception e){
            log.error("Error when create person. ",e);
        }
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
    <Properties>
        <Property name="log.pattern">%d{MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}%n%msg%n%n</Property><!--如何打印日志的格式-->
        <Property name="file.all.filename">log/all.log</Property>
        <Property name="file.all.pattern">log/all.%i.log.gz</Property>
        <Property name="file.err.filename">log/err.log</Property>
        <Property name="file.err.pattern">log/err.%i.log.gz</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${log.pattern}" />
        </Console>
        <RollingFile name="all" bufferedIO="true"
                     fileName="${file.all.filename}" filePattern="${file.all.pattern}">
            <PatternLayout pattern="${log.pattern}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="1 MB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
        <RollingFile name="err" bufferedIO="true"
                     fileName="${file.err.filename}" filePattern="${file.err.pattern}">
            <PatternLayout pattern="${log.pattern}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="1 MB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="console" level="info" /><!--注释之后将只打印1遍,否则打印2遍-->
            <AppenderRef ref="all" level="info" />
            <AppenderRef ref="err" level="error" />
        </Root>
        <Logger name="com.testAssertion" level="debug">
            <AppenderRef ref="console" level="debug" />
        </Logger>
    </Loggers>
</Configuration>

eclipse和IDEA log4j.xml配置文件存放路径是不一样的。
eclipse:在src目录下新建log4j2.xml
IDEA:src/main/resources下新建log4j2.xml

再次运行Main.class

log/all.log

02-32 00:05:10.483 [main] INFO  com.testAssertion.Main
program start...

02-32 00:05:10.486 [main] INFO  com.testAssertion.Main
create person: 小明

02-32 00:05:10.487 [main] INFO  com.testAssertion.Main
call hello(): Hello, 小明

02-32 00:05:10.488 [main] ERROR com.testAssertion.Main
Error when create person. 

java.lang.IllegalArgumentException: name is null
	at com.testAssertion.Person.<init>(Person.java:7) ~[bin/:?]
	at com.testAssertion.Main.main(Main.java:13) [bin/:?]

log/err.log

02-32 00:05:10.488 [main] ERROR com.testAssertion.Main
Error when create person. 

java.lang.IllegalArgumentException: name is null
	at com.testAssertion.Person.<init>(Person.java:7) ~[bin/:?]
	at com.testAssertion.Main.main(Main.java:13) [bin/:?]

3.总结

  • 通过Commons Logging实现日志,不需要修改代码即可使用Log4j
  • 使用Log4j只需要把log4j2.xml和相关jar放入classpath
  • 如果要更换Log4j,只需要移除log4j2.xml和相关jar
  • 只有扩展Log4j时,才需要引用Log4j的接口
原文地址:https://www.cnblogs.com/csj2018/p/10335650.html