Conditional logging in python
I want to include logging in a module, but I don't want the module to create a new log object/file, I want it to use the callers log object, whatever that may be, but only if they pass one. I know I could put all my log calls in a try block, but that's awkward. What I finally came up with seems to work, but it seems pretty kludgy and I'm sure there's开发者_Go百科 a better way to do it.
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')
What's a better way to do something like this?
Thanks!
Most loggers use the factory pattern to let some centralized resource manage which classes (if any) get loggers which actually log (instead of calling dummy functions). This means that there is a centralized API, centralized control, and there becomes no need to have loggers defined on a class-by-class basis.
It is generally a good idea to view passed parameters as a signal from one thing to another, "You need to use this object to do your job." Unless MyClass
is a logger, it doesn't really make sense to pass it one as a parameter -- it shouldn't need a logger to do its job, if it does that is bad design.
a preferred pattern:
import logging
LOGGER = logging.getLogger(__name__)
class MyClass(object):
logger = LOGGER
def do_something(self, somesuch):
self.logger.debug("Starting %s", somesuch)
myInstance = MyClass()
if need_fancy_logging:
myInstance.logger = logging.getLogger("FancyLogger")
myInstance.do_something("blabla")
EDIT: the standard logging
module really, actually does everything right, including nothing.
Python 2.7 (r27:82500, Sep 16 2010, 18:03:06)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> log = logging.getLogger('foo')
>>> log.debug('debug')
>>> log.info('info')
>>> log.error('error')
No handlers could be found for logger "foo"
>>> log.error('error')
>>>
Note that absolutely no output occurs, except a warning is printed once to indicate that message was consumed and that this particular logger is blame.
Use the functions provided by the logging
module directly, i.e.:
logging.debug('Starting')
and leave it up to the caller to change the root logger if they want to.
精彩评论