Custom Logging with Python

Python’s logging module provides simple yet powerful features that allow you to log either to a file or to the console.

I decided to build something similar, albeit a minimalistic and lightweight one. It comes pretty handy when debugging large scale applications too.

Python Console Logs
Python Console Output

We have just one method – ConsoleWrite(messageType, message, variable=None)

  • messageType : Defines what the current line in the log is. The values I set for this are usually INFO, DEBUG, ERROR or WARNING. The value set here shows up after the timestamp and before the actual log.
  • message : The actual log statement.
  • variable [Default – None] : Optional parameter that can be used to debug variables. When this parameter is set, the method will print the variable type, and its value.  When I use this I like to set the value of the message parameter to the variable name.

The Code

Usage

Simply use the ConsoleWrite method like this:

Here, the ConsoleWrite method is used in both the log and debug phases.

The Output

As seen here, this gives a pretty nice, well formatted  and informative display. This can be easily modified to write to the file instead of the console.

You can view the whole code on GitHub.

Adarsh

Howdy! You're reading my blog. To know more about me click here

Leave a Reply

Your email address will not be published. Required fields are marked *