Python使用日志记录来写日志,重复输出文件的日志

时间:2018-04-20 04:48:48

标签: python-3.x logging

我使用日志记录来写日志。但有时会重复日志文件的内容。 喜欢这个:

2018-04-20 13:41:19,164 INFO line:20 test
2018-04-20 13:41:19,164 INFO line:20 test
2018-04-20 13:41:19,164 INFO line:20 test
2018-04-20 13:41:19,164 INFO line:20 test

我的代码:

import logging
import os
import datetime

def write_log():
    logger = logging.getLogger()
    now_date = datetime.datetime.now().strftime('%Y%m%d')
    log_file = now_date + ".log" 
    if not os.path.exists("log"):
        os.makedirs("log")
    formatter = logging.Formatter('%(asctime)s %(levelname)s line:%(lineno)s %(message)s')
    file_handler = logging.FileHandler("log" + os.sep + log_file, mode='a', encoding='utf-8')
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    logger.setLevel(logging.INFO)
    return logger

mylog = write_log()
mylog.info("test")

如何删除重复的日志?

1 个答案:

答案 0 :(得分:1)

作为stated here,您可以为记录器使用特定名称。这样,您就可以避免重复创建,如果它已经存在则进行测试...

# Set up a specific logger with our desired output level
my_logger = logging.getLogger(name)
if not my_logger.handlers:
     # Here I created handler, formatter, loglevel etc..
return my_logger