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的接口

廖雪峰Java3异常处理-2断言和日志-4使用Log4j的更多相关文章

  1. 廖雪峰Java3异常处理-2断言和日志-3使用Commons Logging

    Commons Logging是Apache创建的日志模块: 可以挂接不同的日志系统 可以通过配置文件指定挂接的日志系统 自动搜索并使用Log4j 如果Log4j不存在,使用JDK Logging(J ...

  2. 廖雪峰Java3异常处理-2断言和日志-2使用JDK Logging

    1.日志 为了取代System.out.println() 可以设置输出样式 可以设置输出级别,禁止某些级别输出 可以被重定向到文件 可以按包名控制日志级别 2.JDK内置Logging 在java. ...

  3. 廖雪峰Java3异常处理-2断言和日志-1使用断言

    1.断言 断言Assertion是一种程序调试方式 使用assert关键字 断言条件预期为true 如果断言失败,抛出AssertionError,停止程序 可选的断言消息,断言失败,就会抛出 pub ...

  4. 廖雪峰Java3异常处理-1错误处理-4自定义异常

    JDK已有的异常: RuntimeException * NullPointerException * IndexOutOfBoundsException * SecurityException * ...

  5. 廖雪峰Java3异常处理-1错误处理-3抛出异常

    1.异常的传播 当某个方法抛出异常时: 如果当前方法没有捕获,异常就被抛到上层调用方法 直到遇到某个try...catch被捕获 使用printStackTrace()打印处方法的调用栈 import ...

  6. 廖雪峰Java3异常处理-1错误处理-2捕获异常

    1捕获异常 1.1 finally语句保证有无错误都会执行 try{...}catch (){...}finally{...} 使用try...catch捕获异常 可能发生异常的语句放在try{... ...

  7. 廖雪峰Java3异常处理-1错误处理-1Java的异常

    1.计算机运行中的错误 在计算机程序运行的过程中,错误总会出现,不可避免的 用户输入错误 读写文件错误 网络错误.内存耗尽.无法连接打印机不可 String s = "abc"; ...

  8. python异常处理与断言以及日志模块

    python异常处理与断言 目录: 1.异常处理 2.断言(assert) 3.日志模块(logging) 4.修改之前的车票信息查询,把日志模块.异常处理加进去 1.异常处理 代码如下: 语法: t ...

  9. 廖雪峰Java-3流程控制-7for循环

    for循环 for循环使用计数器实现循环 for循环条件需要设置:计数器初始值:循环前检测条件:每次循环后如何更新计数器 计数器变量通常命名为i int[] ns = {1,4,9,16,25}; f ...

随机推荐

  1. zabbix监控mysql最简单的方法

    该实验基于我的上一篇文章监控第一台主机的基础上 首先,因为水平有限,我选择直接关闭了防火墙和SELinux. 环境: 两台centos7,服务器端IP是192.168.200.128(以下简称主机), ...

  2. day 56 jQuery学习

    1.补充:each 描述:一个通用的迭代函数,它可以用来无缝迭代对象和数组.数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1.其他对象通过其属性名 ...

  3. mtail 提取应用日志数据到时序数据库的工具-支持prometheus

    mtail 是谷歌开源的一款很不错的应用日志提取工具,我们可以方便的用来提取应用的数据 到常见的监控系统(prometheus,stats,collectd,gragphite....) 说明: de ...

  4. Using C++ new() placement in embedded system

    For new(), there are three definition in C++11, which are listed below. throwing (1) void* operator ...

  5. Redis&MongoDB&Zookeeper&Kafka

    目录 Redis MongoDB Zookeeper Kafka Redis 概念 Redis是NoSQL中比较常典型的一个非关系型数据库,在日常工作中也是最为常见的.Redis是一个由C语言编写的开 ...

  6. Revit api 创建楼梯图元

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. Package has no installation candidate解决方法

    今天在安装软件的时候出现了Package has no installation candidate的问题,如:# apt-get install <packagename>Reading ...

  8. c++ 函数中的部分代码执行一次

    编程时有时需要将一段代码中的某一块只执行一次: #include<iostream> using namespace std; int fun1(int a) { static bool ...

  9. SparkStreaming整合kafka编程

    1.下载spark-streaming-kafka插件包 由于Linux集群环境我使用spark是spark-2.1.1-bin-hadoop2.7,kafka是kafka_2.11-0.8.2.1, ...

  10. Video Test Pattern Generator(7.0)软件调试记录

    Video Test Pattern Generator(7.0)软件调试记录 . XVidC_VideoMode XVIDC_VM_576_50_I = XVIDC_VM_720x576_50_I ...