Logging in Python : An Involved Introduction

Basic Logging Code

A short summary of what’s happening in the code below : We begin by importing the logging module. Then we configure the logger using basicConfig method. After that, we write our logging messages.

06/26/2020 02:59:30 PM :: WARNING : Warning message!
06/26/2020 02:59:30 PM :: ERROR : Error message!
06/26/2020 02:59:30 PM :: CRITICAL : Critical message!
  • MSGFORMAT : It describes the format in which we want to print our logs. The format writes date and time, severity level name and the log message. For most one-file applications, the format I’ve given above should suffice. Click here for a more detailed explanation of formatting.
  • DATEFMT : It describes the date time format for the message format.
  • filename : If you want to write the logs into a file, use the filename attribute to specify the filename and location. Use write mode ‘w’ or append mode ‘a’ just as it is used when writing to a file in python. If want to write the logs onto the console, do not specify a filename. As your codebase increases in size, it makes more sense to write into a log file.
  • level : When we’re logging, we’re displaying/printing/writing things based on certain severity levels. There are 5 severity levels pre-defined in python, and arranged in a hierarchy — debug(10), info(20), warning(30), error(40) and critical(50). Each error mode is also referred to by the integer mentioned in the brackets. Only log messages with severity level greater than or equal to the severity level mentioned in argument are printed. This is why only messages with severity level of warning and above get printed. This is discussed in detail in my previous article.

Configuring a Logger

We can also configure a logger object using the getLogger() method. The need for a logger object becomes evident as the code base increases in size and includes multiple files. The logger object keeps track of which code file the logs belong. We again use the basicConfig method before the instantiating the logger object.

root -- 06/26/2020 03:35:13 PM :: DEBUG : Some debug message: This time it is displayed
root -- 06/26/2020 03:35:13 PM :: WARNING : Warning message!
__main__ — 06/26/2020 03:43:26 PM :: WARNING : Warning message!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store