注意:部份代码太长,可以通过文末的图片快速查看对应位置

项目需求

  • 用户想自己配置日志存放的位置,因此我们需要满足提供可以配置的文件,用以满足用户的需求。
  • 因此,我们主要通过 log4j2.xml 来读取 application.yml 中的属性值

项目实现

  • 在eclipse 或者IDEA 中,新建一个 springboot 项目 ,只需要满足基本要求即可。
  • 初始化的pom.xml文件如下
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
  • 因为我们需要使用 log4j2 来实现日志记录功能 ,因此,我们先完善日志基础配置

  • 这其中有许多原理不做解释,网上看一下,大家都能懂,不懂可以咨询作者

    • pom.xml 中加入相关依赖
    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><!-- web 需要放在第一位,才能保证后面的jar包默认去除logback --><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><!-- log4j2 日志 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency><!-- log4j2 日志 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
    </dependencies>
    
    • 将 src/main/source 下面新建一个 log4j2 文件夹 ,并在下面新建一个 log4j2.xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration status="OFF"><appenders><Console name="Console" target="SYSTEM_OUT"><!--只接受程序中DEBUG级别的日志进行处理--><ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/><PatternLayout pattern="[%d{HH:mm:ss.SSS}] %-5level %class{36} %L %M - %msg%xEx%n"/></Console><!--处理DEBUG级别的日志,并把该日志放到logs/debug.log文件中--><!--打印出DEBUG级别日志,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档--><RollingFile name="RollingFileDebug" fileName="./logs/debug.log"filePattern="logs/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log.gz"><Filters><ThresholdFilter level="DEBUG"/><ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/></Filters><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile><!--处理INFO级别的日志,并把该日志放到logs/info.log文件中--><RollingFile name="RollingFileInfo" fileName="./logs/info.log"filePattern="logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz"><Filters><!--只接受INFO级别的日志,其余的全部拒绝处理--><ThresholdFilter level="INFO"/><ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/></Filters><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile><!--处理WARN级别的日志,并把该日志放到logs/warn.log文件中--><RollingFile name="RollingFileWarn" fileName="./logs/warn.log"filePattern="logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz"><Filters><ThresholdFilter level="WARN"/><ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/></Filters><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile><!--处理error级别的日志,并把该日志放到logs/error.log文件中--><RollingFile name="RollingFileError" fileName="./logs/error.log"filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"><ThresholdFilter level="ERROR"/><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile><!--druid的日志记录追加器--><RollingFile name="druidSqlRollingFile" fileName="./logs/druid-sql.log"filePattern="logs/$${date:yyyy-MM}/api-%d{yyyy-MM-dd}-%i.log.gz"><PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile></appenders><loggers><root level="DEBUG"><appender-ref ref="Console"/><appender-ref ref="RollingFileInfo"/><appender-ref ref="RollingFileWarn"/><appender-ref ref="RollingFileError"/><appender-ref ref="RollingFileDebug"/></root><!--记录druid-sql的记录--><logger name="druid.sql.Statement" level="debug" additivity="false"><appender-ref ref="druidSqlRollingFile"/></logger><logger name="druid.sql.Statement" level="debug" additivity="false"><appender-ref ref="druidSqlRollingFile"/></logger><!--log4j2 自带过滤日志--><Logger name="org.apache.catalina.startup.DigesterFactory" level="error" /><Logger name="org.apache.catalina.util.LifecycleBase" level="error" /><Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn" /><logger name="org.apache.sshd.common.util.SecurityUtils" level="warn"/><Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn" /><Logger name="org.crsh.plugin" level="warn" /><logger name="org.crsh.ssh" level="warn"/><Logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="error" /><Logger name="org.hibernate.validator.internal.util.Version" level="warn" /><logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="warn"/><logger name="org.springframework.boot.actuate.endpoint.jmx" level="warn"/><logger name="org.thymeleaf" level="warn"/></loggers>
    </configuration>
    
    • application.yml 中的初始化配置
    logging:config: classpath:log4j2/log4j2.xml
    
  • 按照上诉配置,我们完成了 log4j2 的基本配置,

  • 启动项目,日志如下:就说明成功了

  .   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::       (v1.5.21.RELEASE)[15:36:58.239] INFO  org.springframework.boot.StartupInfoLogger 48 logStarting - Starting Log4j2xml1Application on DESKTOP-EMD1JN0 with PID 9520 (E:\zhongchebottom\log4j2xml-1\target\classes started by LMS in E:\zhongchebottom\log4j2xml-1)[15:36:59.378] INFO  org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer 216 start - Tomcat started on port(s): 8080 (http)
