From 80c08677e0437b7567ebc3ff4567aefc6bc77bb4 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Tue, 11 Oct 2022 13:10:38 +0800 Subject: [PATCH] feat: logger module --- demo.py | 10 ++++++++++ logger.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 demo.py create mode 100644 logger.py diff --git a/demo.py b/demo.py new file mode 100644 index 0000000..802f415 --- /dev/null +++ b/demo.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from logger import logger + +logger.debug('debug') +logger.info('info') +logger.warning('warning') +logger.error('error') +logger.critical('critical') diff --git a/logger.py b/logger.py new file mode 100644 index 0000000..b9f9a06 --- /dev/null +++ b/logger.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import sys +import logging +import colorlog + +logColor = { # log color + 'DEBUG': 'white', + 'INFO': 'green', + 'WARNING': 'yellow', + 'ERROR': 'red', + 'CRITICAL': 'bold_red', +} + +dateFormat = '%Y-%m-%d %H:%M:%S' +timeFormat = '%(asctime)s.%(msecs)03d' +logFormat = '[%(levelname)s] %(message)s (%(module)s.%(funcName)s:%(lineno)d)' + +# load fileHandler -> log file +fileHandler = logging.FileHandler('runtime.log', encoding = 'utf-8') +fileHandler.setFormatter(logging.Formatter( + '[' + timeFormat + '] ' + logFormat, + datefmt = dateFormat +)) +fileHandler.setLevel(logging.DEBUG) # debug level for log file + +# load stdHandler -> stderr +stdHandler = colorlog.StreamHandler() +stdHandler.setFormatter(colorlog.ColoredFormatter( + '%(light_black)s' + timeFormat + '%(log_color)s ' + logFormat, + datefmt = dateFormat, + log_colors = logColor, + stream = sys.stderr +)) +stdHandler.setLevel(logging.INFO) # info level for stderr + +logger = logging.getLogger() +logger.addHandler(stdHandler) +logger.addHandler(fileHandler) +logger.setLevel(logging.DEBUG) # set log level in handler