我想在模块中包括日志记录,但是我不希望模块创建新的日志对象/文件,我希望它使用调用者日志对象,无论是什么,但前提是它们必须通过。我知道我可以将所有日志调用放在try块中,但这很尴尬。我最终想出的方法似乎可以奏效,但似乎很费解,而且我敢肯定有更好的方法可以做到这一点。
class MyClass(object):
def __init__(self, arg1, arg2, log=None):
if log == None:
class log(object):
def error(self, msg): pass
def warning(self, msg): pass
def info(self, msg): pass
def debug(self, msg): pass
self.log = log()
else:
self.log = log
self.log.debug('Starting')
Run Code Online (Sandbox Code Playgroud)
什么是做这样的更好的方法?
谢谢!
直接使用模块提供的功能logging,即:
logging.debug('Starting')
Run Code Online (Sandbox Code Playgroud)
并让调用者根据需要更改根记录器。