Logger implementation in Python:
Logging is a means of tracking events that happen when some software runs.The software’s developer adds logging calls to their code to indicate that certain events have occurred.Python comes with logging module.
To add Logging Module to the Python Program.
import logging
Logging Functions are names after the level or severity of the events they are used to track.The standard levels and their applicability are described below (in increasing order of severity):
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
I have created logger for my program which will take input-loglevel from properties file. I will mention the log-level in the properties file.
How to implement logger:
https://gist.github.com/IndhumathyChelliah/3a8b36392ee8277f4b6e2246c7fbed03
- Creating logger:
logger=logging.getLogger(nm)
I have created logger and nm-filename will be mentioned in the python program where we will be using this logger.
2. Reading log-level from properties file.
I have created one text file “properties.txt” and kept both files (properties.txt,log.py)in same folder.
f=open(“properties.txt”,’r’)
if f.mode==”r”:
loglevel=f.read()
if loglevel==”ERROR”:
logger.setLevel(logging.ERROR)
elif loglevel==”DEBUG”:
logger.setLevel(logging.DEBUG)
I am setting my loglevel for my logger based on the input in “properties.txt”.I have written for loglevel “ERROR” and “DEBUG”.
3.Creating Formatter:
formatter=logging.Formatter(‘%(asctime)s:%(levelname)s:%(name)s:%(message)s’)
Formatter means we are mentioning in which format, we have to print out log message.
%(asctime)s- It will log date and time. %(levelname)s-It will log the loglevel %(name)s-It will mention the logger name. %(message)s-It will log the log message.
We can do any formatting. Detailed information is available in the python docs.I have shared the link under ‘Resources” section.
4.Creating Handler:
file_handler=logging.FileHandler(‘test.log’)
In file handler, we have to mention the log file name.
5.Adding Formatters to Handlers:
file_handler.setFormatter(formatter)
Then, we have to add formatter to Filehandler.
7.Adding Handlers to logger:
logger.addHandler(file_handler)
We have to add filehandler to the logger.
Implementing logger in Python Program:
https://gist.github.com/IndhumathyChelliah/dc2f8684c35de80377363ab618b9d677
- I have imported logger — log.py created before.
from log import getLog
log- file name
getLog-methodname.
2.Setting name to logger
logger =getLog(‘student.py’)
3. Simple Python Program:
class Student: def __init__(self,firstname,lastname,rollno): self.firstname=firstname self.lastname=lastname self.rollno=rollno
logger.info(“Created Student {}-{}”.format(self.firstname,self.lastname))
I have simple Student Class and after initialization,it will log the info-firstname and lastname.
def Totalmarks(self,*args): try: totalmarks=sum(args) logger.info(“Totalmarks:”+str(totalmarks)) return totalmarks except Exception as e: logger.error(e) raise
In this method Totalmarks, we are calculating sum of all marks given.Here,logger will log the Totalmarks.If something goes wrong, it will catch the exception and log it and terminate the program there(raise- will terminate).
def grade(self,totalmarks): logger.info(“Inside Grade :”+str(totalmarks)) if totalmarks>=400: return “Grade A” elif totalmarks>=300: return “Grade B” else: return “Grade C”
Here, in this method, we are calculating Grade.Here logger will log the message “Inside Grade” and Totalmarks.
s1=Student(“indhu”,”mathy”,12) s=s1.Totalmarks(100,90,100) print (s) print (s1.grade(s))
Creating Student Object s1, and calculating Totalmarks and Grade.
Output:
290 Grade C
properties.txt
DEBUG
In properties file, mentioned loglevel as DEBUG.
test.log
Following log message is logged in file-test.log
.In ‘properties.txt’, I have mentioned as DEBUG.So loglevel is set to DEBUG.
2020–06–17 01:24:45,468:INFO:student.py:Created Student indhu-mathy 2020–06–17 01:24:45,469:INFO:student.py:Totalmarks:290 2020–06–17 01:24:45,469:INFO:student.py:Inside Grade :290
If we change the marks given like this:
s=s1.Totalmarks(100,90,”hello”)
It will raise error message and terminate the program.
test.log
2020–06–17 01:26:21,657:INFO:student.py:Created Student indhu-mathy 2020–06–17 01:26:21,657:ERROR:student.py:unsupported operand type(s) for +: ‘int’ and ‘str’
Output:
Traceback (most recent call last): File “C:python_pgmss.py”, line 30, in <module> s=s1.Totalmarks(100,90,”hello”) File “C:python_pgmss.py”, line 13, in Totalmarks totalmarks=sum(args) TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ [Finished in 0.1s with exit code 1]
If we change the loglevel in properties.txt to “ERROR” means only error message is logged.Info message will not be logged.
Note:
I have kept all three files in the same folder.
(properties.txt,log.py,student.py)
Resources:
https://docs.python.org/3/library/logging.html#logrecord-attributes
https://docs.python.org/3/howto/logging.html
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee