springboot log4j2.xml读取application.yml中的属性值

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

项目需求

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

项目实现

  • 在eclipse 或者IDEA 中,新建一个 springboot 项目 ,只需要满足基本要求即可。
  • 初始化的pom.xml文件如下

	
		org.springframework.boot
		spring-boot-starter-web
	

	
		org.springframework.boot
		spring-boot-starter-test
		test
	

  • 因为我们需要使用 log4j2 来实现日志记录功能 ,因此,我们先完善日志基础配置

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

    • pom.xml 中加入相关依赖
    
    	
    		org.springframework.boot
    		spring-boot-starter
    		
    			
    				org.springframework.boot
    				spring-boot-starter-logging
    			
    		
    	
    
    	
    		org.springframework.boot
    		spring-boot-starter-web
    		
    			
    				org.springframework.boot
    				spring-boot-starter-logging
    			
    		
    	
    
    	
    	
    		org.springframework.boot
    		spring-boot-starter-log4j2
    	
    	
    	
    	
    	
    		org.springframework.boot
    		spring-boot-starter-test
    		test
    	
    
    
    • 将 src/main/source 下面新建一个 log4j2 文件夹 ,并在下面新建一个 log4j2.xml文件
    
    
        
    
            
                
                
                
            
    
            
            
            
                
                    
                    
                
                
                
                    
                    
                
            
    
            
            
                
                    
                    
                    
                
                
                
                    
                    
                
            
    
            
            
                
                    
                    
                
                
                
                    
                    
                
            
    
            
            
                
                
                
                    
                    
                
            
    
            
            
                
                
                    
                    
                
            
        
    
        
            
                
                
                
                
                
            
    
            
            
                
            
            
                
            
    
            
            
            
            
            
            
            
            
            
            
            
            
            
        
    
    
    • 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.xml

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

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

		}

	}

	@Override
	public int getOrder() {
		return DEFAULT_ORDER;
	}

	@Override
	public boolean supportsEventType(ResolvableType resolvableType) {
		return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);
	}

	@Override
	public 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> ls = app.getListeners();
        ApplicationStartedEventListener asel = new ApplicationStartedEventListener();
        app.addListeners(asel);
        app.run(args);
//		SpringApplication.run(Log4j2xmlApplication.class, args);
	}

}
  • 在 log4j2.xml 调用application.yml 中的属性值 ,只截取了部分代码,要注意的地方请看图


    
        
            
            
            
        

        
        
        
            
                
                
            
            
            
                
                
            
        

        
        
            
                
                
                
            
            
            
                
                
            
        
。。。。。。。。。。。

参考文章

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

springboot log4j2.xml读取application.yml中的属性值_第1张图片
springboot log4j2.xml读取application.yml中的属性值_第2张图片

你可能感兴趣的:(springboot log4j2.xml读取application.yml中的属性值)