Log4j2:一个日志管理工具。Log4j的升级版,需要Java6以上
 
一、安装log4j2依赖包
1、通过maven的pom.xml直接引入jar:
log4j-api和log4j-core
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
2、通过官网下载jar包直接引入到工程内
 
二、log4j2的配置文件
 
1、配置文件位置和命名规则
以下为官网内容,按照1-8的顺序优先查找文件,优先使用【log4j.configurationFile】
说明:如果是log4j2.xml文件直接放到resources工程资源文件目录下即可。
  1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
  2. If no system property is set the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
  3. If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
  4. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
  5. If a test file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
  6. If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
  7. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
  8. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
 
2、配置详解
下面列出的是XML格式文件的配置方法,也可以用Json的格式配置,官网上有介绍:http://logging.apache.org/log4j/log4j-2.3/manual/configuration.html
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR">
<!--Configuration 配置项
status:log4j本身的日志级别, “trace”, “debug”, “info”, “warn”, “error” and “fatal”
monitorInterval:每隔多少秒从新读取配置文件,可以在不重启的情况下修改配置-->
<Appenders>
<!--Appenders定义日志输出,有Console、File、RollingRandomAccessFile、MongoDB、Flume 等
有Console:输出源到控制台
File:将日志输出到文件,通过fileName指定存储到的文件(目录不存在会自动创建)
RollingRandomAccessFile:也是写入文件,但可以定义规则按照文件大小或时间等重新创建一个新的日志文件存储;如果是按时间分割需要配合filePattern使用
-->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %F %logger{36} - %msg%n"/>
<!--PatternLayout指定输出日志的格式 -->
</Console>
<File name="debuglog" fileName="./log/debug.log" append="true”>
<!--fileName为存储日志的文件地址;append为是否在已有文件上追加,true为追加,false为重建-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
<RollingFile name="customscript" fileName="${LOG_HOME}${FILE_NAME}" filePattern="${LOG_HOME}${FILE_NAME}.%d{yyyy-MM-dd}.log">
<!—filePattern为分割存储的日志的名字;必须加Policies,分割方式-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %M %L - %msg%xEx%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!--日志器,通过LogManager.getLogger(日志器name)的日志器名字决定使用具体哪个日志器
分为根Root日志器和自定义日志器-->
<Root level="ERROR">
<!--当根据名字找不到对应的日志器时,使用Root的日志器
leve:日志输出等级(默认ERROR);TRACE > DEBUG > INFO > WARN > ERROR, ALL or OFF-->
<AppenderRef ref="Console"/>
<!--AppenderRef:关联Appenders中定义的输出规则,可以有多个,日志可以同时输出到多个地方-->
<AppenderRef ref="debuglog"/>
</Root>
<Logger name="customlog" level="INFO" additivity="false">
<!--Logger自定义日志器:
name为日志器的名字,通过LogManager.getLogger(日志器name)获得该日志器连接
additivity:相加性。默认为true,若为true会将当前日志内容也打印到它上面的日志器内,这里上面日志器是Root-->
<AppenderRef ref="Console"/>
</Logger>
</Loggers>
</Configuration>
更多日志输出格式(PatternLayout)

%d{HH:mm:ss.SSS} 表示输出到毫秒的时间
%t 输出当前线程名称
%-5level 输出日志级别,-5表示左对齐并且固定输出5个字符,如果不足在右边补0
%logger 输出logger名称,因为Root Logger没有名称,所以没有输出
%msg 日志文本
%n 换行

其他常用的占位符有:
%F 输出所在的类文件名,如Log4j2Test.java
%L 输出行号
%M 输出所在方法名
%l 输出语句所在的行数, 包括类名、方法名、文件名、行数

 
 
RollingRandomAccessFile的更多配置项

fileName 指定当前日志文件的位置和文件名称
filePattern 指定当发生Rolling时,文件的转移和重命名规则
SizeBasedTriggeringPolicy 指定当文件体积大于size指定的值时,触发Rolling
DefaultRolloverStrategy 指定最多保存的文件个数
TimeBasedTriggeringPolicy 这个配置需要和filePattern结合使用,注意filePattern中配置的文件重命名规则是${FILE_NAME}-%d{yyyy-MM-dd HH-mm}-%i,最小的时间粒度是mm,即分钟
TimeBasedTriggeringPolicy指定的size是1,结合起来就是每1分钟生成一个新文件。如果改成%d{yyyy-MM-dd HH},最小粒度为小时,则每一个小时生成一个文件

RollingFile的更多配置
分割日志文件。
filePattern 指定当发生Rolling时,文件的转移和重命名规则
Policies:分割方式,按照时间或文件大小分割
 
举例如下:
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="25 KB" />
</Policies> 
TimeBasedTriggeringPolicy:按照RollingFile的filePattern中%d的细粒度分割;如果是到dd天,则按天分割,如果到HH按照小时分割
SizeBasedTriggeringPolicy:按照指定大小分割文件
 

三、Java

