For debugging, monitoring, and analyzing code execution, logging is critical in any software development process. Along with the log traces, it is sometimes useful to have the source file name and line number of the log message to determine where this log is being printed. In this article, we will different ways to log the source file name and line number in Python.

Using the logging module

Python’s built-in logging module provides a straightforward way to include the file names and line numbers in log messages.

Let’s see an example:

import logging

# Configure the logging module

# Create a logger instance
logger = logging.getLogger(__name__)

# Create a handler and set the formatter
handler = logging.StreamHandler()
formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', '%m-%d %H:%M:%S')

# Add the handler to the logger

# Log a message with source file name and line number
logger.debug("Debug message")

In the above example, we configure the logging module to set the desired log level. Then, we create a logger instance using the __name__ attribute, which represents the name of the current module.

We also created a StreamHandler to handle the log output and attach it to the logger and set a custom formatter using the pattern [%(asctime)s] p%(process)s {%(filename)s:%(lineno)d} %(levelname)s – %(message)s. This pattern includes the timestamp, process ID, file name, line number, log level, and log message in the log output.

When we use the logger to log a message with the debug level, the formatter formats the log message and includes the source file name and line number from which the log is printed.

Categorized in:

Tagged in: