DEV Community


Posted on

Python: Logging Overview

The first question popping up with every developer noob is my print function is working perfectly fine, and why the hell do I need a log file?

Well your 50 line code's debugging can be easily managed by the simplest of all functions - print() but when it comes to debugging those 1000 lines of code-work, most of which is a result of many sleepless night efforts, surely you need something more than print() to suffice your needs. Drum-rolls: enter Log Files.

Python has an inbuilt logging module that fulfills all the logging needs of any program.

First Things First:

There are basically 5 log levels in Python associated with numeric values which are incremented in multiples of 10.
Critical(50) - Highest Priority which needs immediate attention.
Error(40) - Minute errors which can be resolved and program can re-run.
Warning(30) - Note of caution like space issues.
Info(20) - Confirmation that something is working as expected.
Debug(10) - Detailed information, mostly used while debugging any issue.


The function takes a keyword of arguments as parameters like filename, level,format.
The default level in logging is Warning or 30, however that can be changed as passing the level as:
level=logging.DEBUG or level=logging.INFO
The format would specify what format of message do we want to store in the logfile.

The Default logger is the root logger.

However when a new file is imported and it has its own logger, the root logger of the parent file gets replaced by that of the child logger and all the logging info for the parent file gets lost.

This problem can be resolved by creating separate loggers for each file and then configuring them according to our needs.

Creating a Logger:

logger = logging.getLogger(name)

After creating a logger, we need to create a filehandler.
fileHandler = logging.FileHandler('employee.log')


sample formatting can be added to the filehandler and can be set by passing on the formatter parameter to fileHandler.setFormatter()

There are also handlers like StreamHandler,NullHandler etc.

Top comments (0)