10

Running the code below prints out two messages:

[INFO] 2017-07-14 21:42:07, printed by func A
[INFO] 2017-07-14 21:42:07, printed by func B

We know that the logging module's formatter method can be used to customize the format of the messages. We can configure it to start the logging messages with the current time or the verbosity level or with the date and etc. I wonder if there is a way to include the function name from where the log is being created. So, every time the log.info() method is used there is a name of the function and possibly even a code line number too.

import logging
formatter = logging.Formatter("[%(levelname)s] %(asctime)s, %(message)s", "%Y-%m-%d %H:%M:%S")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log = logging.getLogger(__name__)
log.addHandler(handler)
log.setLevel(logging.DEBUG)


def funct_A():
    log.info('printed by func A')

def funct_B():
    log.info('printed by func B')


funct_A()
funct_B()
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • Does this answer your question? [Python Logging (function name, file name, line number) using a single file](https://stackoverflow.com/questions/10973362/python-logging-function-name-file-name-line-number-using-a-single-file) – 9769953 Dec 24 '21 at 07:14

1 Answers1

17

Just use %(funcName)s, as documented here.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191