Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Logger class and correct line number/function name in log

Tags:

python

logging

I'd like to wrap Python logger in a custom class to embed some application-specific functionality and hide setup details from developers (setting file output, logging level, etc). To do this, I created a class with the following API:

__init__(log_level, filename)
debug(msg)
info(msg)
warning(msg)
error(msg)

Logger.debug/info/warning/etc calls usually write in the log the function and line number where the log call was made. However, using my custom class, the function and line numbers written to the log file are always the same (correspondent to the debug()/info()/warning()/error() functions inside the custom class). I want it to save the line of application code that logged the msg. Is that possible?

Thanks in advance.

like image 265
Alan Evangelista Avatar asked Oct 19 '12 18:10

Alan Evangelista


People also ask

What is logging getLogger (__ Name __)?

To start logging using the Python logging module, the factory function logging. getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not.

What is logger function in Python?

Logging is a Python module in the standard library that provides the facility to work with the framework for releasing log messages from the Python programs. Logging is used to tracking events that occur when the software runs. This module is widely used by the developers when they work to logging.

Which of the following functions is are performed by logging in Python?

Logging provides a set of convenience functions for simple logging usage. These are debug() , info() , warning() , error() and critical() . To determine when to use logging, see the table below, which states, for each of a set of common tasks, the best tool to use for it.


1 Answers

Try stacklevel, which counts the number of calls from the original logging call to the logger's debug(), info(), etc., call. It's new in logging 3.8:

The third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the warnings module.

like image 103
Arthur Avatar answered Sep 24 '22 00:09

Arthur