簡體   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