在微服务arch中,构建在spring引导上,我将prod中的所有日志发送到GCP日志,这是正常工作的。但是日志不包括应用程序名称。由于微服务使用一个通用的启动器工件,因此存在许多相似的日志,并且很难确定哪些服务正在生成日志。那么如何配置日志记录以包含应用程序名称呢?基本上,我正在寻找一种方法来确定日志来自哪个微服务?
pom.xml的修改
<properties>
<spring-cloud-gcp-starter-logging.version>1.2.8.RELEASE</spring-cloud-gcp-starter-logging.version>
</properties>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-logging</artifactId>
<version>${spring-cloud-gcp-starter-logging.version}</version>
</dependency>
下面是logback-spring.xml
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<include resource="org/springframework/cloud/gcp/logging/logback-appender.xml"/>
<include resource="org/springframework/cloud/gcp/logging/logback-json-appender.xml"/>
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<!-- <appender-ref ref="CONSOLE_JSON"/>-->
</root>
</springProfile>
<springProfile name="prod">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<!-- <appender-ref ref="CONSOLE_JSON"/>-->
<appender-ref ref="STACKDRIVER"/>
</root>
</springProfile>
</configuration>
通过创建自己的appender
解决了这个问题<appender name="MY_STACKDRIVER" class="org.springframework.cloud.gcp.logging.LoggingAppender">
<log>${STACKDRIVER_LOG_NAME}</log> <!-- Optional : default java.log -->
<enhancer>com.xyz.logging.MyLoggingEnhancer</enhancer>
<flushLevel>${STACKDRIVER_LOG_FLUSH_LEVEL}</flushLevel> <!-- Optional : default ERROR -->
</appender>
@Component
public class MyLoggingEnhancer extends TraceIdLoggingEnhancer {
private static final String MICROSERVICE_NAME = "serviceName";
@Override
public void enhanceLogEntry(LogEntry.Builder builder) {
super.enhanceLogEntry(builder);
if (StaticBeanUtil.getInstance() != null) {
builder.addLabel(MICROSERVICE_NAME, StaticBeanUtil.getInstance().getApplicationName());
}
}
}