Dynamically Logging source filename in python without passing filename as a parameter everytime

Viewed 16

I'm trying to create a Logger which dynamically logs the filename, function_name and line number from where the logger is triggered.

I tried the following code.

log.py

import logging
logger = logging.getLogger(__name__)
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.DEBUG)

def log_message(message):
    logger.info(message) 

check.py

from log import log_message

def A():
    log_message("Error occurred")
A()

when I run check.py, it gives the output as..

[log.py:8 -          log_message() ] Error occurred

But I want it like,

[check.py:4 -          A() ] Error occurred

Is there any way to attain this dynamically without passing the filename everytime as a parameter like this.

logger.info(file_name=__name__, function_name=function_name)

Thanks.

1 Answers

you can change the stacklevel in logger.info:

import logging
logger = logging.getLogger(__name__)
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.DEBUG)


def log_message(message):
    logger.info(message, stacklevel=2)


def test():
    log_message("Hi")


test()

Output:

[scratch_1.py:20 -                 test() ] Hi
Related