HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Any side effects from this Python logging code?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisloggingsideanyeffectspythoncodefrom

Problem

def _getCallerLogger():
    caller = inspect.currentframe().f_back.f_back
    name = "{}-{}".format(caller.f_globals['__name__'], caller.f_code.co_name )
    logger = logging.getLogger(name)
    return logger

log = lambda msg : _getCallerLogger().debug(msg)
info = lambda msg: _getCallerLogger().info(msg)
warning = lambda msg: _getCallerLogger().warning(msg)
error = lambda msg: _getCallerLogger().error(msg)
critical = lambda msg: _getCallerLogger().critical(msg)


I have the above logging code in my application so I can just call log from anywhere and it will print the file and where the log method was called from.

Would there be anything wrong with this in the long run?

Solution

The logging module already supplies a function name to log messages. If you want to include the function name in your log message just set the appropriate formatter with %(funcName)s in the format string on your log handler with: http://docs.python.org/2/library/logging.html#logging.Handler.setFormatter

See also http://docs.python.org/2/library/logging.html#logrecord-attributes

The typical usage is to create a global log variable in your module like

logger = logging.getLogger(__name__)


and use that logger within functions in that module. But creating a separate logger for every single function is excessive.

I (just now) realized this is a pretty old question, but if you're still interested I can provide a full working example.

Code Snippets

logger = logging.getLogger(__name__)

Context

StackExchange Code Review Q#26400, answer score: 3

Revisions (0)

No revisions yet.