You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot应用中通过OpenTelemetry直接发送日志至Google Cloud Logging?

解决方案

要直接将Spring Boot日志发送至Google Cloud Logging,无需通过OpenTelemetry Collector,你可以直接使用Spring Cloud GCP提供的原生Logback Appender,步骤如下:

1. 调整Maven依赖

在pom.xml中添加Spring Cloud GCP Logging依赖(如果尚未添加),若仍需OpenTelemetry做链路追踪可保留原依赖,无需移除:

<!-- 保留OpenTelemetry用于链路追踪(可选) -->
<dependency>
    <groupId>io.opentelemetry.instrumentation</groupId>
    <artifactId>opentelemetry-spring-boot-starter</artifactId>
</dependency>

<!-- 添加Spring Cloud GCP Logging依赖 -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter-logging</artifactId>
</dependency>

2. 修改Logback配置

修改logback-spring.xml,移除OpenTelemetry Appender配置,将日志输出指向Google Cloud Logging的原生Appender(你已通过<include>引入该Appender的定义):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 引入Google Cloud Logging Appender定义 -->
    <include resource="com/google/cloud/spring/logging/logback-appender.xml" />
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />

    <!-- 移除原OpenTelemetry Appender配置 -->

    <!-- 将根日志输出到Google Cloud Logging,同时可保留控制台输出便于调试(可选) -->
    <root level="info">
        <appender-ref ref="GOOGLE_CLOUD_LOGGING"/>
        <appender-ref ref="CONSOLE"/> <!-- 可选配置 -->
    </root>
</configuration>

3. 认证配置

  • GCP托管环境(如Cloud Run、GKE、App Engine):无需额外配置,应用会自动通过元数据服务器获取认证凭据。
  • 本地/非GCP环境:设置环境变量GOOGLE_APPLICATION_CREDENTIALS,指向你的GCP服务账号密钥文件路径,示例:
    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-service-account-key.json"
    

完成以上配置后,应用日志会直接发送至Google Cloud Logging,无需经过OpenTelemetry Collector。

内容的提问来源于stack exchange,提问作者Jad Chahine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 17:02:47