Logging in Python

Hello all,

This is the ninth article in the series Python for Data Science. If you are new to this series, we would recommend you to read our previous articles

  1. Python for Data Science Series - Part 1
  2. Python for Data Science Series - Part 2
  3. Using Numpy in Python
  4. Using Pandas in Python
  5. Data Visualization using Matplotlib Python
  6. Parsing XML file in python
  7. Parsing Json file in python
  8. Interactive Data Visualization using Plotly in Python


Please refer the videos below for detailed explanation on how to use logging in Python


Please refer the following code to understand on how to implement logging in python





In [1]:
import logging
import os
In [2]:
main_folder_path = r"E:\openknowledgeshare.blogspot.com\Python\Outputs"
log_file_path = os.path.join(main_folder_path,'mylogfile.log')
logging.basicConfig(filename=log_file_path, filemode='w', format='%(name)s - %(levelname)s - %(message)s',level=logging.INFO)
In [3]:
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

a = 5
b = 0

try:
  c = a / b
except Exception as e:
  logging.error("Exception occurred", exc_info=True)

Viewing Log File

In [4]:
f = open(log_file_path,'r')
log_data = f.readlines()
f.close()
for each_line in log_data:
    print(each_line)
root - INFO - This is an info message

root - WARNING - This is a warning message

root - ERROR - This is an error message

root - CRITICAL - This is a critical message

root - ERROR - Exception occurred

Traceback (most recent call last):

  File "<ipython-input-3-acc57b75bdb0>", line 11, in <module>

    c = a / b

ZeroDivisionError: division by zero

In [ ]:
 

Comments

Popular posts from this blog

How to run Jupyter Notebooks in Cloud

GUI Programming using Tkinter Python

How to download , install and configure Anaconda - Python