简体   繁体   English

如何在 python 应用引擎中更改日志消息的默认格式?

[英]How do I change the default format of log messages in python app engine?

I would like to log the module and classname by default in log messages from my request handlers.我想在来自我的请求处理程序的日志消息中默认记录模块和类名。

The usual way to do this seems to be to set a custom format string by calling logging.basicConfig , but this can only be called once and has already been called by the time my code runs.执行此操作的常用方法似乎是通过调用logging.basicConfig来设置自定义格式字符串,但这只能调用一次,并且在我的代码运行时已被调用。

Another method is to create a new log Handler which can be passed a new log Formatter , but this doesn't seem right as I want to use the existing log handler that App Engine has installed.另一种方法是创建一个新的日志Handler ,它可以传递一个新的日志Formatter ,但这似乎不正确,因为我想使用 App Engine 已安装的现有日志处理程序。

What is the right way to have extra information added to all log messages in python App Engine, but otherwise use the existing log format and sink?将额外信息添加到 python App Engine 中的所有日志消息的正确方法是什么,否则使用现有的日志格式和接收器?

I cooked this up by reading the logging module's __init__.py .我通过阅读logging模块的__init__.py I don't know if this is proper, but it seems to work:我不知道这是否合适,但它似乎有效:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    )

logging.info('Danger Will Robinson!')
# 03-31 20:00 root         INFO     Danger Will Robinson!
root = logging.getLogger()
hdlr = root.handlers[0]
fmt = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
hdlr.setFormatter(fmt)
logging.info('Danger Will Robinson!')
# root        : INFO     Danger Will Robinson!

I found this to be working for Python 3.6, it will set the logging level / format for all subsequent logging calls, even if logging is called by previous imports.我发现这适用于 Python 3.6,它将为所有后续日志记录调用设置日志记录级别/格式,即使logging是由以前的导入调用的。

logging_level = logging.INFO
logging_fmt = "%(levelname)s:%(name)s:%(message)s"   # the default
try:
    root_logger = logging.getLogger()
    root_logger.setLevel(logging_level)
    root_handler = root_logger.handlers[0]
    root_handler.setFormatter(logging.Formatter(logging_fmt))
except IndexError:
    logging.basicConfig(level=logging_level, format=logging_fmt)

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

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