Log4j2配置步骤

前言

spring boot支持的日志框架有,logback,Log4j2,Log4j和Java Util  Logging,默认使用的是logback日志框架,一直在使用log4j2,决定仍使用log4j2,那么要使用新的日志管理就需要把默认的去掉;

1.Spring Boot在pom.xml中的配置

去掉有默认的logback日志管理,使用log4j2日志管理

<!-- log related --><dependency> <!-- exclude掉spring-boot的默认log配置 --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><!-- a. --><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency> <!-- 引入log4j2依赖 --><!-- b. --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency><dependency>  <!-- 加上这个才能辨认到log4j2.yml文件 --><!-- c. --><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-yaml</artifactId></dependency><!-- end of log related -->

a.忽略spring boot自带的日志管理;

b.配置加载log4j2的日志管理;

c.加入辨别yml文件或者ymal文件的依赖;

2.yml或者ymal文件配置(log4j2.yml)

Configuration:status: warnProperties: # 定义全局变量Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:# 测试:-Dlog.level.console=warn -Dlog.level.xjj=trace# 生产:-Dlog.level.console=warn -Dlog.level.xjj=info- name: log.level.console    #控制台日志输出的级别value: trace- name: log.level.com.mars.mybatis.mappervalue: trace- name: log.pathvalue: /Users/fandong/Desktop/logs  #日志文件存储的位置- name: project.namevalue: Mars-DashBoard # 项目名称Appenders:Console:  # 输出到控制台name: CONSOLEtarget: SYSTEM_OUTThresholdFilter:level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值onMatch: ACCEPTonMismatch: DENYPatternLayout:pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%5p %20t [%50F:%3L] - %m%n"RollingFile: # 输出到文件,超过128MB归档- name: ROLLING_FILEignoreExceptions: falsefileName: ${log.path}/${project.name}.log    #日志文件存储位置+文件名称filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"PatternLayout:pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%5p %20t [%50F:%3L] - %m%n"Policies:SizeBasedTriggeringPolicy:size: "128 MB"    #最大日志文件大小DefaultRolloverStrategy:max: 1000Loggers:Root:level: info    #日志输出级别AppenderRef:- ref: CONSOLE- ref: ROLLING_FILELogger: # 为 com.jeiker.demo.mapper 包配置特殊的Log级别,方便调试 SQL 语句输出- name: log.level.com.mars.mybatis.mapperadditivity: falselevel: ${sys:log.level.com.mars.mybatis.mapper}AppenderRef:- ref: CONSOLE- ref: ROLLING_FILE

以上配置文件拿过去直接用就可以了,主要修改文件存放位置和项目名称(日志的名称)

3.测试

@Controller
public class TestController {protected final Logger logger = LoggerFactory.getLogger(this.getClass());@RequestMapping("/xslsheet")public String xslsheet(){logger.trace("I am trace log.");logger.debug("I am debug log.");logger.warn("I am warn log.");logger.error("I am error log.");return "/xslsheet";}
}

输出结果

2018-05-25 15:36:31,681:TRACE main (TestController.java:20) - I am trace log.
2018-05-25 15:36:31,681:DEBUG main (TestController.java:21) - I am debug log.
2018-05-25 15:36:31,682:WARN main (TestController.java:22) - I am warn log.
2018-05-25 15:36:31,682:ERROR main (TestController.java:23) - I am error log.

同时我们会发现/Users/fandong/Desktop/logs目录下会有日志文件.log生成;

4.其他

4.1为什么会替换掉spring boot默认的logback日志管理呢?

基于log4j2日志管理的性能和配置的灵活性;

更多的可以参考性能对比:https://www.jianshu.com/p/f18a9cff351d

4.2为什么只是配置了一个log4j2.yml就要就什么都不用管了就可以生成日志文件呢?

spring boot提供相应的缺省解析机制;

下面是自动的解析配置机制,不断的检测是否有符合规则的配置文件,检测到则加载?

Automatic Configuration
Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.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.
If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.
If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.
If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.

4.3错误配置方式

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId> 
<exclusions>  <exclusion>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-logging</artifactId>  </exclusion>  </exclusions>  
</dependency>    

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>

标红的地方是错误的配置数据;

4.4配置文件的格式是否只有yml一种?

log4j2日志管理配置文件会有多种格式配置;

79.2.1 Use YAML or JSON to Configure Log4j 2In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files. To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example:Format   Dependencies    File names
YAMLcom.fasterxml.jackson.core:jackson-databind com.fasterxml.jackson.dataformat:jackson-dataformat-yamllog4j2.yaml log4j2.ymlJSONcom.fasterxml.jackson.core:jackson-databindlog4j2.json log4j2.jsn

以上是支持格式说明,更多参考:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-log4j-for-logging-yaml-or-json-config

4.5日志有哪些级别

log4j定义了8个级别的log(除去OFF和ALL,可以说分为6个级别),优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL。

ALL 最低等级的,用于打开所有日志记录。

TRACE designates finer-grained informational events than the DEBUG.Since:1.2.12,很低的日志级别,一般不会使用。

DEBUG 指出细粒度信息事件对调试应用程序是非常有帮助的,主要用于开发过程中打印一些运行信息。

