美文网首页
logging 模块使用

logging 模块使用

作者: 虚心的锄头 | 来源:发表于2018-12-14 18:18 被阅读0次

    简单使用

    import logging
    logging.basicConfig(
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s',
        level=logging.DEBUG
        
        # datefmt='%Y-%m-%d %H:%M:%S',    # 时间格式
        # handlers=[logging.FileHandler(logpath, encoding='utf-8')]  # 指定文件编码
        # handlers=[logging.handlers.TimedRotatingFileHandler(logpath, when='M',  backupCount=5, encoding='utf-8')]  # 按分钟分割日志, 保留5分历史
    
        )
    logging.info('info message')
    
    

    日志分割

    按天分割, 保留5份历史日志

    import logging
    import logging.handlers
    
    SCRIPTNAME = os.path.basename(__file__).split('.')[0]
    LOGDIR = "/var/log"
    if not os.path.isdir(LOGDIR):
        os.makedirs(LOGDIR)
    LOG_FILE = os.path.join(LOGDIR, SCRIPTNAME)
    logger = logging.getLogger(SCRIPTNAME)
    logger.setLevel(logging.INFO)
    timefilehandler = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='D', backupCount=5, encoding='utf-8')
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s')
    timefilehandler.setFormatter(formatter)
    logger.addHandler(timefilehandler)
    
    logger.info("This is the log")
    
    日志等级(level)

    logging.warn('error message') 弃用

    logging.debug('debug message')
    logging.info('info message')
    logging.warning('warn message')
    logging.error('error message')
    logging.critical('critical message')
    
    # 特殊的用法
    logging.log(level, 'log message')  
    # level ==logging.DEBUG, logging.INFO, ... 
    
    
    basicConfig 的参数
    filename:即日志输出的文件名,如果指定了这个信息之后,实际上会启用 FileHandler,而不再是 StreamHandler,这样日志信息便会输出到文件中了。
    filemode:这个是指定日志文件的写入方式,有两种形式,一种是 w,一种是 a(默认),分别代表清除后写入和追加写入。
    format:指定日志信息的输出格式,即上文示例所示的参数,部分参数如下所示:
        %(name)s                Logger的名字
        %(levelno)s             数字形式的日志级别
        %(levelname)s           文本形式的日志级别
        %(pathname)s            调用日志输出函数的模块的完整路径名,可能没有
        %(filename)s            调用日志输出函数的模块的文件名
        %(module)s              调用日志输出函数的模块名
        %(funcName)s            调用日志输出函数的函数名
        %(lineno)d              调用日志输出函数的语句所在的代码行
        %(created)f             当前时间,用UNIX标准的表示时间的浮 点数表示
        %(relativeCreated)d     输出日志信息时的,自Logger创建以 来的毫秒数
        %(asctime)s             字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
        %(thread)d              线程ID。可能没有
        %(threadName)s          线程名。可能没有
        %(process)d             进程ID。可能没有
        %(message)s             用户输出的消息
    
    datefmt:指定时间的输出格式。
    style:如果 format 参数指定了,这个参数就可以指定格式化时的占位符风格,如 %、{、$ 等。
    level:指定日志输出的类别,程序会输出大于等于此级别的信息。
    stream:在没有指定 filename 的时候会默认使用 StreamHandler,这时 stream 可以指定初始化的文件流。
    handlers:可以指定日志处理时所使用的 Handlers,必须是可迭代的。
    
    错误输出案例
    try:
        result = 5 / 0
    except Exception as e:
        # bad
        logging.error('Error: %s', e)
        # good
        logging.error('Error', exc_info=True)  # 使用这个方式
        # good
        logging.exception('Error')  # 或者 使用这个方式
    
    日志分割 其他
    import logging
    from logging.handlers import RotatingFileHandler  # 按大小分割
    from logging.handlers import TimedRotatingFileHandler  # 按时间分割
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    # 文件大小
    #Rthandler = RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5, encoding='utf-8')  # encoding='utf-8' ,不指定中文乱码
    
    # 时间分割
    # pyhton2  encoding='utf-8' 报错, 不能加
    Rthandler = TimedRotatingFileHandler('message.log', when='D',backupCount=5, encoding='utf-8')  # python3 encoding='utf-8' ,不指定中文乱码
    
    # Rthandler.suffix = '%Y-%m-%d_%H-%M'  # 日志分割格式  # message.log.2018-10-12_14-44
    
    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
    Rthandler.setFormatter(formatter)
    logger.addHandler(Rthandler)
    
    

    按大小分割

    官网 https://docs.python.org/3.6/library/logging.handlers.html#rotatingfilehandler
    logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
    
    filename  日志文件名
    mode  写入方式
    maxBytes  指定大小, 超过这个大小后自动分割
    backupCount  分割文件备份数  格式 log.log.1, log.log.2,.....
    encoding  日志文件编码
    delay   If *delay* is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely.
    
    

    按时间分割

    官网 https://docs.python.org/3.6/library/logging.handlers.html#timedrotatingfilehandler
    logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)
    
    filename      日志文件名
    when  日志分割时间请查看下列表格
    
    
    
    when 时间分割指定表
    Value Type of interval If/how atTime is used
    'S' Seconds Ignored
    'M' Minutes Ignored
    'H' Hours Ignored
    'D' Days Ignored
    'W0'-'W6' Weekday (0=Monday) Used to compute initial rollover time
    'midnight' Roll over at midnight, if atTime not specified, else at time atTime Used to compute initial rollover time

    相关文章

      网友评论

          本文标题:logging 模块使用

          本文链接:https://www.haomeiwen.com/subject/vxtnhqtx.html