• logging模块


    logging 日志模块

    logging模块不能自动生成程序员需要的日志

    logging模块的使用

    简单配置法

    这种方式不能输出中文,会有编码错误的问题

    且不能同时输出到文件和屏幕

    import logging
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S')
    
    logging.debug('debug message')      # 调试
    logging.info('info message')        # 普通信息
    logging.warning('warning message')  # 警告
    logging.error('error message')      # 错误信息
    logging.critical('critical message')# 严重错误

    标准配置法

    用创建一个logger对象的方法来使用logging模块

    import logging
    
    # 首先 先创建logger对象
    logger = logging.getLogger()
    
    #如果要更改级别控制,显示更低级别的内容
    logger.setLevel(logging.DEBUG)
    
    # 第二 创建一个文件操作符
    fh = logging.FileHandler('log',encoding='utf-8')
    
    # 第三 创建一个屏幕操作符
    sh = logging.StreamHandler()
    
    # 第四 创建一个格式
    fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # logger 绑定 文件操作符
    logger.addHandler(fh)
    
    # logger 绑定 屏幕操作符
    logger.addHandler(sh)
    
    # 文件操作符 绑定格式
    fh.setFormatter(fmt)
    
    # 屏幕操作符 绑定格式
    sh.setFormatter(fmt)
    
    #输出日志
    logger.debug('logger debug message')
    logger.info('logger info message')
    logger.warning('logger warning message')
    logger.error('logger error message')
    logger.critical('logger critical message')

     旗舰版(Django项目使用)

    """
    logging配置
    """
    
    import os
    import logging.config
    
    # 定义三种日志输出格式 开始
    
    standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 
                      '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字
    
    simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
    
    id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
    
    # 定义日志输出格式 结束
    
    logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录
    
    logfile_name = 'all2.log'  # log文件名
    
    # 如果不存在定义的日志目录就创建一个
    if not os.path.isdir(logfile_dir):
        os.mkdir(logfile_dir)
    
    # log文件的全路径
    logfile_path = os.path.join(logfile_dir, logfile_name)
    
    # log配置字典
    LOGGING_DIC = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': standard_format
            },
            'simple': {
                'format': simple_format
            },
        },
        'filters': {},
        'handlers': {
            #打印到终端的日志
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',  # 打印到屏幕
                'formatter': 'simple'
            },
            #打印到文件的日志,收集info及以上的日志
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                'formatter': 'standard',
                'filename': logfile_path,  # 日志文件
                'maxBytes': 1024*1024*5,  # 日志大小 5M
                'backupCount': 5,
                'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
            },
        },
        'loggers': {
            #logging.getLogger(__name__)拿到的logger配置
            '': {
                'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
                'level': 'DEBUG',
                'propagate': True,  # 向上(更高level的logger)传递
            },
        },
    }
    
    
    def load_my_logging_cfg():
        logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
        logger = logging.getLogger(__name__)  # 生成一个log实例
        logger.info('It works!')  # 记录该文件的运行状态
    
    if __name__ == '__main__':
        load_my_logging_cfg()
  • 相关阅读:
    python matplotlib 绘图
    python set add 导致问题 TypeError: unhashable type: 'list'
    python 子类继承父类的__init__方法
    python 内存监控模块之memory_profiler
    git log 常用命令
    wireshark使用教程
    python os.path模块
    Linux crontab 定时任务
    linux环境变量LD_LIBRARY_PATH
    Linux的ldconfig和ldd用法
  • 原文地址:https://www.cnblogs.com/biulo/p/10665990.html
Copyright © 2020-2023  润新知