Search code examples
pythonloggingpython-logging

How to log source file name and line number in Python


Is it possible to decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it?


Solution

  • Sure, check formatters in logging docs. Specifically the lineno and pathname variables.

    %(pathname)s Full pathname of the source file where the logging call was issued(if available).

    %(filename)s Filename portion of pathname.

    %(module)s Module (name portion of filename).

    %(funcName)s Name of function containing the logging call.

    %(lineno)d Source line number where the logging call was issued (if available).

    Looks something like this:

    formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')