python logging模块

import logging

# 在文件和窗口二选一个位置打印信息,有filename的话在写入文件
logging.basicConfig(
    level=logging.DEBUG,  # 设置错误级别
    filename='logging.txt',  # 日志文件名
    filemode='w',  # 文件打开模式
    format='%(asctime)s %(filename)s [%(lineno)d] %(message)s'
)

logging.debug("this is a debug")
logging.info('this is info')
logging.warning('this is warning')
logging.error('this is error')
logging.critical('this is critical')


# -------------------------------------------------
# 文件和窗口同时打印错误信息
def logger():
    logger_obj = logging.getLogger()
    fh = logging.FileHandler('logging_text')
    ch = logging.StreamHandler()

    fm = logging.Formatter('%(asctime)s %(filename)s [%(lineno)d] %(message)s')

    fh.setFormatter(fm)
    ch.setFormatter(fm)

    logger_obj.addHandler(fh)
    logger_obj.addHandler(ch)

    logger_obj.setLevel('DEBUG')
    return logger_obj


logger = logger()
logging.debug("this is a debug")
logging.info('this is info')
logging.warning('this is warning')
logging.error('this is error')
logging.critical('this is critical')

 

posted @ 2019-09-06 12:43  The_small_white  阅读(139)  评论(0编辑  收藏  举报