Python记录器打印两次

时间:2019-04-08 14:48:20

标签: python-3.x logging argparse custom-formatting

我创建了一种自定义格式,可以根据记录的级别以不同的颜色打印到粗壮的颜色。

问题是我两次打印到终端。 我正在尝试摆脱基本的记录器输出

这是我的代码:

import argparse
import logging
import sys
from logging.handlers import RotatingFileHandler
from logging import handlers










myself = lambda: inspect.stack()[1][3]
logger = logging.getLogger(__name__)
class MyFormatter(logging.Formatter):
"""
class to handle the logging formatting
"""
# ----------------------------

 PURPLE = '\033[95m'
 CYAN = '\033[96m'
 DARKCYAN = '\033[36m'
 BLUE = '\033[94m'
 GREEN = '\033[92m'
 YELLOW = '\033[93m'
 RED = '\033[91m'
 BOLD = '\033[1m'
 UNDERLINE = '\033[4m'
 END = '\033[0m' 

 err_fmt = "[\033[91m%(levelname)-5s\033[0m] \033[91m%(message)s\033[0m"
 dbg_fmt = "[\033[36m%(levelname)-4s\033[0m] [\033[36m% (filename)s\033[0m:\033[36m%(lineno)d\033[0m] \033[36m%(message)s\033[0m"
 dbgplus_fmt = "[\033[92m%(levelname)-8s\033[0m] (\033[92m%(filename)s:% (lineno)d\033[0m) \033[92m%(message)s\033[0m"
 info_fmt = "[\033[94m%(levelname)-4s\033[0m] \033[94m%(message)s\033[0m"
 warn_fmt = "[\033[93m%(levelname)-7s\033[0m] \033[93m%(message)s\033[0m"


 def format(self, record):

    # Save the original format configured by the user
    # when the logger formatter was instantiated
    format_orig = self._style._fmt

    # Replace the original format with one customized by logging level
    if record.levelno == logging.DEBUG:

        self._style._fmt = MyFormatter.dbg_fmt

    elif record.levelno == logging.INFO:
        self._style._fmt = MyFormatter.info_fmt

    elif record.levelno == logging.ERROR:
        self._style._fmt = MyFormatter.err_fmt

    elif record.levelno == logging.WARNING:
        self._style._fmt = MyFormatter.warn_fmt

    elif record.levelno == 5:
        self._style._fmt = MyFormatter.dbgplus_fmt

    # Call the original formatter class to do the grunt work
    result = logging.Formatter.format(self, record)

    # Restore the original format configured by the user
    self._style._fmt = format_orig

    return result
def main():
       logger.info('info')
       logger.debug('debug')
       logger.warning('warn')
       logger.error('error')
       logger.log(5, "debug plus")


if __name__ == '__main__':




 parser = argparse.ArgumentParser(description='Run CORMAT_py')
 parser.add_argument("-d", "--debug", type=int,
                    help="Debug level. 0: Info, 1: Warning, 2: Debug,"
                         " 3: Error, 4: Debug Plus; \n default level is    
 INFO", default=0)
 parser.add_argument("-doc", "--documentation", type=str,
                    help="Make documentation. yes/no", default='no')

 args = parser.parse_args(sys.argv[1:])


 debug_map = {0: logging.INFO,
             1: logging.WARNING,
             2: logging.DEBUG,
             3: logging.ERROR,
             4: 5}

 logging.addLevelName(5, "DEBUG_PLUS")
 logger = logging.getLogger(__name__)
 logging.basicConfig(level=debug_map[args.debug])

 fmt = MyFormatter()
 hdlr = logging.StreamHandler(sys.stdout)


 hdlr.setFormatter(fmt)
 logging.root.addHandler(hdlr)
 fh = handlers.RotatingFileHandler('./LOGFILE.DAT', mode = 'w',maxBytes= (1048576*5), backupCount=7)
 fh.setFormatter(fmt)
 logging.root.addHandler(fh)






 main()

我尝试删除basicConfig命令(这似乎导致两次打印)

但是如果我写这个

logging.addLevelName(5, "DEBUG_PLUS")
logger = logging.getLogger(__name__)
logger.setLevel(debug_map[args.debug])

我丢失了来自模块和辅助文件的日志消息

0 个答案:

没有答案