[15:36:59.380] INFO  org.springframework.boot.StartupInfoLogger 57 logStarted - Started Log4j2xml1Application in 1.348 seconds (JVM running for 1.957)

项目实现 二

  • 在 application.yml 中加入 部分代码,进行测试
logging:config: classpath:log4j2/log4j2.xmltest:demo: D:/mylog
  • 新建一个监听类,内容如下
  • 主要关注下面一段内容代码 ,这一段代码主要是获取 application.yml中的值
@Override
public void onApplicationEvent(ApplicationEvent event) {if (event instanceof ApplicationEnvironmentPreparedEvent) {ConfigurableEnvironment envi = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();MutablePropertySources mps = envi.getPropertySources();PropertySource<?> ps = mps.get("applicationConfigurationProperties");if (ps != null && ps.containsProperty("test.demo")) {String logs = (String) ps.getProperty("test.demo");System.err.println("=========" + logs);MDC.put("log", logs);}}}
package com.example.demo;import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;public class ApplicationStartedEventListener implements GenericApplicationListener {public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10;private static Class<?>[] EVENT_TYPES = { ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class,ApplicationPreparedEvent.class, ContextClosedEvent.class, ApplicationFailedEvent.class };private static Class<?>[] SOURCE_TYPES = { SpringApplication.class, ApplicationContext.class };@Overridepublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof ApplicationEnvironmentPreparedEvent) {ConfigurableEnvironment envi = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();MutablePropertySources mps = envi.getPropertySources();PropertySource<?> ps = mps.get("applicationConfigurationProperties");if (ps != null && ps.containsProperty("test.demo")) {String logs = (String) ps.getProperty("test.demo");System.err.println("=========" + logs);MDC.put("log", logs);}}}@Overridepublic int getOrder() {return DEFAULT_ORDER;}@Overridepublic boolean supportsEventType(ResolvableType resolvableType) {return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);}@Overridepublic boolean supportsSourceType(Class<?> sourceType) {return isAssignableFrom(sourceType, SOURCE_TYPES);}private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {if (type != null) {for (Class<?> supportedType : supportedTypes) {if (supportedType.isAssignableFrom(type)) {return true;}}}return false;}
}
  • 修改启动类中的启动方式,然后启动项目即可
package com.example.demo;import java.util.Set;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableAsync
@EnableScheduling
@ComponentScan(basePackages = { "com.example.demo" })
public class Log4j2xmlApplication {private String bootstrap;public String getBootstrap() {return bootstrap;}public void setBootstrap(String bootstrap) {this.bootstrap = bootstrap;}public static void main(String[] args) {SpringApplication app = new SpringApplication(Log4j2xmlApplication.class);Set<ApplicationListener<?>> ls = app.getListeners();ApplicationStartedEventListener asel = new ApplicationStartedEventListener();app.addListeners(asel);app.run(args);
//      SpringApplication.run(Log4j2xmlApplication.class, args);}}
  • 在 log4j2.xml 调用application.yml 中的属性值 ,只截取了部分代码,要注意的地方请看图
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF"><appenders><Console name="Console" target="SYSTEM_OUT"><!--只接受程序中DEBUG级别的日志进行处理--><ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/><PatternLayout pattern="[%d{HH:mm:ss.SSS}] %-5level %class{36} %L %M - %msg%xEx%n"/></Console><!--处理DEBUG级别的日志,并把该日志放到logs/debug.log文件中--><!--打印出DEBUG级别日志,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档--><RollingFile name="RollingFileDebug" fileName="${ctx:log}/debug.log"filePattern="${ctx:log}/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log.gz"><Filters><ThresholdFilter level="DEBUG"/><ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/></Filters><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="2 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile><!--处理INFO级别的日志,并把该日志放到logs/info.log文件中--><RollingFile name="RollingFileInfo" fileName="${ctx:log}/info.log"filePattern="${ctx:log}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz"><Filters><!--只接受INFO级别的日志,其余的全部拒绝处理--><ThresholdFilter level="INFO"/><ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/></Filters><PatternLayoutpattern="[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"/><Policies><SizeBasedTriggeringPolicy size="500 MB"/><TimeBasedTriggeringPolicy/></Policies></RollingFile>
。。。。。。。。。。。

参考文章

