zoukankan      html  css  js  c++  java
  • python写入日志文件并实时输出在控制台

    python添加log日志配置代码

    日志级别: debug --> info --> warning --> error --> critical。

    • DEBUG 详细信息,调试使用
    • INFO 正常信息
    • WARNING 警告信息
    • ERROR 错误信息
    • CRITICAL 问题很严重
    import logging
    from logging import handlers
    
    class Logger(object):
        level_relations = {
            'debug':logging.DEBUG,
            'info':logging.INFO,
            'warning':logging.WARNING,
            'error':logging.ERROR,
            'crit':logging.CRITICAL
        }     #日志关系映射
    
        def __init__(self,filename,level='info',backCount=10,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
            self.logger = logging.getLogger(filename)
            format_str = logging.Formatter(fmt)                  #设置日志格式
            self.logger.setLevel(self.level_relations.get(level))#设置日志级别
            
            sh = logging.StreamHandler()  #往屏幕上输出
            sh.setFormatter(format_str)   #设置屏幕上显示的格式
            self.logger.addHandler(sh)    #把对象加到logger里
            
            fh = handlers.RotatingFileHandler(filename=filename,maxBytes=10485760,backupCount=backCount)   # 按照文件大小分割日志文件
            fh.setLevel(self.level_relations.get(level))
            fh.setFormatter(format_str)   #设置文件里写入的格式
            self.logger.addHandler(fh)
            
    if __name__ == '__main__':
        log = Logger('my.log',level='debug')
        log.logger.debug('------0. it is a debug ------')
        log.logger.info('------ 1. it is a test ------')
        log.logger.warning('------ 2. it is a warning ------')
        log.logger.error('------ 3. it is an error ------')
        log.logger.critical('------ 4. serious problem ------')
    

    实时查看log日志

    tail -f my.log
    
  • 相关阅读:
    Linux 头文件详解
    Linux 进程运行状态
    配置uboot指定nfs挂载根文件系统
    (实例)Linux 内核添加exfat驱动
    Linux 内核 编译模块
    简单添加自己的驱动程序到Linux内核树中
    Linux 生成随机mac地址,并固化到本地
    (转)为什么ssh一关闭,程序就不再运行了?
    Ubuntu 安装 QtCreator (version : Qt 5.9.8)
    Ubuntu 固定自己的IP
  • 原文地址:https://www.cnblogs.com/lihouqi/p/14283201.html
Copyright © 2011-2022 走看看