• 企业400电话
  • 网络优化推广
  • AI电话机器人
  • 呼叫中心
  • 全 部 栏 目

    网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Python基础之logging模块知识总结
    POST TIME:2021-10-18 13:54

    前言

    logging模块是Python内置的标准模块,主要用于输出脚本运行日志,可以设置输出日志的等级、日志保存路径等。

    一、日志级别

    级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG

    import logging  # 引入logging模块
    # 将信息打印到控制台上
    logging.debug("debug")
    logging.info("info")
    logging.warning("warning")
    logging.error("error")
    logging.critical("critical")
    
    [root@zijie ~]# python log.py
    WARNING:root:warning
    ERROR:root:error
    CRITICAL:root:critical
    

    默认生成的root logger的level是logging.WARNING,低于该级别不输出,如果要展示低于WARNING级别的内容,可以引入logging.basicConfig指定日志级别logging.basicConfig(level=logging.DEBUG)

    二、basicConfig

    格式 描述
    filename 指定使用指定的文件名而不是 StreamHandler 创建 FileHandler。
    filemode 如果指定 filename,则以此模式打开文件(‘r'、‘w'、‘a')。默认为“a”。
    format 为处理程序使用指定的格式字符串。
    datefmt 使用 time.strftime() 所接受的指定日期/时间格式。
    style 如果指定了格式,则对格式字符串使用此样式。'%' 用于 printf 样式、'{' 用于 str.format()、'$' 用于 string。默认为“%”。
    level 将根记录器级别设置为指定的级别。默认生成的 root logger 的 level 是 logging.WARNING,低于该级别的就不输出了。级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG。(如果需要显示所有级别的内容,可将 level=logging.NOTSET)
    stream 使用指定的流初始化 StreamHandler。注意,此参数与 filename 不兼容——如果两者都存在,则会抛出 ValueError。
    handlers 如果指定,这应该是已经创建的处理程序的迭代,以便添加到根日志程序中。任何没有格式化程序集的处理程序都将被分配给在此函数中创建的默认格式化程序。注意,此参数与 filename 或 stream 不兼容——如果两者都存在,则会抛出 ValueError。
    import logging
    
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(filename)s %(levelname)s %(message)s',
                        datefmt='%a %d %b %Y %H:%M:%S',
                        filename='xuehui.log',
                        filemode='w')
    
    logging.info('This is a info.')
    logging.debug('This is a debug message.')
    logging.warning('This is a warning.')
    

    三、日志写文件

    import logging
    import os.path
    import time
    
    #创建logger
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    # 创建handler,用于写入日志文件
    logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    log_path = 'logs/'
    log_name = log_path + logdate + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)
    # 定义输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    # 将logger添加到handler
    logger.addHandler(fh)
    # 日志
    logger.debug('this is a logger debug message')
    logger.info('this is a logger info message')
    logger.warning('this is a logger warning message')
    logger.error('this is a logger error message')
    logger.critical('this is a logger critical message')
    

    四、traceback记录

    import logging
    import os.path
    import time
    
    #创建logger
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    # 创建handler,用于写入日志文件
    logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    log_path = 'logs/'
    log_name = log_path + logdate + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)
    # 定义输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    # 将logger添加到handler
    logger.addHandler(fh)
    # 日志
    try:
        open('/data/exist', 'rb')
    except BaseException as e:
        logger.error('Failed to open file', exc_info=True)
    

    到此这篇关于Python基础之logging模块知识总结的文章就介绍到这了,更多相关Python logging模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    您可能感兴趣的文章:
    • Python日志模块logging简介
    • Python接口自动化浅析logging封装及实战操作
    • Python 解决logging功能使用过程中遇到的一个问题
    • Python的logging模块基本用法
    • Python logging简介详解
    上一篇:python防止栈溢出的实例讲解
    下一篇:NumPy实现ndarray多维数组操作
  • 相关文章
  • 

    关于我们 | 付款方式 | 荣誉资质 | 业务提交 | 代理合作


    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    X

    截屏,微信识别二维码

    微信号:veteran88

    (点击微信号复制,添加好友)

     打开微信