From c8e2274e5922daa696efa1aedd52882421fbb4ad Mon Sep 17 00:00:00 2001 From: Guillem Borrell Nogueras Date: Thu, 26 Jan 2023 11:09:10 +0100 Subject: [PATCH] Add 'Python log to a file' --- Python-log-to-a-file.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python-log-to-a-file.md diff --git a/Python-log-to-a-file.md b/Python-log-to-a-file.md new file mode 100644 index 0000000..8ba5126 --- /dev/null +++ b/Python-log-to-a-file.md @@ -0,0 +1,29 @@ +``` +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]) +``` \ No newline at end of file