Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging sys.exit('message')

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"]
    }
}
like image 392
Agostino Avatar asked May 22 '15 02:05

Agostino


People also ask

How do you exit a message in Python?

exit() The sys. exit() function is described as exiting the Python interpreter. Raise a SystemExit exception, signaling an intention to exit the interpreter.

What does sys exit mean in Python?

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”.

What is the use of SYS exit?

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.

Is it good to use Sys exit in Python?

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”.


1 Answers

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
like image 152
tdihp Avatar answered Sep 18 '22 19:09

tdihp