6

I've recently been assigned to a new project because I'm one of the only developers at my company who has used Python extensively in the past. My first task was to clean up the code base and make it more Pythonic - while doing so I came across this:

import logging   # The builtin logging module

def logInfo(message):
    logger = logging.getLogger('')
    logger.info(message)

def logError():
    logger = logging.getLogger('')
    logger.error('Failed: {0}'.format(traceback.format_exc()))

def logCritical(message):
    logger = logging.getLogger('')
    logger.critical(message)

def logWarning(message):
    logger = logging.getLogger('')
    logger.warn(message)

def logDebug(message):
    logger = logging.getLogger('')
    logger.debug(message)

This smells pretty bad to me - it seems that a much cleaner solution would be to just create a global logger object at the top of the file, and then just use the normal logger.debug|info|error|warn|critical functions. Am I overthinking this?

Of course, then there is all of the hairiness of a global object - in which case maybe I'd do something like

@memoize
def getLogger(name='__main__'):
    return logging.getLogger(name)

With an appropriate memoizing function.

This is a pretty young project still, so we have a lot of freedom in how we set this up.

3
  • Does the argument to logging.getLogger('') matter? In the code I work on, a global logger per-file is a good thing because each file can give it a different string to prepend its messages with, which makes it easier to sift through logs later. If this code is ignoring that argument it seems like it's just not using the logger properly.
    – Ixrec
    Jul 17, 2015 at 21:59
  • 1
    This looks like a good idea that got poorly implemented. The idea was to have separate formatting and features when logging various types of messages. Something reassembling Strategy Pattern, however, it ended up being implemented in "copy-paste" fashion.
    – Alexus
    Jul 17, 2015 at 22:31
  • @Ixrec Yes, it does. docs.python.org/3.3/library/logging.html#logging.getLogger Jul 17, 2015 at 23:23

1 Answer 1

6

A common way is, to define one global logger at the beginning of the module with:

import logging
logger = logging.getLogger(__name__)

so it's easier to assign different log-levels to different modules. If you don't have a distinguishing logger name, you can directly use the log-functions of logging; instead of logDebug simply write logging.debug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.