zoukankan      html  css  js  c++  java
  • 常用模块logging

    常用模块logging

    什么时候用到logging模块

    1.用来记录用户的行为 - 数据分析
    2.用来记录用户的行为 - 操作审计
    3.排查代码中的错误

    输出内容是有等级的 : 默认处理warning级别以上的所有信息
    logging.debug('debug message')          # 调试
    logging.info('info message')            # 信息
    logging.warning('warning message')      # 警告
    logging.error('error message')          # 错误
    logging.critical('critical message')    # 批判性的
    

    默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

    import logging
    
    file_handler = logging.FileHandler(filename='x1.log', mode='a', encoding='utf-8',)
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        handlers=[file_handler,],
        level=logging.ERROR
    )
    
    logging.error('你好')
    
    # 同时向文件和屏幕上输出
    fh = logging.FileHandler('tmp.log',encoding='utf-8') #向文件输出
    # fh2 = logging.FileHandler('tmp2.log',encoding='utf-8')
    sh = logging.StreamHandler()  #向屏幕输出
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s[line :%(lineno)d]-%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        level= logging.DEBUG,
        # handlers=[fh,sh,fh2]
        handlers=[fh,sh]
    )
    logging.debug('debug 信息错误 test2')
    logging.info('warning 信息错误 test2')
    logging.warning('warning message test2')
    logging.error('error message test2')
    logging.critical('critical message test2')
    

    做日志的切分

    import time
    from logging import handlers
    sh = logging.StreamHandler()
    rh = handlers.RotatingFileHandler('myapp.log', maxBytes=1024,backupCount=5)   # 按照大小做切割
    fh = handlers.TimedRotatingFileHandler(filename='x2.log', when='s', interval=5, encoding='utf-8')
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s[line :%(lineno)d]-%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        level= logging.DEBUG,
        # handlers=[fh,sh,fh2]
        handlers=[fh,rh,sh]
    )
    for i in range(1,100000):
        time.sleep(1)
        logging.error('KeyboardInterrupt error %s'%str(i))
    
  • 相关阅读:
    PHP查看IP时候能ping通
    mysql把查询到不一样的记录插入到另一张表中
    js本地预览图片
    redis 扩展下载
    mysql update select子查询
    mysql view视图的简单使用....
    两表联查关联字段我想查多个怎么办???
    两表联查是关联字段的值位数不一样时怎么办???
    使用PHP生成二维码(PHPQRCode)
    .net初学之SerialPort串口类
  • 原文地址:https://www.cnblogs.com/wyh0717/p/13124156.html
Copyright © 2011-2022 走看看