Python logging - display the name of the script that triggers the custom logging module
I would like to get the name of the script that triggers a custom logging module.
The formatter of the logging module called module_x
is saved in logger.py
and looks like:
import logging.config
import sys
class ConsoleFormatter(logging.Formatter):
def __init__(self, datefmt, output_format):
super().__init__()
self.datefmt = datefmt
self.output_format = output_format
"""Logging Formatter to add colors and count warning / errors"""
INFO = '\033[94m'
DEBUG = '\033[37m'
WARNING = '\033[33m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
formatting = output_format
self.FORMATS = {
logging.DEBUG: DEBUG + formatting + BOLD + ENDC,
logging.INFO: INFO + formatting + BOLD +ENDC,
logging.WARNING: WARNING + formatting + BOLD + ENDC,
logging.ERROR: FAIL + formatting + BOLD + ENDC,
logging.CRITICAL: FAIL + formatting + BOLD + ENDC
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt, datefmt=self.datefmt)
return formatter.format(record)
class Log(ConsoleFormatter):
def __init__(self, datefmt=None, format=None, handlers=None):
if datefmt == None:
datefmt = "%Y-%m-%d %H:%M:%S"
if format == None:
format = "%(asctime)s [%(levelname)s] [%(filename)s] %(message)s"
super().__init__(datefmt, format)
self.logger = logging.getLogger('test')
...
In test.py
I am triggering the module using:
logs = Log()
logs.output(msg="This is the first test.", level="INFO")
With this piece of code, the display that I am getting is:
2022-01-11 16:15:28 [INFO] [logger.py] This is the first test.
I would like to get the name of the file that is triggering the logger.py
which is test.py
, not logger.py
. How can I accomplish this?
You can name a logger when calling getLogger
and you can then use this as %(name)s
in your logger format.
So in test.py
you could call with the current file name:
import os
logs = Log(name=os.path.basename(__file__))
logs.output(msg="This is the first test.", level="INFO")
and change your definition of the Log class in logger.py
to something like this:
class Log(ConsoleFormatter):
def __init__(self, name="test", datefmt=None, format=None, handlers=None): ##
if datefmt == None:
datefmt = "%Y-%m-%d %H:%M:%S"
if format == None:
format = "%(asctime)s [%(levelname)s] [%(name)s] %(message)s" ##
super().__init__(datefmt, format)
self.logger = logging.getLogger(name) ##
(Changed lines marked with ##
)