  • SpringBoot+log4j2.xml使用application.yml属性值 : https://www.cnblogs.com/extjava/p/7553642.html


springboot log4j2.xml读取application.yml中的属性值相关推荐

  1. SpringBoot+log4j2.xml读取application.yml属性值

    参考文章:SpringBoot+log4j2.xml使用application.yml属性值 1.创建Listener package com.cloud.config;import org.apac ...

  2. SpringBoot中通过ConfigurationProperties注解的方式读取application.yml中配置的属性值

    场景 在SpringBoot后台项目中,某些固定的属性需要配置在配置文件application.yml中. 比如上传到服务器的文件路径. 然后在其他业务代码中比如上传文件接口中需要或者到配置的这个属性 ...

  3. 获取application.yml中的属性的方法

    @ConfigurationProperties(prefix = "girl") 获取application.yml 中的以girl为开头的配置属性 引用配置文件里的数据 @Va ...

  4. SpringBoot使用@Value读取Application.yml为null(疯狂踩坑)

    项目需求:在springBoot中有一个写死的url,发送http请求获取一个视频地址. 一开始的思路是这样的,然后考虑到这样写不够灵活,因为是springBoot项目,所以直接在配置文件中获取url ...

  5. C# 读取AssemblyInfo文件中的属性值

    using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...

  6. springboot yml怎么建常量_【Java】SpringBoot 中从application.yml中获取自定义常量

    由于这里我想通过java连接linux,connection连接需要host.port.username.password及其他路径等等.不想每次修改的时候都去改源文件,所以想写在applicatio ...

  7. Springboot默认加载application.yml原理

    Springboot默认加载application.yml原理以及扩展 SpringApplication.run(-)默认会加载classpath下的application.yml或applicat ...

  8. log4j2.xml 的标签 loggers 中 root 的属性 level 指的是什么

    log4j2.xml 的标签 loggers 中 root 的属性 level 指的是什么   log4j2.xml 是 log4j2 中的其中一种配置文件.log4j2.xml 中往往有如下配置: ...

  9. Springboot 配置类( @Configuration) 不能使用@Value注解从application.propertyes中加载值以及Environment为null解决方案

    Springboot 配置类( @Configuration) 不能使用@Value注解从application.propertyes中加载值以及Environment为null解决方案 参考文章: ...

最新文章

  1. 控制C++的内存分配
  2. C++_复合、委托、继承
  3. python之命令行解析工具argparse
  4. 产品中心和用户中心的视角摘抄
  5. 我们无法在你选择的位置安装Windows。0x80300002
  6. tcp三次握手四次挥手(及原因)详解
  7. android volley 上传图片 和参数,Android使用Volley实现上传文件功能
  8. [渝粤教育] 上海交通大学 微生物的世界 参考 资料
  9. android4.0.3 修改启动动画和开机声音
  10. Kafka(三)-- Kafka主要参数
  11. 省选知识清单/计划列表(咕?)
  12. 每天一道剑指offer-包含min函数的栈
  13. Centos7 Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon run
  14. i5 7200u 计算机专业,i5 7200U理论性能对比_笔记本评测-中关村在线
  15. W ndows7安装Hp1020,hp1020打印机驱动
  16. Linux 镜像文件ISO下载地址:
  17. ZZULIOJ1046-1050Python解法
  18. CSS特效(一):制作盒子荧光特效
  19. CAD快捷键命令------画矩形
  20. mac os 下 打开 JXM 文件

热门文章

  1. 嵌入式到底要不要考研?
  2. 定义一个数组,获取数组中的最大值和最小值
  3. Codesys使用ST语言实现离散PID模型的仿真(非自带PID模型)
  4. 【JavaEE】Linux基本使用
  5. oa系统换服务器信息失效,oa系统服务器的设置
  6. 为什么成年人总是有抹不去的故乡情结?
  7. Business collocations
  8. 替代启攀微8按键触控八通道触摸芯片-GTC08L
  9. Eclipse的卸载
  10. Ansible ping Unreachable TimeOut解决