3Java异常处理——2断言和日志——4使用Log4j(廖雪峰)

1.Log4j

Log4j是目前最流行的日志框架

  • 1.x:Log4j
  • 2.x:Log4j2
log.info("User logged in.");

Commons Logging可以自动使用Log4j:

Commons Logging如果在classpath中发现了log4j,就会使用log4j

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

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即可

2.应用实例

Main.java 


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);
        }
        log.info("Program end.");
    }
}

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;
    }		
}

 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>

运行结果:

all.log

08-03 10:46:40.160 [main] INFO  com.xiaoxiatianxi.main.Main
create person: 小明

08-03 10:46:40.161 [main] INFO  com.xiaoxiatianxi.main.Main
call hello(): Hello, 小明

08-03 10:46:40.161 [main] ERROR com.xiaoxiatianxi.main.Main
Error when create person. 

java.lang.IllegalArgumentException: name is null
	at com.xiaoxiatianxi.main.Person.<init>(Person.java:7) ~[bin/:?]
	at com.xiaoxiatianxi.main.Main.main(Main.java:17) [bin/:?]
08-03 10:46:40.164 [main] INFO  com.xiaoxiatianxi.main.Main
Program end.

err.loh

08-03 10:46:40.161 [main] ERROR com.xiaoxiatianxi.main.Main
Error when create person. 

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

3.总结

  • 通过Commons Logging实现日志,不需要修改代码即可使用Log4j
  • 使用Log4j只需要把log4j2.xml和相关jar放入classpath
  • 如果要更换Log4j,只需要移除log4j2.xml和相关jar
  • 只有扩展Log4j时,才需要引用Log4j的接口

猜你喜欢

转载自blog.csdn.net/qq_24573381/article/details/107758944
今日推荐