Custom Python Logging Wrapper Using colorlog
This article introduces a custom Python logging wrapper built on the standard logging module and colorlog, explaining its design, configuration of console and file handlers, level settings, formatter setup, and usage examples to enhance debugging and monitoring across development, testing, and production phases.
A complete program relies on logs during development, testing, and runtime to monitor behavior and locate issues; the following code provides a Python 3 logging wrapper based on the standard logging library and colorlog to satisfy most logging needs.
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/10/14 上午11:18 # @Author : huaan import logging import os, sys import colorlog class Loggin: def __init__(self): self.leve = 0 self.loggin_path = os.path.join(sys.path[1], "result/logs", "test.txt") def warning(self, warning): self.colorlog().warning(warning) def debug(self, debug): self.colorlog().debug(debug) def info(self, info): self.colorlog().info(info) def critical(self, critical): self.colorlog().critical(critical) def colorlog(self): log_colors_config = { 'DEBUG': 'white', # cyan white 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } logger = logging.getLogger('logger_name') # 输出到控制台 console_handler = logging.StreamHandler() # 输出到文件 file_handler = logging.FileHandler(filename=self.loggin_path, mode='a', encoding='utf8') # 日志级别,logger 和 handler以最高级别为准,不同handler之间可以不一样,不相互影响 logger.setLevel(logging.DEBUG) console_handler.setLevel(logging.DEBUG) file_handler.setLevel(logging.INFO) # 日志输出格式 file_formatter = logging.Formatter( fmt='[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) console_formatter = colorlog.ColoredFormatter( fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S', log_colors=log_colors_config ) console_handler.setFormatter(console_formatter) file_handler.setFormatter(file_formatter) # 重复日志问题: # 1、防止多次addHandler; # 2、loggername 保证每次添加的时候不一样; # 3、显示完log之后调用removeHandler if not logger.handlers: logger.addHandler(console_handler) logger.addHandler(file_handler) console_handler.close() file_handler.close() return logger log=Loggin() if __name__ == '__main__': Loggin().warning("warning:%s") Loggin().debug("debug") Loggin().info("info")
Click the card below to follow and keep up the effort together.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.