【问题标题】:How can Python Bottle templates be used in a Formatter for the Logging modulePython Bottle 模板如何在 Logging 模块的格式化程序中使用
【发布时间】:2017-10-09 12:51:50
【问题描述】:

有没有办法将 Python logging module 配置为将 Bottle templating engine 用作 Formatter

user_table_template = '''\
Logged-in users:
% for username, session_id in user_table:
  {{ username }} --> {{ session_id }}
% end
'''

logging.info(user_table_template, user_table=user_table)

【问题讨论】:

    标签: python logging template-engine bottle formatter


    【解决方案1】:

    您可以使用自定义消息类执行此操作,其__str__ 方法会执行实际格式化,如下例所示(未测试):

    from bottle import SimpleTemplate
    class BottleTemplateMessage(object):
        def __init__(self, source, **kwargs):
            self.template = SimpleTemplate(source)
            self.context = kwargs
    
        def __str__(self):
            return self.template.render(**self.context)
    

    然后

    import logging
    logging.warning(BottleTemplateMessage('Hello, {{name}}!', name='world'))
    

    应该打印类似的东西

    WARNING:root:Hello, world!
    

    【讨论】:

    • 有没有办法在上游注入这种行为,以便调用者代码简化为logging.warning('Hello, {{name}}!', name='world')
    • 并非没有诸如使用适配器并通过该适配器记录的方法(以便第三方库继续正常记录 - 如果您不使用 any 第三方代码,那么我想Logger 可以被子类化...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2023-03-27
    • 2011-08-03
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多