Logging is very useful for programmer at debuging side. It will keep track of the logs/operations performed during the program.

Python provides the standard library to perform logging.You can get the information, debug the program, generate warning or error.

We will see the very useful usecase of  logging in decorators.

So, by considering the example taken in the decorators we are going to discuss logging.

Using logging, we can keep track of what arguments executed

In [1]:

## Now this nested function will be able to handle any no. of arguments - zero, one , so on arguments and also able to handle ## key value pair arguments as well.
def company(decorated_function):
## Importing logging module
import logging
## Creating a file to store the logging info
logging.basicConfig(filename 'company_log_file.log',level=logging.INFO)

  ## *args => any no. of aruguments ## **kwargs => any no. of key value pair value or dictionary values

def wrapper_function(*args, **kwargs):
## Info to be written in that file.
logging.info('{} function ran with args {} and kwargs {}'.format(decorated_function.__name__,args,kwargs))
return decorated_function(*args, **kwargs)
return wrapper_function

Creating a function with arguments to be passed in a decorator funtion

In this calculating the office hours, we are keeping track of what variables are used by using logging functionality in the outer function.In [2]:

## Function with arguments
@ company
def office_hours(start_time,finish_time):
return ('Hi! Your office hours will be ' + str((int(finish_time.split(':')[0]) - int(start_time.split(':')[0])))+ ' hours.')

In [3]:



'Hi! Your office hours will be 8 hours.'

Created another function without arguments to be passed in the decorator function.

In [4]:

@ company
def new_employee():
print('Hi! Welcome to Robofied team')

In [5]:

## This function will also work fine as our function can handle any no. of arguments - zero, one, two etc..

Hi! Welcome to Robofied team

After running these two function when we will check our log file created by using “config” command, will be created in a same directory and stores the log as -:

Log file(company_log_file.log) contains these outputs -:

INFO:root:office_hours function ran with args (’10:00′, ’18:00′) and kwargs {}
INFO:root:new_employee function ran with args () and kwargs {}

Hope you are clear with the logging concepts. Stay tuned! Keep learning with us.

Leave a Comment

Your email address will not be published. Required fields are marked *