欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot+log4j2.xml使用application.yml屬性值問題

 更新時(shí)間:2023年12月11日 08:40:56   作者:extjava  
這篇文章主要介紹了SpringBoot+log4j2.xml使用application.yml屬性值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

項(xiàng)目中有個(gè)需求,需要log4j2.xml加載application.yml的屬性,折騰了半天,貼代碼吧:

1.自定義啟動(dòng)監(jiān)聽ApplicationStartedEventListener

代碼中標(biāo)紅的就是從yml中讀取的屬性,然后通過MDC設(shè)置到log4j2的上下文

package com.wm.dcm.utils;

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;

/**
 * @ClassName: MyApplicationStartedEventListener
 * @Description:TODO
 * @author: SUN
 * @date: 2017年9月19日 下午5:51:04
 * 
 */
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("spring.kafka.bootstrap-servers")) {
                String kafkaUrl = (String) ps.getProperty("spring.kafka.bootstrap-servers");
                //System.out.println(kafkaUrl);
                MDC.put("host", kafkaUrl);
            }
            
            if (ps != null && ps.containsProperty("logging.file")) {
                String fileName = (String) ps.getProperty("logging.file");
                //System.out.println(kafkaUrl);
                MDC.put("fileName", fileName);
            }

        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.core.Ordered#getOrder()
     */
    @Override
    public int getOrder() {
        // TODO Auto-generated method stub
        return DEFAULT_ORDER;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.context.event.GenericApplicationListener#
     * supportsEventType(org.springframework.core.ResolvableType)
     */
    @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;
    }
}

2.在Application啟動(dòng)類中添加

自定義的啟動(dòng)監(jiān)聽ApplicationStartedEventListener

package com.wm.dcm.db;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.wm.dcm.constant.LogTypeAndLevel;
import com.wm.dcm.utils.ApplicationStartedEventListener;

@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages = { "com.wm.dcm" })
@EnableKafka
@EnableAsync
public class DBApplication {
private String bootstrap;

    public String getBootstrap() {
        return bootstrap;
    }

    public void setBootstrap(String bootstrap) {
        this.bootstrap = bootstrap;
    }

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {



        // System.out.println(env);

        SpringApplication app = new SpringApplication(DBApplication.class);

        Set<ApplicationListener<?>> ls = app.getListeners();

        ApplicationStartedEventListener asel = new ApplicationStartedEventListener();

        app.addListeners(asel);
        
        app.run(args);


    }

}

3.在log4j2.xml中使用MDC定義的屬性

標(biāo)紅的就是使用方式

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
    
        <Appenders>
            <RollingFile name="RollingFile" fileName="logs/${ctx:fileName}"
                filePattern="logs/$${date:yyyy-MM}/${ctx:fileName}-%d{MM-dd-yyyy}-%i.log.gz"
                immediateFlush="true" append="true">
                <PatternLayout charset="UTF-8" pattern="[%-5p] %d[%t]  [%c] - %m%n" />

                <SizeBasedTriggeringPolicy size="50MB" />
                <!-- DefaultRolloverStrategy屬性如不設(shè)置,則默認(rèn)為最多同一文件夾下7個(gè)文件,這里設(shè)置了20 -->
                <DefaultRolloverStrategy max="20" />
            </RollingFile>
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout charset="UTF-8" pattern="[%-5p] %d[%t]  [%c] - %m%n" />
            </Console>
            <Kafka name="Kafka" topic="wmdcm_log">
                <JSONLayout complete="false" compact="true" locationInfo="true" />
                
                <Property name="bootstrap.servers" value="${ctx:host}"/>
            </Kafka>
        </Appenders>


    <Loggers>
        <!-- root loggers <AppenderRef ref="Console" /> -->
        <Root level="info" includeLocation="true">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
            <AppenderRef ref="Kafka" />
        </Root>
        <Logger name="org.apache.kafka" level="ERROR" />
        <Logger name="org.springframework.kafka" level="ERROR" />
    </Loggers>



