Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Avoid passing logger reference between functions?

Tags:

python

logging

I have a simple Python script that uses the in-built logging.

I'm configuring logging inside a function. Basic structure would be something like this:

#!/usr/bin/env python import logging import ...  def configure_logging():     logger = logging.getLogger("my logger")     logger.setLevel(logging.DEBUG)     # Format for our loglines     formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")     # Setup console logging     ch = logging.StreamHandler()     ch.setLevel(logging.DEBUG)     ch.setFormatter(formatter)     logger.addHandler(ch)     # Setup file logging as well     fh = logging.FileHandler(LOG_FILENAME)     fh.setLevel(logging.DEBUG)     fh.setFormatter(formatter)     logger.addHandler(fh)     return logger  def count_parrots():     ...     logger.debug??  if __name__ == '__main__':     logger = configure_logging()     logger.debug("I'm a log file")     parrots = count_parrots() 

I can call logger fine from inside __main__. However, how do I call logger from inside the count_parrots() function? What's the most pythonic way of handling configuring a logger like this?

like image 853
victorhooi Avatar asked May 12 '11 06:05

victorhooi


People also ask

What is logger exception in Python?

Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message.

Is Python logging using log4j?

The inbuilt logging module in python requires some handful of lines of code to configure log4j-like features viz - file appender, file rotation based on both time & size. For one-liner implementation of the features in your code, you can use the package autopylogger .

Does Python logging go to stdout?

logging - Making Python loggers output all messages to stdout in addition to log file - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


1 Answers

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

EDIT:

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):                 logger.debug(enter_message)                 r = f(*args, **kargs)                 if exit_message:                     logger.debug(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.

like image 92
Yannick Loiseau Avatar answered Sep 22 '22 22:09

Yannick Loiseau