Spring Boot日志记录和Google Cloud Platform日志查看器

时间:2020-02-07 14:51:47

标签: google-cloud-platform stackdriver java.util.logging

我正在Google Cloud Platform中运行Spring Boot应用程序,并通过Google Platform Logs Viewer查看日志文件。在使用Spring Boot并仅使用简单的servlet之前,日志记录条目将显示为:

Logs are grouped and show the blue information icon

每个请求将被分组,并且通过扩展行可以看到该请求的所有日志记录信息。但是,当使用Spring Boot时,请求不再分组,并且日志条目仅逐行显示。当有多个请求时,日志条目将变得非常混乱,因为无法以分组方式查看它们。我以相同的方式设置了logging.properties:

.level = INFO
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n

记录器在每个类中的初始化为:

private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(MyClass.class.getName());

然后将日志记录API用作: LOG.info(“我的消息”);

我不明白为什么语句的记录方式有所不同并且不再分组,但是它必须具有Spring Boot处理日志的方式?

1 个答案:

答案 0 :(得分:4)

自从最近的运行时以来,AppEngine的行为正与基于容器的方法越来越融合,与其他新产品(例如Cloud Run)一样,越来越“开放”。

这正在改变我们使用GAE进行开发的方式,特定的旧式库不可用(SearchAPI ...),并且也在改变日志的管理方式。

我们可以在新的java11运行时中重现此“ 嵌套日志功能”,但我们需要自己进行管理。

official docs所述:

在“日志查看器”中,可以将与同一跟踪相关的日志条目 以“亲子”格式查看。

这意味着,如果我们检索在请求的trace HTTP标头内收到的X-Cloud-Trace-Context标识符,则可以使用它通过将其作为{{ 1}}标识符属性。

这可以通过使用Stackdriver Logging Client libraries

完成

使用Spring GCP

幸运的是,Spring Cloud GCP可以使我们的生活更轻松。

您可以找到实现它的sample project。请注意,这是一个LogEntry的示例,但它在trace运行时中可以正常工作。 它使用Logback

AppEngine Flexible上的Spring Boot项目中,要执行的步骤如下:

  • 添加Standard依赖项:
GAE Java11
  • spring-cloud-gcp-starter-logging文件夹中添加一个<!-- Starter for Stackriver Logging --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-gcp-starter-logging</artifactId> <version>1.2.1.RELEASE</version> </dependency>
logback-spring.xml
  • src/main/resources内启用Spring GCP日志记录功能:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/cloud/gcp/autoconfigure/logging/logback-appender.xml" />
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />

    <root level="INFO">
        <!-- If running in GCP, remove the CONSOLE appender otherwise logs will be duplicated. -->
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="STACKDRIVER" />
    </root>
</configuration>
  • 并在代码中使用LOGGER:
src/main/resources/application.properties

对于spring.cloud.gcp.logging.enabled=true ,结果将在@SpringBootApplication @RestController public class DemoApplication { private static final Log LOGGER = LogFactory.getLog(DemoApplication.class); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @GetMapping() public SomeData get() { LOGGER.info("My info message"); LOGGER.warn("My warning message"); LOGGER.error("My error message"); return new SomeData("Hello from Spring boot !"); } } 查看器中显示:

Stackdriver Logging Viewer

相关问题