是否可以在python日志记录中将日志级别注入结构化数据

时间:2020-07-13 16:15:07

标签: python logging google-cloud-platform stackdriver

我正在尝试从python程序的stdout上写一些结构注销。具体来说,我正在尝试编写符合以下条件的json,以便在GCP中运行它时,它会被堆栈驱动程序拾取并解释为结构化数据:

https://cloud.google.com/run/docs/logging#run_manual_logging-python

看看python文档,我可以为结构化数据创建一个类,并将其渲染为单行json字符串:

https://docs.python.org/2/howto/logging-cookbook.html#implementing-structured-logging

但是我坚持的是;如何在没有冗余日志调用的情况下将日志级别添加到该结构化数据:

class StructuredMessage(object):
def __init__(self, **kwargs):
    self.kwargs = kwargs

def __str__(self):
    return json.dumps(self.kwargs)

// Ideally I should have to type level='INFO' here, is there a way to get the logging
// module to do something to insert that information on the StructuredMessage instance?
logging.info(StructuredMessage(level='INFO'))

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式执行此操作-一种方法是使用像这样的简单辅助函数(假定import logging已经完成):

def log_structured(logger, level, **kwargs):
    kwargs[level] = level
    # you could also inject the logger name into kwargs here ...
    # convert e.g. string 'INFO' to logging.INFO
    # assumes you only use the standard levels defined in logging
    level = getattr(logging, level)
    logger.log(level, StructuredMessage(**kwargs))

logging.info()之类的功能使用root记录器,因此您可以执行类似的操作

root_logger = logging.getLogger()
log_structured(root_logger, 'INFO', foo='bar', bar='baz', num=123, fnum=123.456)