I followed this guide on how to take advantage of Python's logging
module.
Now I each of my .py files get its logger by calling
logger = logging.getLogger(__name__)
The main .py file sets up logging reading a json configuration file.
import os
import json
import logging.config
def setup_logging(
default_path='logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
setup_logging()
However, I have a lot of code that was written without proper logging that simply prints an error message before exiting.
# when error occurs
sys.exit('error message')
I'd like to know if there's a way to capture those errors, format them in the same way as other errors (with timestamp) and save them in the same a error.log
file used by the logger.
This is my configuration file, logging.json
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"info_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "INFO",
"formatter": "simple",
"filename": "info.log",
"maxBytes": 10485760,
"backupCount": 20,
"encoding": "utf8"
},
"error_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "ERROR",
"formatter": "simple",
"filename": "errors.log",
"maxBytes": 10485760,
"backupCount": 20,
"encoding": "utf8"
}
},
"loggers": {
"my_module": {
"level": "ERROR",
"handlers": ["console"],
"propagate": false
}
},
"root": {
"level": "DEBUG",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
exit() The sys. exit() function is described as exiting the Python interpreter. Raise a SystemExit exception, signaling an intention to exit the interpreter.
exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.
If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys. exit("some error message") is a quick way to exit a program when an error occurs.
Unlike quit() and exit(), sys. exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.
Since sys.exit is implemented by raising the SystemExit exception, you can catch the exception and log it:
import logging
import sys
import os
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('example')
def function_will_exit():
sys.exit('some error log')
try:
function_will_exit()
except SystemExit as e:
# this log will include traceback
logger.exception('function_will_exit failed with exception')
# this log will just include content in sys.exit
logger.error(str(e))
# if you don't need exception traceback from Python
# os._exit(1)
raise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With