python使用logging实现日志前台和文件输出

python使用logging实现日志前台和文件输出,第1张

python使用logging实现日志前台和文件输出

同时输出到前台和文件(滚动覆盖)

import os
import logging
import time
from logging.handlers import RotatingFileHandler


def login(mm):
    log = logging.getLogger()
    log.setLevel(logging.NOTSET)
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    log_path = os.path.dirname(os.getcwd()) + '/Logs/'
    log_name = log_path + 'log.log'
    logfile = log_name
    # fsc = logging.FileHandler(logfile, mode='w') # 不循环回滚日志
    fsc = RotatingFileHandler(logfile, maxBytes=1, backupCount=2)  # 循环回滚日志,最大1kb,最多保留2个备份
    fsc.setLevel(logging.NOTSET)

    ch = logging.StreamHandler()  # 创建输出到前台的handler
    ch.setLevel(logging.NOTSET)  # 定义日志显示级别为无级别

    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s:%(message)s")
    fsc.setFormatter(formatter)
    ch.setFormatter(formatter)

    log.addHandler(fsc)
    log.addHandler(ch)

    log.debug(mm)
    # log.info('this is a logger info message')
    # log.warning('this is a logger warning message')
    # log.error('this is a logger error message')
    # log.critical('this is a logger critical message')

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5437214.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存