Logging

Aidanmc
2 min readNov 1, 2020

Logging what is the point. It doesn't move the codebase forward and doesn't make introduce new functionality to your users. So really why would I need it?

While yes it does not do any of these things it can help speed up the development process, help new contributors acclimate to the code more easily and help you get back to a project that you haven't worked on for some time. Let's say you ran into a bug and wanted to figure out why the problem occurred. Without a good log, you will have to try and figure out how the problem occurred and recreate it. This could take hours of hunting just to figure out that one line of code was missing a ‘:’ or your code only accepted integers but you were passing a string. These are just simple instances of when a nice log could come in handy and let you know where and some extra information as to why it may have failed.

In this, we will just talk about the simples version of logging in Python. This would be the use of the logging module that is built into Python. This is a simple but highly complex system that can allow you to start on your logging journey.

In this library there are 5 different levels of logging messages that you can set. Bellow the level and when to use it will be described:

DEBUG

Detailed information, typically of interest only when diagnosing problems.

INFO

Confirmation that things are working as expected.

WARNING

An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.

ERROR

Due to a more serious problem, the software has not been able to perform some function.

CRITICAL

A serious error, indicating that the program itself may be unable to continue running.

Here is a simple example of how to implement your first logger:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

The default logger will only output logging for anything ‘Warning’ and above. If you would like to set logging for lower-level things you will need to change the configuration of the logger. This and more can be done by using:

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

This statement will allow logging for anything all types of messages because we set the level to DEBUG which is the lowest level. Not only did we change the level but also changed the logger to write to a file instead of the command line. This is helpful because it allows a user to more easily access and search the logs at any time. This is just a brief overview of logs there are much more advanced topics that we will delve into next time. If you would like to read more then please head to, https://docs.python.org/2/howto/logging.html.

--

--