Python日志记录将所有级别的日志写入文件

时间:2019-09-08 14:47:36

标签: python logging

import logging

def set_logging():
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(message)s',
        level=logging.INFO,
        datefmt='%m/%d/%Y %I:%M:%S %p'
        )
    logger = logging.getLogger('simple_example')
    fl = logging.FileHandler("myapp.log")
    fl.setLevel(logging.INFO)
    logger.addHandler(fl)
    return logger

if __name__ == "__main__":
    logger = set_logging()
    logger.info('infoooo')
    logger.error('erorrrr')

Output:
/home/admin# python logging.py
09/08/2019 02:40:36 PM INFO infoooo
09/08/2019 02:40:36 PM ERROR erorrrr
/home/admin# cat myapp.log
infoooo
erorrrr

如果我在上面的代码中注释了logging.basicConfig()行,则在控制台中看不到输出,并且仅将“ erorrrr”消息写入文件。我可以在上述代码中进行哪些更改,以将所有级别的日志写入文件,而无需向控制台写入任何内容?

2 个答案:

答案 0 :(得分:1)

如果您仅在logger.propagate = False函数中添加set_logging,则此行。它将所有级别的日志写入文件,并且不会在控制台上显示。

def set_logging():
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(message)s',
        level=logging.INFO,
        datefmt='%m/%d/%Y %I:%M:%S %p'
        )
    logger = logging.getLogger('simple_example')
    fl = logging.FileHandler("myapp.log")
    fl.setLevel(logging.INFO)
    logger.addHandler(fl)
    logger.propagate = False  # added this line to disable console logs.
    return logger

答案 1 :(得分:1)

您可以使用logger.propagate = False禁用控制台日志记录。

import logging

def set_logging():
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(message)s',
        level=logging.INFO,
        datefmt='%m/%d/%Y %I:%M:%S %p'
        )
    logger = logging.getLogger('simple_example')
    logger.propagate = False
    fl = logging.FileHandler("myapp.log")
    fl.setLevel(logging.INFO)
    logger.addHandler(fl)
    return logger

if __name__ == "__main__":
    logger = set_logging()
    logger.info('infoooo')
    logger.error('erorrrr')