The native logging class in Python can be a little cumbersome and daunting to use. I've combined the use of ArgParse along with some simple use of logging as an example that solves a lot of problems I often want to solve:
This example does the following:
- Default logging level is to print warning, error, and fatal/critical error messages. Debugging and warning messages are not printed
- Using one -v option prints all of the messages above including informational messages
- Using two -v options prints all of the messages above including debugging messages
- Using three or more -v options does not change the behavior from using two options. There is no error but there is no benefit to additional options either
- You can specify an explicit log level and even reduce messages using -loglevel LEVEL where LEVEL must be one of:
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
The -loglevel LEVEL and -v options are mutually exclusive. - There's no way to dispose of messages altogether through the options but it can be done by redirecting stderr to /dev/null
- A custom format includes elements of the error that I want printed
- Logging messages go to stderr
Usage
Here's the script in action:
$ ./log_example 2019-01-18 08:26:31,929 WARNING ./log_example:16 This is a warning message 2019-01-18 08:26:31,929 ERROR ./log_example:17 This is an error message 2019-01-18 08:26:31,929 CRITICAL ./log_example:18 This is a fatal/critical message $ ./log_example -v 2019-01-18 08:26:33,893 INFO ./log_example:15 This is an informational message 2019-01-18 08:26:33,893 WARNING ./log_example:16 This is a warning message 2019-01-18 08:26:33,893 ERROR ./log_example:17 This is an error message 2019-01-18 08:26:33,894 CRITICAL ./log_example:18 This is a fatal/critical message $ ./log_example -vv 2019-01-18 08:26:35,603 DEBUG ./log_example:14 This is a debugging message 2019-01-18 08:26:35,603 INFO ./log_example:15 This is an informational message 2019-01-18 08:26:35,603 WARNING ./log_example:16 This is a warning message 2019-01-18 08:26:35,603 ERROR ./log_example:17 This is an error message 2019-01-18 08:26:35,603 CRITICAL ./log_example:18 This is a fatal/critical message $ ./log_example -vvvvvvvvv 2019-01-18 08:26:38,438 DEBUG ./log_example:14 This is a debugging message 2019-01-18 08:26:38,438 INFO ./log_example:15 This is an informational message 2019-01-18 08:26:38,438 WARNING ./log_example:16 This is a warning message 2019-01-18 08:26:38,438 ERROR ./log_example:17 This is an error message 2019-01-18 08:26:38,438 CRITICAL ./log_example:18 This is a fatal/critical message $
Comments
Post a Comment