通过logging与ctypes打印不同颜色的日志,loggingctypes日志,1.log在CMD显示与


1.log在CMD显示与记录在硬盘上的文件

2.针对不同级别的log使用不同的颜色显示

#! /usr/bin/env python#coding=gbkimport logging,osimport ctypesFOREGROUND_WHITE = 0x0007FOREGROUND_BLUE = 0x01 # text color contains blue.FOREGROUND_GREEN= 0x02 # text color contains green.FOREGROUND_RED  = 0x04 # text color contains red.FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREENSTD_OUTPUT_HANDLE= -11std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)def set_color(color, handle=std_out_handle):    bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)    return boolclass Logger:    def __init__(self, path,clevel = logging.DEBUG,Flevel = logging.DEBUG):        self.logger = logging.getLogger(path)        self.logger.setLevel(logging.DEBUG)        fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')        #设置CMD日志        sh = logging.StreamHandler()        sh.setFormatter(fmt)        sh.setLevel(clevel)        #设置文件日志        fh = logging.FileHandler(path)        fh.setFormatter(fmt)        fh.setLevel(Flevel)        self.logger.addHandler(sh)        self.logger.addHandler(fh)    def debug(self,message):        self.logger.debug(message)    def info(self,message):        self.logger.info(message)    def war(self,message,color=FOREGROUND_YELLOW):        set_color(color)        self.logger.warn(message)        set_color(FOREGROUND_WHITE)    def error(self,message,color=FOREGROUND_RED):        set_color(color)        self.logger.error(message)        set_color(FOREGROUND_WHITE)    def cri(self,message):        self.logger.critical(message)if __name__ =='__main__':    logyyx = Logger('yyx.log',logging.WARNING,logging.DEBUG)    logyyx.debug('一个debug信息')    logyyx.info('一个info信息')    logyyx.war('一个warning信息')    logyyx.error('一个error信息')    logyyx.cri('一个致命critical信息')#该片段来自于http://byrx.net

评论关闭