</Configuration>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java設(shè)計(jì)模式之單例模式的詳解及優(yōu)點(diǎn)

    java設(shè)計(jì)模式之單例模式的詳解及優(yōu)點(diǎn)

    這篇文章主要介紹了java設(shè)計(jì)模式之單例模式的詳解及優(yōu)點(diǎn)的相關(guān)資料,如果一個(gè)類始終只能創(chuàng)建一個(gè)實(shí)例,那么這個(gè)類被稱為單例類,這種設(shè)計(jì)模式被稱為單例模式,需要的朋友可以參考下
    2017-08-08
  • SpringBoot實(shí)現(xiàn)轉(zhuǎn)頁功能

    SpringBoot實(shí)現(xiàn)轉(zhuǎn)頁功能

    這篇文章主要介紹了SpringBoot實(shí)現(xiàn)轉(zhuǎn)頁功能,頁面的跳轉(zhuǎn)在web開發(fā)中是經(jīng)常用的基礎(chǔ)功能,感興趣想要詳細(xì)了解可以閱讀下文,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值
    2023-05-05
  • Future與FutureTask接口實(shí)現(xiàn)示例詳解

    Future與FutureTask接口實(shí)現(xiàn)示例詳解

    這篇文章主要為大家介紹了Future與FutureTask接口實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • Java全面細(xì)致講解==和equals的使用

    Java全面細(xì)致講解==和equals的使用

    這篇文章主要介紹了Java中==和equals()的區(qū)別,,==可以使用在基本數(shù)據(jù)類型變量和引用數(shù)據(jù)類型變量中,equals()是方法,只能用于引用數(shù)據(jù)類型,需要的朋友可以參考下
    2022-05-05
  • SpringBoot封裝JDBC的實(shí)現(xiàn)步驟

    SpringBoot封裝JDBC的實(shí)現(xiàn)步驟

    本文主要介紹了SpringBoot封裝JDBC的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • Spring?Boot2?整合連接?Redis的操作方法

    Spring?Boot2?整合連接?Redis的操作方法

    在Spring?Boot中,通過RedisTemplate可以方便地對(duì)Redis進(jìn)行操作,包括設(shè)置和獲取數(shù)據(jù),文章詳細(xì)介紹了如何配置RedisTemplate,創(chuàng)建RedisConfig類進(jìn)行自定義配置,并通過Controller訪問Redis數(shù)據(jù)庫,感興趣的朋友一起看看吧
    2025-02-02
  • java多線程實(shí)現(xiàn)文件下載功能

    java多線程實(shí)現(xiàn)文件下載功能

    這篇文章主要介紹了java多線程實(shí)現(xiàn)文件下載功能的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • Java實(shí)現(xiàn)二分查找BinarySearch算法

    Java實(shí)現(xiàn)二分查找BinarySearch算法

    這篇文章主要介紹了Java實(shí)現(xiàn)二分查找BinarySearch算法,二分查找針對(duì)的是一個(gè)有序的數(shù)據(jù)集合,每次都通過跟區(qū)間的中間元素對(duì)比,將待查找的區(qū)間縮小為之前的一半,直到找到要查找的元素,或者區(qū)間被縮小為 0,需要的朋友可以參考下
    2023-12-12
  • 創(chuàng)建一個(gè)Java的不可變對(duì)象

    創(chuàng)建一個(gè)Java的不可變對(duì)象

    這篇文章主要介紹了創(chuàng)建一個(gè)Java的不可變對(duì)象,一個(gè)類的對(duì)象在通過構(gòu)造方法創(chuàng)建后如果狀態(tài)不會(huì)再被改變,那么它就是一個(gè)不可變(immutable)類。它的所有成員變量的賦值僅在構(gòu)造方法中完成,不會(huì)提供任何 setter 方法供外部類去修改,需要的朋友可以參考下
    2021-11-11
  • IDEA手動(dòng)添加junit4時(shí)出現(xiàn)的問題與解決方法

    IDEA手動(dòng)添加junit4時(shí)出現(xiàn)的問題與解決方法

    這篇文章主要給大家介紹了關(guān)于IDEA手動(dòng)添加junit4時(shí)出現(xiàn)的問題與解決方法,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評(píng)論