Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include the function name into logging

Tags:

python

logging

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()
like image 588
alphanumeric Avatar asked Jul 15 '17 04:07

alphanumeric


1 Answers

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

like image 164
Vinay Sajip Avatar answered Nov 15 '22 20:11

Vinay Sajip