Logging is one of the crucial steps in software development. While working on any project, we need to record the details in order to debug and analyse our code, this is where log decorators comes into play. It will not log the details, but also save us a lot of time, help to minimize lines of code and most importantly will help us to maintain cleaner and modular code.

I researched a lot about implementing log decorators and struggled to resolve a lot of use cases which came while implementing it in one of my project and hence came up with a related appropriate approach.

Defining the get_logger() function :

We create our first file, log.py in which we define a _get_logger()_ function. Here, we will create and return a logger object using the_Logging_ module in python.

In _get_logger(),_ we will pass two parameters - log_file_name and log_sub_dir, which we want to set. Then we will create a log path if it does not exist. Create a logger object using the_Logger()_ function of the_Logging_ module.

get_logger()

After creating a logger object, we need to add a formatter and levelin order to specify the format for our log text file.

Add Formatter in get_logger():

add formatting in get-logger()

We will create a FileHandler and specify our own log format using CustomFormatter().

So, Why are we using the customFormatter class?

The logging decorator, logs the file and function name where it’s defined not where it’s used.

For example, if we are using a decorator to log the file main.py and defined the log decorator in log_decorator.py. Then, in our log file even though we are logging main.py, it will take function name and file name of log_decorator.py from where we are calling.

To get the actual file name and function name we have defined our own custom class named as customFormatter by overiding their values.

custom_formatter()

Now, let us set the logging level.

Setting level:

There are various levels in python in which one can log details. When a logger is created, the level defaults to NOTSET.

LEVEL      NUMERIC VALUE
CRITICAL : 50
ERROR    : 40
WARNING  : 30
INFO     : 20
DEBUG    : 10
NOTSET   : 0

#logging #python3 #python #decorators

Add Log Decorators to Your Python Project
6.10 GEEK