【问题集】Spring boot 项目中Logback配置文件使读取yaml配置,读取不到配置

3,091 阅读2分钟

作为一个 php开发 转型 java开发,将工作中遇到的问题做个记录,以及与大家分享踩坑经历

踩坑原因

当公司运维统一 要求通过consul更具系统环境,读取不同环境的配置阿里云日志服务配置,而发生了,spring boot 项目启动时,logback 往阿里云推送日志失败。

发现问题

主要由于读取yaml配置,未读取到

为何为读取到?

主要由于:

  • logback.xml
  • logback-spring.xml 文件是 spring 默认的logback默认的配置文件名,会早于application.ymal文件加载前

我项目中就是使用 logback-spring 为文件名称

解决方案

1、自定义文件名:logback-xxx.xml
2、配置文件引入:

logging:
    config: classpath:logback-xxx.xml

具体的配置

yaml文件配置 (已阿里云为例,其他的源可以自行修改)
logging:
    config: classpath:logback-xxx.xml
    
sls:
  endpoint: endpoint
  accessKeyId: accessKeyId
  accessKeySecret: accessKeySecret
  project: project
  logStore: logStore
  canalLogStore: canalLogStore
logback文件
 <?xml version="1.0" encoding="UTF-8"?>
<Configuration debug="false">
  <!--  获取yaml中的应用名称 -->
  <springProperty scope="context" name="application.name" source="spring.application.name"/>
  <springProperty scope="context" name="sls.endpoint" source="sls.endpoint"/>
  <springProperty scope="context" name="sls.accessKeyId" source="sls.accessKeyId"/>
  <springProperty scope="context" name="sls.accessKeySecret" source="sls.accessKeySecret"/>
  <springProperty scope="context" name="sls.project" source="sls.project"/>
  <springProperty scope="context" name="sls.logStore" source="sls.logStore"/>
  <appender name="aliyunLoghubAppender" class="com.aliyun.openservices.log.logback.LoghubAppender">
    <!--必选项-->
    <!-- 账号及网络配置 -->
    <endpoint>${sls.endpoint}</endpoint>
    <accessKeyId>${sls.accessKeyId}</accessKeyId>
    <accessKeySecret>${sls.accessKeySecret}</accessKeySecret>
    <project>${sls.project}</project>
    <logStore>${sls.logStore}</logStore>
    <ioThreadCount>8</ioThreadCount>
    <retries>3</retries>
    <topic>${application.name}_${SYSTEM_ENV}</topic>
    <source>${HOSTNAME}</source>
    <timeFormat>yyyy-MM-dd'T'HH:mm:ssZ</timeFormat>
    <timeZone>Asia/Shanghai</timeZone>
    <batchSizeThresholdInBytes>3145728</batchSizeThresholdInBytes>
    <batchCountThreshold>4096</batchCountThreshold>
    <encoder>
      <pattern>[TrackId:%X{track-id}] %logger{0}</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
        by default -->
    <encoder>
      <pattern>[TrackId:%X{track-id}] %d{HH:mm:ss.SSS} [%thread] %-5level %logger{0}: - %msg %X{THREAD_ID} %n
      </pattern>
    </encoder>
  </appender>

  <!-- 可用来获取StatusManager中的状态 -->
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener"/>
  <!--环境设置-->
  <springProfile name="dev">
    <root level="INFO">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="aliyunLoghubAppender"/>
    </root>
  </springProfile>
  <springProfile name="test,prepare,production">
    <root level="WARN">
      <appender-ref ref="aliyunLoghubAppender"/>
    </root>
  </springProfile>
</Configuration>