Logging in Python

Peggie Mishra
4 min readJun 5, 2023

--

Logging provides a smooth way of tracking events in python programming. In real time applications when a software developer comes across such events like debugging and troubleshooting, logging provides a wholesome experience to tackle down those occurrences in a creative way.

Logging module helps to achieve the same with its different objects, methods and levels. As we speak about levels, there are five type of them depending upon what category of logging is required & such is used.

Severity Level in order(DIWEC)

There are numerical notation of these levels as well.

CRITICAL: 50;ERROR: 40;WARNING: 30;INFO: 20;DEBUG: 10;NOTSET: 0

Levels are in sequence from debug to critical. Default level is warning. It is possible to change the level using basicConfig method of the module which lets you perform one-time configuration for setting up the basic behavior of logging. Below image depicts only “look out” is logged to stderr even if we mentioned info.

Info string not logged

Notice root after level i.e logger name which can be changed as well.

Set Level using basicConfig

info & warning logged

Set Logger Name:

Here, we are changing the name from root logger to testlog and formatting the logging by passing format argument along with levelset to info. We can also write this log to another file using filename argument and filemode which can be used for either appending or writing to the file.Default is append.

We use the above code with additional arguments filename and filemode and upon execution in the current working directory the file test1.log will be created with write mode.

Passing Arguments:

It is possible to pass arguments to levels in the log. Here, we are having two info about flowers and fruits(dict form). Logger info we are passing them as per data type(%d,%s). Notice we have used stream handler for stdout display as level is being set without basicConfig. Stream handler can send log message to stdout console. We can also log this output to a file using FileHandler.

Eg: log_fh=logging.FileHandler(“log.tx”);logger.addHandler(log_fh)

Logging to multiple destinations:

We can output log to parallel destinations like error and warnings to output console while info to files. One logger object can have multiple handlers at the same time.

Additionally, there can be multiple handlers depending upon logging needs like HTTP Handler, Queue Handler, Socket Handler etc.

Example HTTPHandler:

Here, we have used test host , http handler and request handler for serving the purpose.

Logger.py
Server.py

Console O/P:

b’{“log”: “This is a http log.”}’
127.0.0.1 — — [05/Jun/2023 15:54:05] “POST / HTTP/1.1”
200 -

Hope you enjoyed the article !

--

--

No responses yet