是否应该将Python记录器作为参数传递? [英] Should a Python logger be passed as parameter?

查看:58
本文介绍了是否应该将Python记录器作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发的Python应用程序需要一个记录器.一位同事认为,应该在使用记录器的每个类中创建和配置记录器.我的意见是,应在应用程序启动时创建和配置它,并以构造函数参数形式传递它.

A Python application we're developing requires a logger. A coworker argues that the logger should be created and configured in every class that's using it. My opinion is that it should be created and configured on application start and passed as a constructor-parameter.

这两种变体都有其优点,我们不确定最佳实践是什么.

Both variants have their merits and we're unsure what the best practice is.

推荐答案

也许这可以帮助您获得想法?当然,您可以做得更好,从配置文件或其他任何文件中读取设置,但这只是一个简单的示例.

Maybe this helps you to get an idea? Of course you can make it much better, reading settings from a config file or whatever but this is quick example.

用于配置日志记录的单独模块:mylogmod.py:

A separate module to configure the logging: mylogmod.py :

import logging

FILENAME = "mylog.log" # Your logfile
LOGFORMAT = "%(message)s" # Your format
DEFAULT_LEVEL = "info" # Your default level, usually set to warning or error for production
LEVELS = {
    'debug':logging.DEBUG,
    'info':logging.INFO,
    'warning':logging.WARNING,
    'error':logging.ERROR,
    'critical':logging.CRITICAL}

def startlogging(filename=FILENAME, level=DEFAULT_LEVEL):
    logging.basicConfig(filename=filename, level=LEVELS[level], format=LOGFORMAT)

main.py:

import logging
from mylogmod import startlogging
from myclass import MyClass

startlogging()

logging.info("Program started...")
mc = MyClass()

具有自测模块的类myclass.py.您可以在单元测试中执行类似的操作:(请注意,您无需在单元测试中导入日志记录模块,只需startlogging函数就足够了.这样,您可以将默认级别设置为警告或错误以及单元测试和自我测试进行调试)

A class myclass.py from a module with self test. You can do something similar in a unittest: (Note that you don't need to import the logging module in a unittest, just the startlogging function is enough. This way you can set the default level to warning or error and the unittests and self tests to debug)

import logging

class MyClass(object):
    def __init__(self):
        logging.info("Initialze MyClass instance...")

if __name__ == "__main__":
    from mylogmod import startlogging
    startlogging(level="debug")
    logging.debug("Test MyClass...")
    #... rest of test code...

这篇关于是否应该将Python记录器作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