3
\$\begingroup\$
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?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ why not log = _getCallerLogger().debug? why dont' you set the logger in a variable instead of creating a new one 5 times? \$\endgroup\$
    – tokland
    Commented May 21, 2013 at 12:20
  • \$\begingroup\$ :) Might have over thought it on the day \$\endgroup\$
    – Nathan W
    Commented May 21, 2013 at 12:39
  • \$\begingroup\$ Well that also wouldn't work because I call these methods from all over the code base and in that case _getCallerLogger() would only be called once. \$\endgroup\$
    – Nathan W
    Commented May 21, 2013 at 12:42

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

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

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