2 Python log to a file
Guillem Borrell Nogueras edited this page 2023-01-26 11:09:25 +01:00
import logging
import traceback
import sys

# this raise an error

def err():
    raise ValueError("This is not the expected value")

# configure the logger handler and formatter for the log file

logger = logging.getLogger("file_logger")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("python_process.log")
fh.setLevel(logging.DEBUG)
ff = logging.Formatter(fmt='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')
fh.setFormatter(ff)
logger.addHandler(fh)

# Log known errors to a file. Logging all possible exceptions is not recommended

try:
    err()
except ValueError as e:
    logger.error(str(e))
    logger.error(traceback.format_exc())
    logger.error(sys.exc_info()[2])