我们正在开发的Python应用程序需要一个记录器。一位同事认为,记录器应该在使用它的每个类中创建和配置。我的观点是,应该在应用程序启动时创建和配置它,并将其作为构造函数参数传递。
这两个变体都有其优点,我们不确定最佳实践是什么。
发布于 2013-08-05 11:52:45
也许这能帮你想出个主意?当然,您可以更好地读取配置文件或其他设置,但这是一个快速的例子。
配置日志记录的单独模块: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。您可以在unittest中执行类似的操作:(请注意,不需要在单元测试中导入日志模块,只要startlogging函数就足够了。通过这种方式,可以将默认级别设置为警告或错误,将单元测试和自测试设置为调试)
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...发布于 2017-02-17 15:07:24
通常不会;它通常不打算作为参数传递。
约定是在每个模块的顶部使用log = logging.getLogger(__name__)。每个模块的__name__值是不同的。然后,__name__的结果值可以反映在每个日志消息中。
发布于 2013-08-05 07:49:52
我认为把记录器作为参数传递不是个好主意。您应该将全局记录器视为自己的模块,这将是最好的主意。例如:
logger.py
import logging
log = logging.getLogger('')classFoo.py
form logger import log
log.debug('debug message')classBar.py
form logger import log
log.warn('warn!')https://stackoverflow.com/questions/18052778
复制相似问题