logging log with color

 

The print function is usually used when printing in the console, but if we need to print some progress information, which usually contains a unified format, is it more cumbersome to use the print function, in addition, when you need to write information to a file, create a file and write Information, file management and frequent opening and closing are not more dangerous. For the Python language, a logging module can solve the above problems.

1. Format setting

Use logging directly instead of where you need to print. The logging is divided into five levels: debug, info, warning, error, and critical (the levels are sequentially increased). By default, only the levels above warning are printed: warning, error, critical If you need to print the log above debug and modify the print format, you need to set logging through the basicConfig function.

logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.DEBUG)

Among them format to set the printing format, the specific meaning can refer to https://blog.csdn.net/orca123456/article/details/84864785

level is the minimum level for printing. Because debug <info <warning <error <critical, when set to debug, all levels of logs will be printed.

Second, save the file

 By default, logging is only output to the console and will not be saved to the file system. If you need to save the log, you need to get the logging object through the getLogger () method to set it. Refer to https://www.cnblogs.com/nancyzhu/p/8551506.html

import logging
from logging import handlers

class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期(interval==0时代表星期一)
        # midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)
if __name__ == '__main__':
    log = Logger('all.log',level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    Logger('error.log', level='error').logger.error('error')

 

Three, with color log

Under normal circumstances, we want logs with colors, usually error and critical are indicated in red, warning is indicated in orange, and info is indicated in green. In addition, I do n’t want to use log.logger for such a long time, and I do n’t want to regenerate an object every time before application. The following is the specific implementation.

import logging
from colorma import Fore,style


# 获取对象
def get_logger():
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    if not logger.handlers:
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            " %(message)s")
        ch.setFormatter(formatter)
        logger.addHandler(ch)
    return logger

#通过静态成员方法来调用
class Log:

    logger = get_logger()

    @staticmethod
    def debug(msg):
        Log.logger.debug(Fore.WHITE + "[DEBUG]: " + str(msg) + Style.RESET_ALL)

    @staticmethod
    def info(msg):
        Log.logger.info(Fore.GREEN + "[INFO]: " + str(msg) + Style.RESET_ALL)

    @staticmethod
    def warning(msg):
        Log.logger.warning("\033[38;5;214m" + "[WARNING]: " + str(msg) + "\033[m")

    @staticmethod
    def error(msg):
        Log.logger.error(Fore.RED + "[ERROR]: " + str(msg) + Style.RESET_ALL)

    @staticmethod
    def critical(msg):
        Log.logger.critical(Fore.RED + "[CRITICAL]: " + str(msg) + Style.RESET_ALL)

When you use it, you only need to import Log, you can use it directly in specific places (such as Log.info ("I am green")), and you can see that the log color has changed.

But when the file needs to be written, how can the filename be passed in through encapsulation? This content will be updated later

Published 42 original articles · praised 4 · 10,000+ views

Guess you like

Origin blog.csdn.net/wangyhwyh753/article/details/105277142