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.
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:
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:
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:
You’ll also notice that some new files have been created:
The warning and error logs will be empty, but you’ll see the full output has been copied into app.log
:
Now if you’re really feeling crazy, throw in a logger.warning
or logger.error
and prepare to be amazed ;)