栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring基础篇-07-SpringBoot项目内日志输出(logback.xml)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring基础篇-07-SpringBoot项目内日志输出(logback.xml)

1. 配置logback-spring.xml
    compile('org.springframework.kafka:spring-kafka:2.2.3.RELEASE')
    compile('com.github.danielwegener:logback-kafka-appender:0.2.0-RC2')
    compile('net.logstash.logback:logstash-logback-encoder:6.0')

Apollo配置

log.kafka.servers = kafka的ip端口
log.root.level = INFO
log.console.appender = ConsoleAppender
log.kafka.appender = KafkaJsonAppender



    
    

    
    
    

    

    
    
    
    
    
    
    


    
    
        
            ${COMMON_PATTERN}
            utf-8
        
    

    
        
            
                
                    UTC
                
                
                    
                        {
                        "requestUrl": "%mdc{requestUrl}",
                        "traceId": "%mdc{traceId}",
                        "engineRequestId": "%mdc{engineRequestId}",
                        "orderNumber": "%mdc{orderNumber}",
                        "refundNumber": "%mdc{refundNumber}",
                        "message": "%msg%n%r"
                        }
                    
                
            
        
        json_${PROJECT_NAME}.log_${PROFILE_ACTIVE}
        
        
        bootstrap.servers=${LOG_SERVERS}
        acks=0
        linger.ms=1000
        max.block.ms=0
    

    




    
        
        

    


2. 将主机名放到日志当中
public class HostNameDefiner extends PropertyDefinerBase {

    @Override
    public String getPropertyValue() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

}
3. 过滤不需要出现的日志

形式1: 固定写死在xml内,如

形式2: 动态配置,通过代码实现

import static org.springframework.boot.logging.LoggingSystem.ROOT_LOGGER_NAME;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerConfiguration;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.stereotype.Component;



@Slf4j
@Component
public class LoggingSystemAdjustListener {

    
    private static final String LOGGER_PREFIX = "logging.level.";

    @Resource
    private LoggingSystem loggingSystem;
    

    // By default only read config in "application"
    @ApolloConfigChangeListener
    public void onChange(ConfigChangeEvent changeEvent) throws Exception {
        //  遍历配置集的每个配置项,判断是否是 logging.level 配置项
        for (String key : changeEvent.changedKeys()) {
            // 如果是 logging.level 配置项,则设置其对应的日志级别
            if (key.startsWith(LOGGER_PREFIX)) {
                String loggerName = key.replace(LOGGER_PREFIX, "");
                //
                LoggerConfiguration cfg = loggingSystem.getLoggerConfiguration(loggerName);
                if (cfg == null) {
                    if (log.isErrorEnabled()) {
                        log.error("no loggerConfiguration with loggerName:{}", loggerName);
                    }
                    continue;
                }

                // 获得日志级别
                ConfigChange change = changeEvent.getChange(key);
                // the newLevel could be null if the config is deleted from apollo
                // in this case we update it same as "root" level
                String newLevel = change.getNewValue();

                LogLevel level = null;
                // config is deleted or kept as empty string
                if (newLevel == null || newLevel.isEmpty()) {
                    level = getFallbackLogLevel(ROOT_LOGGER_NAME);
                } else {
                    try {
                        level = LogLevel.valueOf(newLevel.toUpperCase());
                    } catch (IllegalArgumentException e) {
                        // do nothing
                    }
                }

                if (level == null) {
                    if (log.isErrorEnabled()) {
                        log.error("logger:[{}]current LogLevel is invalid:{}", loggerName, newLevel);
                    }
                    continue;
                }

                if (!isSupportLevel(level)) {
                    if (log.isErrorEnabled()) {
                        log.error("LoggingSystem:[] not support current LogLevel:{}",
                                loggingSystem.getClass().getName(), newLevel);
                    }
                    continue;
                }

                if (log.isInfoEnabled()) {
                    log.info("logger:[{}] current effective level:{}, to be changed to level:{}", loggerName,
                            cfg.getEffectiveLevel(), newLevel);
                }

                // 基于springboot的日志抽象类,设置日志级别到 LoggingSystem 中
                loggingSystem.setLogLevel(loggerName, level);
            }
        }
    }

    private boolean isSupportLevel(LogLevel level) {
        for (LogLevel ll : loggingSystem.getSupportedLogLevels()) {
            if (ll == level) {
                return true;
            }
        }
        return false;
    }

    public LogLevel getFallbackLogLevel(String loggerName) {
        LoggerConfiguration cfg = loggingSystem.getLoggerConfiguration(loggerName);
        if (cfg == null) {
            if (log.isErrorEnabled()) {
                log.error("no loggerConfiguration with loggerName:{}", loggerName);
            }
            // use WARN as unexpected case
            return LogLevel.WARN;
        }

        return cfg.getEffectiveLevel();
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号