python - python 日志模块的日志记录问题

标签 python logging

我正在使用 python 日志记录模块。我正在初始化具有以下数据的文件

def initialize_logger(output_dir):
    '''
    This initialise the logger
    :param output_dir:
    :return:
    '''
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    format = '%(asctime)s - %(levelname)-8s - %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'
    if 'colorlog' in sys.modules and os.isatty(2):
        cformat = '%(log_color)s' + format
        f = colorlog.ColoredFormatter(cformat, date_format,
                                      log_colors={'DEBUG': 'green', 'INFO': 'green',
                                                  'WARNING': 'bold_yellow', 'ERROR': 'bold_red',
                                                  'CRITICAL': 'bold_red'})
    else:
        f = logging.Formatter(format, date_format)
    #ch = logging.FileHandler(output_dir, "w")
    ch = logging.StreamHandler()
    ch.setFormatter(f)
    root.addHandler(ch)

由于只有一个streamHandler,但我在控制台上得到了两个打印

INFO:root:clearmessage:%ss1=00

2017-12-21 17:07:20 - INFO     - clearmessage:%ss1=00

INFO:root:clearmessage:%ss2=00

2017-12-21 17:07:20 - INFO     - clearmessage:%ss2=00

每条消息都打印为RootInfo。知道为什么我会得到两张照片吗?在上面的代码中您可以忽略颜色代码。

最佳答案

您有两个处理程序。在添加新处理程序之前清除处理程序:

root.handlers = [] # clears the list
root.addHandler(ch) # adds a new handler

关于python - python 日志模块的日志记录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924256/

相关文章:

java - 如何避免在 log4j v.1 中将消息写入根记录器

使用自定义注释的 Spring Logging

python - 计算具有偶数列和奇数列的 Pandas 的平均值

python - Django 中的 SQL 查询产生不同的结果

python - 我正在尝试调试给定的 python 代码,但它给出了给定的错误

python - 读取 .xlsx 并访问单元格值,但不按其位置

c# - 如何找到执行函数的对象类型和名称?

java - Cassandra 控制台日志消息

testing - 对于快速测试、可移植 Linux 还是可移植编程语​​言?

python - SAS date9 格式到 python 日期时间