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
colorlogexternal 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.
Consider this project structure tree:
Copy and paste the code above into
log.py . Then you can use it as follows:
And for the runner function
Now go ahead and run the example with:
You should see some pretty output like this:
Now open up
hello/world.py and change
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
Now if you’re really feeling crazy, throw in a
logger.error and prepare to be amazed ;)