package util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; public class Log { static final Logger logger_root = LogManager.getLogger(Log.class.getName());//配置文件没配置Log的class名字,所以用默认的Root
static final Logger logger_custom = LogManager.getLogger("customlog");//配置文件定义了customlog,所以用customlog public static void main(String[] args) {
// 记录debug级别的信息
logger_root.debug("This is debug message.");
// 记录info级别的信息
logger_root.info("This is info message.");
// 记录error级别的信息
logger_root.error("This is error message."); // 记录debug级别的信息
logger_custom.debug("This is debug message.");
// 记录info级别的信息
logger_custom.info("This is info message.");
// 记录error级别的信息
logger_custom.error("This is error message.");
}
}
说明:
LogManager.getLogger(Log名字):获得一个Logger对象
通过Logger对象的.debug等输出日志(trace、debug、info、warn、error、fatal)
执行结果:
15:23:53.087 [main] ERROR Log.java util.Log - This is error message.
15:23:53.096 [main] INFO  Log.java customlog - This is info message.
15:23:53.097 [main] ERROR Log.java customlog - This is error message.
 
命中Root的log文件输出如下:
15:33:27.947 ERROR util.Log 17 main - This is error message.
 
 

Log4j2配置及使用的更多相关文章

  1. 转:spring boot log4j2配置(使用log4j2.yml文件)---YAML 语言教程

    转:spring boot log4j2配置(使用log4j2.yml文件) - CSDN博客http://blog.csdn.net/ClementAD/article/details/514988 ...

  2. log4j2配置ThresholdFilter,让info文件记录error日志

    日志级别: 是按严重(重要)程度来分的(如下6种): ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < ...

  3. Log4j2配置之Appender详解

    Log4j2配置之Appender详解 Appender负责将日志事件传递到其目标.每个Appender都必须实现Appender接口.大多数Appender将扩展AbstractAppender,它 ...

  4. Log4j2 - 配置

    官方文档:http://logging.apache.org/log4j/2.x/index.html 1 概述 Log4j2的配置包含四种方式,其中3种都是在程序中直接调用Log4j2的方法进行配置 ...

  5. log4j2配置详解

    1.    log4j2需要两个jar   log4j-api-2.x.x.jar    log4j-core-2.x.x.jar  .log4j和log4j2有很大的区别,jar包不要应错. 2. ...

  6. 【Log4j2 配置详解】log4j2的资源文件具体怎么配置

    可以先附上一个log4j2的资源文件详细内容,对照着看 ### set log levels ### log4j.rootLogger = INFO , C , D , E ### console # ...

  7. Log4j2 配置笔记(Eclipse+maven+SpringMVC)

    Log4j2相关介绍可以百度看下,这里只注重配置Log4j2 能够马上跑起来: 1.pom.xml文件中添加Log4j2的相关Maven配置信息 <!-- log4j2 --> <d ...

  8. Spring Boot初探之log4j2配置

    一.背景 下面讲在使用Spring Boot搭建微服务框架时如何配置log4j2,通过log4j2输出系统中日志信息. 二.添加log4j2的配置文件 在项目的src/main/rescources目 ...

  9. Log4j2配置与使用

    依赖包: <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <depend ...

  10. spring boot log4j2配置

    [传送门]:log4j官网配置文件详解 1. 排除 spring boot 自带的  spring-boot-starter-logging 依赖 <dependency> <gro ...

随机推荐

  1. 网络表示学习Network Representation Learning/Embedding

    网络表示学习相关资料 网络表示学习(network representation learning,NRL),也被称为图嵌入方法(graph embedding method,GEM)是这两年兴起的工 ...

  2. js:浏览器插件

    1.chrome background.js //chrome.webRequest.onBeforeRequest.addListener(function(info) { // chrome.ta ...

  3. python中的isalnum、isalpha、istitle、isspace、islower、isupper、isdigit

    isalnum()判断是否包含字母或者数字 isalpha()判断是否都是字母 istitle()判断每个单词首字母是否是大写 isspace()判断是否是空格 islower()判断字母是否全都是小 ...

  4. 《锋利的JQuery》中的动画效果:

    说实话,虽然这本书已经很老了,老到什么程度呢,这本书以JQuery1.9以前的版本写就的,toggle()方法的(func1,func2,...)这个切换事件的功能已经被删去了 但是这本书还是挺8错的 ...

  5. xsync

    shell  小工具,用于集群搭建: xsync脚本基于rsync工具,rsync 远程同步工具,主要用于备份和镜像.具有速度快.避免复制相同内容和支持符号链接的优点,它只是拷贝文件不同的部分,因而减 ...

  6. 抓取mooc中国随笔

    // $url = "http://www.baidu.com/"; $url= "https://www.icourse163.org/web/j/courseBean ...

  7. CRC16-CCITT C语言代码

    代码如下,使用空间换时间的方法 #define CRC16_CCITT_SEED 0xFFFF // 该位称为预置值,使用人工算法(长除法)时 需要将除数多项式先与该与职位 异或 ,才能得到最后的除数 ...

  8. 利用STM32CubeMX来生成USB_HID_Mouse工程

    硬件开发板:STM32F103C8 软件平台 好了现在开始利用STM32CubeMX来生成我们的工程 1.新建工程 选择MCU的型号 选择选择时钟 开启usb的模块 选择USB的类 配置时钟树(主要是 ...

  9. 机器学习进阶-阈值与平滑-图像阈值 1. cv2.threshold(进行阈值计算) 2. 参数type cv2.THRESH_BINARY(表示进行二值化阈值计算)

    1. ret, dst = cv2.thresh(src, thresh, maxval, type) 参数说明, src表示输入的图片, thresh表示阈值, maxval表示最大值, type表 ...

  10. 【JEECG技术文档】JEECG 接口权限开发及配置使用说明

    1.功能介绍   通过接口配置实现,对接口的访问权限控制和数据权限控制,接口时REST接口,接口权限认证机制使用Json web token (JWT) 接口权限调用流程: (1)通过接口用户的用户名 ...