繁体   English   中英

在App Engine Standard python中使用Google Stackdriver日志时出错

[英]Error using Google Stackdriver Logging in App Engine Standard python

我的堆栈:
Google App Engine标准版
Python(2.7)

目标:
要在Google Stackdriver日志记录中创建命名日志, 请访问https://console.cloud.google.com/logs/viewer

文档 - Stackdriver日志记录: https ://google-cloud-python.readthedocs.io/en/latest/logging/usage.html

码:

from google.cloud import logging as stack_logging
from google.cloud.logging.resource import Resource
import threading

class StackdriverLogging:
    def __init__(self, resource=Resource(type='project', labels={'project_id': 'project_id'}), project_id='project_id'):

    self.resource = resource
    self.client = stack_logging.Client(project=project_id)

    def delete_logger(self, logger_name):
        logger = self.client.logger(logger_name)
        logger.delete()

    def async_log(self, logger_name, sev, msg):
        t = threading.Thread(target=self.log, args=(logger_name, sev, msg,))
        t.start()

    def log(self, logger_name, sev, msg):
        logger = self.client.logger(logger_name)

    if isinstance(msg, str):
        logger.log_text(msg, severity=sev, resource=self.resource)
    elif isinstance(msg, dict):
        logger.log_struct(msg, severity=sev, resource=self.resource)

class hLog(webapp2.RequestHandler):
   def get(self):
      stackdriver_logger = StackdriverLogging()
      stackdriver_logger.async_log("my_new_log", "WARNING", msg="Hello")
      stackdriver_logger.async_log("my_new_log", "INFO", msg="world")

错误:找到1个没有匹配响应的RPC请求

如果在Google App Engine Standard(Python)中无法以任何方式使此代码生效:

  from google.cloud import logging
  client = logging.Client()
  # client = logging.Client.from_service_account_json('credentials.json')
  logger = client.logger("my_new_log")
  logger.log_text("hello world") 

如果需要凭据,我想使用项目服务帐户。

任何帮助,将不胜感激。 谢谢。

我通常将Python日志记录模块直接绑定到Google Stackdriver Logging。 为此,我创建了一个log_helper模块:

from google.cloud import logging as gc_logging
import logging

logging_client = gc_logging.Client()
logging_client.setup_logging(logging.INFO)

from logging import *

然后我将其导入到其他文件中:

import log_helper as logging

之后,您可以像使用默认的python日志记录模块一样使用该模块。

要使用默认的python日志记录模块创建命名日志,请对不同的命名空间使用不同的记录器:

import log_helper as logging

test_logger = logging.getLogger('test')
test_logger.setLevel(logging.INFO)
test_logger.info('is the name of this logger')

输出:

INFO:test:是此记录器的名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM