简体   繁体   English

如何将不同的类记录到不同的文件中?

[英]How to log different classes into different files?

Let's say I have different classes defined like this假设我有这样定义的不同类

class PS1:
    def __init__(self):
        pass

    def do_sth(self):
        logging.info('PS1 do sth')

class PS2:
    def __init__(self):
        pass

    def do_sth(self):
        logging.info('PS2 do sth')

How can I make PS1 log into PS1.log and PS2 log into PS2.log?如何让 PS1 登录 PS1.log 和 PS2 登录 PS2.log? I know I can set up loggers and file handlers and do something likes ps1_logger.info instead of logging.info .我知道我可以设置记录器和文件处理程序并执行类似ps1_logger.info而不是logging.info的操作。 However, my current code base already has hundreds of logging.info , do I have to change them all?但是,我当前的代码库已经有数百个logging.info ,我必须全部更改吗?

When you call logging methods on the module level you are creating logs directly at the root logger, so you no longer can separate them by logger.当您在模块级别调用日志记录方法时,您将直接在根记录器上创建日志,因此您不再可以通过记录器将它们分开。 The only chance left is to separate your logs by Handler with a filter.剩下的唯一机会是使用过滤器按处理程序分隔日志。 Since you don't want to update your logging calls to add any information about where the call happens you have to inspect the stack to find the calling class.由于您不想更新日志调用以添加有关调用发生位置的任何信息,因此您必须检查堆栈以找到调用 class。 The code below does this, but I highly recommend not using this solution in production and refactor your code to not send everything to the root logger.下面的代码执行此操作,但我强烈建议不要在生产中使用此解决方案,并重构您的代码以不将所有内容发送到根记录器。 Look into logging adapters and/or the extra keyword argument for an alternative solution that modifies the logging calls.查看日志适配器和/或额外的关键字参数,以获得修改日志调用的替代解决方案。

import logging
import inspect


root = logging.getLogger()

ps1_handler = logging.FileHandler('ps1.log')
ps2_handler = logging.FileHandler('ps2.log')

def make_class_filter(class_name):
    def filter(record):
        for fi in inspect.stack():
            if 'self' in fi[0].f_locals and class_name in str(fi[0].f_locals['self']):
                return True 
        return False
    return filter

ps1_handler.addFilter(make_class_filter('PS1'))
ps2_handler.addFilter(make_class_filter('PS2'))

root.addHandler(ps1_handler)
root.addHandler(ps2_handler)

class PS1:
    def do_sth(self):
        logging.warning('PS1 do sth')

class PS2:
    def do_sth(self):
        logging.warning('PS2 do sth')


PS1().do_sth()
PS2().do_sth()

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

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