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

如何为Cloud Run服务的自动生成日志添加自定义属性?

为Cloud Run自动生成日志添加自定义属性

可以实现这个需求,通过输出结构化JSON日志到容器标准输出(stdout),Cloud Logging会自动解析并将自定义字段注入到日志的httpRequest对象中。以下是修改后的Express中间件实现:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  const myCustomHeader = req.get('x-my-custom-header');

  // 在响应完成后触发日志输出
  res.on('finish', () => {
    // 构造符合Cloud Logging规范的日志条目
    const structuredLog = {
      severity: 'INFO',
      httpRequest: {
        requestMethod: req.method,
        requestUrl: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
        status: res.statusCode,
        userAgent: req.get('user-agent'),
        remoteIp: req.ip,
        myCustomHeader: myCustomHeader // 注入自定义头部字段
      },
      labels: {
        mylabel: "mylabelvalue",
        mysecondlabel: "mysecondlabelvalue"
      }
    };

    // 输出到stdout,Cloud Run会自动收集并解析
    console.log(JSON.stringify(structuredLog));
  });

  next();
});

// 示例路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(process.env.PORT || 8080, () => {
  console.log('Server started');
});

关键说明:

  • Cloud Run默认的自动请求日志由平台生成,通过自行输出结构化日志,你可以补充自定义字段到httpRequest对象中
  • 日志条目需符合Cloud Logging结构化格式,httpRequest中的核心字段(如requestMethod、status)建议保留,确保日志被正确识别为请求日志类型
  • 输出的JSON日志会被Cloud Run自动收集,进入与自动日志相同的日志流(run.googleapis.com/requests),并关联到对应Cloud Run资源
  • 若不想保留重复日志,可通过Cloud Run服务配置调整,禁用平台自动请求日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:40:32