Created
July 10, 2024 07:50
-
-
Save singleghost2/11fd210caad8b49d68d91834fc425355 to your computer and use it in GitHub Desktop.
A beautiful custom logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import time | |
from colorama import init, Fore, Style | |
init(autoreset=True) # 初始化colorama并设置自动重置 | |
# 创建一个自定义的日志记录格式,包括颜色设置和时间格式 | |
class CustomFormatter(logging.Formatter): | |
format_dict = { | |
logging.DEBUG: Fore.CYAN + "[%(custom_time)s] %(levelname)s: %(message)s" + Style.RESET_ALL, | |
logging.INFO: Fore.GREEN + "[%(custom_time)s] %(levelname)s: %(message)s" + Style.RESET_ALL, | |
logging.WARNING: Fore.YELLOW + "[%(custom_time)s] %(levelname)s: %(message)s" + Style.RESET_ALL, | |
logging.ERROR: Fore.RED + "[%(custom_time)s] %(levelname)s: %(message)s" + Style.RESET_ALL, | |
logging.CRITICAL: Fore.RED + Style.BRIGHT + "[%(custom_time)s] %(levelname)s: %(message)s" + Style.RESET_ALL, | |
} | |
def format(self, record): | |
# 创建一个新记录,以避免修改原始记录 | |
record_copy = logging.LogRecord(record.name, record.levelno, record.pathname, record.lineno, | |
record.msg, record.args, record.exc_info, record.funcName) | |
# 设置时间戳,包括毫秒部分 | |
ct = time.gmtime(record.created + 8 * 3600) # 使用UTC时间 | |
t = time.strftime("%Y-%m-%dT%H:%M:%S", ct) | |
s = "%s.%03dZ" % (t, record.msecs) | |
record_copy.custom_time = s | |
# 使用修改后的记录 | |
log_fmt = self.format_dict.get(record.levelno) | |
formatter = logging.Formatter(log_fmt) | |
return formatter.format(record_copy) | |
def setup_custom_logger(name, level=logging.DEBUG): | |
# 创建日志记录器,并设置日志级别 | |
logger = logging.getLogger(name) | |
logger.setLevel(level) | |
# 使用特定格式的时间字符串,设置日志处理器和格式化器 | |
ch = logging.StreamHandler() | |
ch.setLevel(level) | |
ch.setFormatter(CustomFormatter()) | |
# 将处理器添加到日志记录器 | |
logger.addHandler(ch) | |
return logger | |
if __name__ == "__main__": | |
logger = setup_custom_logger("test_logger") | |
# 测试log输出 | |
logger.debug("这是一个 debug 信息") | |
logger.info("这是一个 info 信息") | |
logger.warning("这是一个 warning 信息") | |
logger.error("这是一个 error 信息") | |
logger.critical("这是一个 critical 信息") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment