python logging messages and exit codes
Everyone knows that an application exit code should change based on the success, error or maybe warnings that happened during execution.
Lately i came along some python code that was structured the following way:
the situation was a little bit more complicated, some functions in other modules also exited the application, so sys.exit() calls were distributed in lots of modules an files.
Exiting the application in some random function of another module is something i dont consider nice coding style, because it makes it hard to track down errors.
- exit code 0 on success
- exit code 1 on errors
- exit code 2 on warnings
- warnings or errors shall be logged in the function where they actually happen: the logging module will show the function name with a better format option: nice for debugging.
- one function that exits accordingly, preferrably main()
How to do better?
As the application is using the logging module, we have a single point to collect warnings and errors that might happen accross all modules. This works by passing a custom handler to the logging module which tracks emitted messages.
Heres an small example:
This also makes easy to define something like:
- hey, got 2 warnings, change exit code to error?
- got 3 warnings, but no –strict passed, ingore those, exit with success!