INFO 消息在粗粒度级别上突出强调应用程序的运行过程。打印一些你感兴趣的或者重要的信息,这个可以用于生产环境中输出程序运行的一些重要信息,但是不能滥用,避免打印过多的日志。
WARN 表明会出现潜在错误的情形,有些信息不是错误信息,但是也要给程序员的一些提示。
ERROR 指出虽然发生错误事件,但仍然不影响系统的继续运行。打印错误和异常信息,如果不想输出太多的日志,可以使用这个级别。
FATAL 指出每个严重的错误事件将会导致应用程序的退出。这个级别比较高了。重大错误,这种级别你可以直接停止程序了。
OFF 最高等级的,用于关闭所有日志记录。
如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。

从我们实验的结果可以看出,log4j默认的优先级为ERROR或者WARN(实际上是ERROR)。

4.6log4j2日志配置结构说明

参考:https://blog.csdn.net/qqhjqs/article/details/74095143

参考:

spring boot官网地址:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-log4j-for-logging-yaml-or-json-config

Log4j2配置官网地址:https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

https://blog.csdn.net/shiyong1949/article/details/52643711

https://www.cnblogs.com/ly-radiata/articles/6026534.html

Spring Boot之Log4j2配置(总结)相关推荐

  1. spring boot—集成log4j2日志框架

    文章目录 市场上的日志框架 spring boot日志框架关系 移除默认日志框架 切换为log4j2日志框架 市场上的日志框架   1)日志门面最常用的是slf4j   2)日志实现最常用的是logb ...

  2. Spring Boot与Log4j2集成之java.lang.IllegalStateException: Logback configuration error detected:

    引言: 一个问题的分析与解决过程是表与里的过程,是一个大胆猜测与小心求证的过程,spring boot与log4j2的集成过程中,我将描述一下分析这个问题的思路和过程. 我一直强调一点: 重要的不是解 ...

  3. Spring boot集成log4j2

    spring boot默认使用的是logback作为日志框架,那如何使用log4j2呢?下面就给大家介绍一下集成步骤: 此处我使用的是spring boot 2.1.2 1.新建一个spring bo ...

  4. spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

  5. spring boot多环境配置

    spring boot多环境配置 通过多环境配置,可以实现生产环境和测试环境灵活切换. 主配置文件加载生产环境配置文件语法: spring.profiles.active=pro 注意一旦pro被激活 ...

  6. 自定义spring boot的自动配置

    文章目录 添加Maven依赖 创建自定义 Auto-Configuration 添加Class Conditions 添加 bean Conditions Property Conditions Re ...

  7. Spring Boot的自动化配置原理

    转载自 Spring Boot的自动化配置原理 随着Ruby.Groovy等动态语言的流行,相比较之下Java的开发显得格外笨重.繁多的配置.低下的开发效率.复杂的部署流程以及第三方技术集成难度大等问 ...

  8. Spring Boot Server容器配置

    转载自 Spring Boot Server容器配置 参数配置容器 server.xx开头的是所有servlet容器通用的配置,server.tomcat.xx开头的是tomcat特有的参数,其它类似 ...

  9. 在Spring Boot中使用配置元数据来配置您的配置

    Spring Boot 1.3.0中发布了许多更新,但是其中一个对我很突出,因为我以前并不了解此更新,它的状态使其成为一项真正有用的功能(不幸的是,撰写本文时仅在Spring Boot中可用)这个). ...

最新文章

  1. TP-link 设置MAC地址过滤
  2. requests库和BeautifulSoup4库爬取新闻列表
  3. python读取excel表格-python读写Excel表格的实例代码(简单实用)
  4. 阿捷外传之Git代码统计:DotNetCore + PowerBI 实现Git仓库日志分析
  5. mysql lepus_MySQL 监控软件lepus天兔
  6. linux adduser mysql,linux独享初始配置方法(ftp、apache、mysql)
  7. 2018.03.12、Android知识点-Java篇
  8. 「常微分方程」(阿諾爾德) Page 6 問題4 經過擴張相空間的每一點有且僅有一條積分曲線...
  9. 【utorrent】ubuntu 安装utorrent
  10. 数据结构实验之图论七:驴友计划(最新版)
  11. verilog中的定点数、浮点数、定点小数、定点整数的表示及运算
  12. 把live2D模型放上网页
  13. onlinephototool免费在线图片处理器
  14. 最新:斐讯K3千兆无线路由器刷官改版固件的详细图文教程
  15. php直播源码平台开发过程中使用第三方sdk
  16. OpenCV4学习记录(一)解决第一步OpenCV4.5.1+VS2019+CMake
  17. web项目中图片上传
  18. 软件工程毕业设计课题(26)基于JAVA毕业设计JAVA家政预约系统毕设作品项目
  19. 计算机编程常用的英语,100916计算机编程常用的英语
  20. 计算器ajax实现代码,jQuery实现计算器功能

热门文章

  1. 为dev c++配置图形开发环境easyx之mingw32
  2. 流程图怎么做,教你制作流程图
  3. 管家婆ERP不显示打印次数的解决方法
  4. origin安装教程
  5. Linux下配置C语言编程环境
  6. Office系列及WPS等常用办公软件学习教程
  7. E1696 无法打开 源 文件 “chrono“
  8. DDoS 保护、缓解和防御:8 个基本技巧
  9. VMware vSphere Hypervisor 7(ESXi 7)
  10. [原]OWC做电子表格和图表的试验