0

I have a question which is a follow up to this question. I want the logger statement in the imported function to include the name of the main function that called it.

#!python3
import logging
from logging import config

config.fileConfig("logger_config.conf", defaults={'logfilename': 'myapp.log'})
logger = logging.getLogger(__name__)

from utils import fetch_user_info

def events():
    logger.info("In the main function")
    print("main function")
    fetch_user_info("john")

if __name__ == '__main__':
    events()

utils.py:

#!python3
import logging
logger = logging.getLogger(__name__)

def fetch_user_info(name):
    logger.info("In fetch_user_info grabbing user info for {}".format(name))
    return 

In my log file I see this

2023-02-02 08:42:46,727:INFO    :events:__main__:events:11 In the main function
2023-02-02 08:42:46,727:INFO    :utils:utils:fetch_user_info:8 In fetch_user_info grabbing user info for john

I have multiple programs importing this utils.py file. How do I configure the log statement in the function to include the name of the calling program - events like the following

2023-02-02 08:42:46,727:INFO    :events:__main__:events:11 In the main function
2023-02-02 08:42:46,727:INFO    :events:utils:fetch_user_info:8 In fetch_user_info grabbing user info for john

my logger_config.conf

[loggers]
keys=root

[handlers]
keys= timedRotatingFileHandler

[formatters]
keys=timedRotatingFormatter

[logger_root]
handlers = timedRotatingFileHandler
level = DEBUG

[handler_timedRotatingFileHandler]
class = handlers.TimedRotatingFileHandler
level = DEBUG
formatter = timedRotatingFormatter
args=('%(logfilename)s','midnight', 7)

[formatter_timedRotatingFormatter]
format = %(asctime)s:%(levelname)-8s:%(module)s:%(name)s:%(funcName)s:%(lineno)d %(message)s
Ravi M
  • 71
  • 7

0 Answers0