Python CherryPy向日志记录添加上下文信息

Python CherryPy向日志记录添加上下文信息,python,cherrypy,Python,Cherrypy,我正在使用Cherrypy3.7.0构建一个小型web应用程序 我的问题是,我不知道如何将上下文信息添加到日志输出中 尽管我已经看过它的文档好几次了,但不清楚如何实现这样的目标。 我想在记录器中添加一个task属性,以便在我的一个视图中可以编写: logger.info('Processing finished', extra={'task': 'jashgd-765273-ehdfiuh'}) 我该怎么做 提前感谢试试这个 import cherrypy from cherrypy impo

我正在使用
Cherrypy3.7.0
构建一个小型web应用程序

我的问题是,我不知道如何将上下文信息添加到日志输出中

尽管我已经看过它的文档好几次了,但不清楚如何实现这样的目标。 我想在记录器中添加一个
task
属性,以便在我的一个视图中可以编写:

logger.info('Processing finished', extra={'task': 'jashgd-765273-ehdfiuh'})
我该怎么做

提前感谢

试试这个

import cherrypy
from cherrypy import log

class MyApp(object):
    def index(self):
        log.error(msg='This is My Error ', context='HTTP', severity=20, traceback=True)
        return "Hello World!"    
    index.exposed = True

cherrypy.tree.mount(MyApp(), "/")

cherrypy.config.update({'tools.staticdir.on': True,
    'tools.staticdir.dir': 'C:\\Documents and Settings\\d\\My Documents\\Aptana Studio 3 Workspace\\ScratchPad',
    'log.access_file' : "access.log",
    'log.error_file' : "error.log",
    'log.screen' : False,
    'tools.sessions.on': True,
    })


cherrypy.engine.start()
cherrypy.engine.block()
希望这有帮助

阅读文档 以下是关于
extra
关键字参数的文档说明:

第三个可选关键字参数是extra,可用于传递字典,该字典用于使用用户定义的属性填充为日志事件创建的日志记录。然后,可以根据需要使用这些自定义属性。例如,它们可以合并到记录的消息中。例如:

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
也就是说,
extra
不是自动记录的——您需要提供适当的格式化程序

下面是CherryPy的例程,它有效地将数据传递给stdlib的记录器:

def error(self, msg='', context='', severity=logging.INFO, traceback=False):
    """...
    This is not just for errors! Applications may call this at any time
    to log application-specific information.
    ...
    """
    if traceback:
        msg += _cperror.format_exc()
    self.error_log.log(severity, ' '.join((self.time(), context, msg)))
还可以查看的docstring。它解释了CherryPy日志记录的预期扩展

编写代码 从上面的部分,我们有一些后果。简单的回答是,你不能直接做。另外,@AndrewKloos answer实际上不是答案,因为您不能按顺序将
dict
传递给
str.join
。您甚至不能传递
额外的
关键字参数,因为签名中没有这样的正式参数。即使可以,为格式化程序提供额外的占位符也会在任何CherryPy的正常日志记录中导致字符串插值错误(这显然不提供任何额外的键)

因此,最好的折衷办法就是:

cherrypy.log('Processing finished ' + str({'task': 'jashgd-765273-ehdfiuh'}))
其他选择:

  • 除了错误和访问日志之外,创建自己的日志记录程序
  • 直接调用
    cherrypy.log.error\u log.info
  • Monkeypatch
    cherrypy.log
    和您的
    cherrypy
更新 这是一篇很好的文章(和包),它解释了CherryPy应用程序的日志层次结构和消息传递示例