从 Google 云 运行 执行日志记录的最简单方法

Simplest way to perform logging from Google Cloud Run

我按照本指南 https://firebase.google.com/docs/hosting/cloud-run 设置了云 运行 docker。 然后我试着按照这个指南 https://cloud.google.com/run/docs/logging 来执行一个简单的日志。尝试将结构化日志写入标准输出 这是我的代码:

    trace_header = request.headers.get('X-Cloud-Trace-Context')

    if trace_header:
        trace = trace_header.split('/')
        global_log_fields['logging.googleapis.com/trace'] = "projects/sp-64d90/traces/" + trace[0]

    # Complete a structured log entry.
    entry = dict(severity='NOTICE',
                 message='This is the default display field.',
                 # Log viewer accesses 'component' as jsonPayload.component'.
                 component='arbitrary-property',
                 **global_log_fields)

    print(json.dumps(entry))

我在 Cloud Logs Viewer 中看不到此日志。每次调用 docker 时,我都会看到 http Get 日志。 我错过了什么吗?我是新手,想知道什么是能够记录信息并查看信息的简单方法,假设我创建的 docker 完全符合指南中的步骤 (https://firebase.google.com/docs/hosting/cloud-run)

谢谢

1.Follow你提到的指南Serve dynamic content and host microservices with Cloud Run

2.Add下面的代码改为index.js

 const {Logging} = require('@google-cloud/logging');
 const express = require('express');
 const app = express();

 app.get('/', (req, res) => {
  console.log('Hello world received a request.');

  const target = process.env.TARGET || 'World';
  const projectId = 'your-project';
  const logging = new Logging({projectId});

  // Selects the log to write to
  const log = logging.log("Cloud_Run_Logs");

  // The data to write to the log
  const text = 'Hello, world!';

  // The metadata associated with the entry
  const metadata = {
    resource: {type: 'global'},
    // See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity
    severity: 'INFO',
  };

  // Prepares a log entry
  const entry = log.entry(metadata, text);

   async function writeLog() {
    // Writes the log entry
    await log.write(entry);
    console.log(`Logged the log that you just created: ${text}`);
  }
  writeLog();




  res.send(`Hello ${target}!`);
});

const port = process.env.PORT || 8080;
app.listen(port, () => {
  console.log('Hello world listening on port', port);
});
   

3.Check Logging/Global

下的日志

编辑

对于python:


import os
import google.cloud.logging
import logging


from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    target = os.environ.get('TARGET', 'World')
    # Instantiates a client
    client = google.cloud.logging.Client()

    # Connects the logger to the root logging handler; by default this captures
    # all logs at INFO level and higher
    client.setup_logging()

    # The data to log
    text = 'Hello, these are logs from cloud run!'

    # Emits the data using the standard logging module
    logging.warning(text)
    return 'Hello {}!\n'.format(text)

Google Cloud Logging 中支持 Bunyan 和 Winston node.js 库:

通常,如果您不想进行 结构化日志记录 ,您需要做的就是将内容打印到 stdout/stderr,Cloud 运行 会选择顶起来。

这在 https://cloud.google.com/run/docs/logging 中有记录,它还有 Node.js 结构化和非结构化日志记录的示例。

我 运行 遇到了完全相同的问题。我确实发现刷新标准输出会导致日志记录出现,否则不会出现。看起来像 Cloud 运行 me.

中的错误
print(json.dumps(entry))
import sys
sys.stdout.flush()

Output with flushing

#对于Python/Java

使用“google-cloud-logging”模块是将容器日志推送到 Stackdriver 日志的最简单方法。配置 google-cloud-logging 以使用 python 的默认日志记录模块

import logging as log
import google.cloud.logging as logging

def doSomething(param):
    logging_client = logging.Client()
    logging_client.setup_logging()
log.info(f"Some log here: {param}") 

现在您应该会在 Cloud 运行 Revision 下的 Stackdriver 日志记录中看到此日志。

将 Google Cloud Platform 登录集成到您的 Python 代码中的一种简单方法是从 logging.StreamHandler 创建一个子类。这样,日志记录级别也将与 Google Cloud Logging 的级别相匹配,使您能够根据严重性进行过滤。此解决方案也适用于 Cloud 运行 容器。

您也可以只将此处理程序添加到任何现有的记录器配置中,而无需更改当前的记录代码。

import json
import logging
import os
import sys
from logging import StreamHandler

from flask import request


class GoogleCloudHandler(StreamHandler):
    def __init__(self):
        StreamHandler.__init__(self)

    def emit(self, record):
        msg = self.format(record)
        # Get project_id from Cloud Run environment
        project = os.environ.get('GOOGLE_CLOUD_PROJECT')

        # Build structured log messages as an object.
        global_log_fields = {}
        trace_header = request.headers.get('X-Cloud-Trace-Context')

        if trace_header and project:
            trace = trace_header.split('/')
            global_log_fields['logging.googleapis.com/trace'] = (
                f"projects/{project}/traces/{trace[0]}")

        # Complete a structured log entry.
        entry = dict(severity=record.levelname, message=msg)
        print(json.dumps(entry))
        sys.stdout.flush()

配置和使用处理程序的方法可以是:

def get_logger():
    logger = logging.getLogger(__name__)

    if not logger.handlers:
        gcp_handler = GoogleCloudHandler()
        gcp_handler.setLevel(logging.DEBUG)

        gcp_formatter = logging.Formatter(
            '%(levelname)s %(asctime)s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s')
        gcp_handler.setFormatter(gcp_formatter)
        logger.addHandler(gcp_handler)
    return logger