Python Logging Example (with color formatting & file handlers)

I show a function that initializes a logging object for use in my python modules. This lets me outputs colored logs to the screen and also routes them into files. I have separate files for all output, warnings, and errors. I’ll also show an example of how this function can be used with your project.

Image for post

Here’s the function:

  • It uses the colorlog external dependency (GitHub) - pip install colorlog .
  • I’m using an f-string here, which is only works for Python 3.6+. If needed, do yourself a favour and upgrade. If you can’t upgrade then just reformat this line.

Example usage

Consider this project structure tree:

Image for post

Copy and paste the code above into log.py . Then you can use it as follows:

For world.py :

And for the runner function app.py :

Now go ahead and run the example with:

python app.py

You should see some pretty output like this:

Image for post

Now open up hello/world.py and change testing_mode to True. Run the app again and you should see the debug line being triggered:

Image for post

You’ll also notice that some new files have been created:

Image for post

The warning and error logs will be empty, but you’ll see the full output has been copied into app.log :

Image for post

Now if you’re really feeling crazy, throw in a logger.warning or logger.error and prepare to be amazed ;)

Written by

Python Data Engineer, MSc. Physics

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