logging – Python – Avoid passing logger reference between functions?

logging – Python – Avoid passing logger reference between functions?

You can either use the root (default) logger, and thus the module level functions logging.debug, … or get your logger in the function using it.
Indeed, the getLogger function is a factory-like function with a registry (singleton like), i.e. it always returns the same instance for the given logger name.
You can thus get your logger in count_parrots by simply using

logger = logging.getLogger(my logger) 

at the beginning. However, the convention is to use a dotted hierarchical name for your logger. See http://docs.python.org/library/logging.html#logging.getLogger


You can use a decorator to add the logging behaviour to your individual functions, for example:

def debug(loggername):
    logger = logging.getLogger(loggername) 
    def log_(enter_message, exit_message=None):
        def wrapper(f):
            def wrapped(*args, **kargs):
                r = f(*args, **kargs)
                if exit_message:
                return r
            return wrapped
        return wrapper
    return log_

my_debug = debug(my.logger)

@my_debug(enter foo, exit foo)
def foo(a, b):
    return a+b

you can hardcode the logger name and remove the top-level closure and my_debug.

You can just do :

logger = logging.getLogger(my logger) 

in your count_parrots() method. When you pass the name that was used earlier (i.e. my logger) the logging module would return the same instance that was created corresponding to that name.

Update: From the logging tutorial
(emphais mine)

getLogger() returns a reference to a
logger instance with the specified
name if it is provided, or root if
not. The names are period-separated
hierarchical structures. Multiple
calls to getLogger() with the same
name will return a reference to the
same logger object.

logging – Python – Avoid passing logger reference between functions?

The typical way to handle logging is to have a per-module logger stored in a global variable. Any functions and methods within that module then just reference that same logger instance.

This is discussed briefly in the intro to the advance logging tutorial in the documentation:

You can pass logger instances around as parameters, but doing so is typically rare.

Leave a Reply

Your email address will not be published. Required fields are marked *