[英]Logging Python and Google Cloud
I am creating an application which can be run locally or on Google Cloud.我正在创建一个可以在本地或 Google Cloud 上运行的应用程序。 To set up google cloud logging I've used Google Cloud Logging , made a cloud logger and basically log using the class below为了设置谷歌云日志,我使用了谷歌云日志,制作了一个云记录器,基本上使用下面的 class 进行日志记录
class CloudLogger():
def __init__(self, instance_id: str = LOGGER_INSTANCE_ID, instance_zone: str = LOGGER_INSTANCE_ZONE) -> None:
self.instance_id = instance_id
self.instance_zone = instance_zone
self.cred = service_account.Credentials.from_service_account_file(CREDENTIAL_FILE)
self.client = gcp_logging.Client(project = PROJECT, credentials=self.cred)
self.res = Resource(type="gce_instance",
labels={
"instance_id": self.instance_id,
"zone": self.instance_zone
})
self.hdlr = CloudLoggingHandler(self.client, resource = self.res)
self.logger = logging.getLogger('my_gcp_logger')
self.hdlr.setFormatter(logging.Formatter('%(message)s'))
if not self.logger.handlers:
self.logger.addHandler(self.hdlr)
self.logger.setLevel(logging.INFO)
def info(self, log_this):
self.logger.setLevel(logging.INFO)
self.logger.info(log_this)
I want to have this so that if it is running on the cloud, it uses the GCP logger, and if run locally, it uses python logging.我想要这样,如果它在云上运行,它使用 GCP 记录器,如果在本地运行,它使用 python 日志记录。 I can either pass in as an argument ("Cloud", "Local") or make it intelligent enough to understand on its own.我既可以作为参数传入(“云”、“本地”),也可以让它足够智能以自行理解。 But I want the underlying logic to be the same so that I can log to cloud/local seamlessly.但我希望底层逻辑相同,以便我可以无缝登录到云/本地。 How would I go about doing this?我将如何 go 这样做?
Wondering if (maybe) theres some way to create a local logger.想知道(也许)是否有某种方法可以创建本地记录器。 And have those local logs parsed to GCP if running on the cloud.如果在云上运行,则将这些本地日志解析到 GCP。
I coped with this issue and Google is aware of it (and also for Go).我解决了这个问题,Google 也意识到了这一点(Go 也是如此)。 My helper do this:我的助手这样做:
http://metadata.google.internal/computeMetadata/v1/project/
with this header Metadata-Flavor: Google
使用此 header 元数据风格访问http://metadata.google.internal/computeMetadata/v1/project/
Metadata-Flavor: Google
Not perfect, but enough for me!不完美,但对我来说足够了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.