3.13 logging模块

  1. low版日志
import logging
logging.basicConfig(
    level=logging.DEBUG,
)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

应用:
    def func():
        print('in func')
        logging.debug('正常执行')
        func()

        try:
            i = input('请输入选项:')
            int(i)
            except Exception as e:
                logging.error(e)
                print(11)

                low版的日志:缺点: 文件与屏幕输入只能选择一个.
                        import logging
                        logging.basicConfig(
                            # level=logging.DEBUG,
                            level=30,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                            filename=r'test.log',
                        )
logging.debug('调试模式')  # 10
logging.info('正常模式')  # 20
logging.warning('警告信息')  # 30
logging.error('错误信息')  # 40
logging.critical('严重错误信息')  # 50
  1. 标配版日志

    import logging
    
    # 创建一个logging对象
    logger = logging.getLogger()
    
    # 创建一个文件对象
    fh = logging.FileHandler('标配版.log', encoding='utf-8')
    
    # 创建一个屏幕对象
    sh = logging.StreamHandler()
    
    # 配置显示格式
    formatter1 = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
    formatter2 = logging.Formatter('%(asctime)s %(message)s')
    fh.setFormatter(formatter1)
    sh.setFormatter(formatter2)
    
    logger.addHandler(fh)
    logger.addHandler(sh)
    
    # 总开关
    logger.setLevel(10)
    
    fh.setLevel(10)
    sh.setLevel(40)
    
    logging.debug('调试模式')  # 10
    logging.info('正常模式')  # 20
    logging.warning('警告信息')  # 30
    logging.error('错误信息')  # 40
    logging.critical('严重错误信息')  # 50
    
  2. 旗舰版日志

    """
    logging配置
    """
    
    
    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_name = 'login.log'  # log文件名
    logfile_path_staff = r'D:\s23\day19\日志模块\旗舰版日志文件夹\staff.log'
    logfile_path_boss = r'D:\s23\day19\日志模块\旗舰版日志文件夹\boss.log'
    
    # log配置字典
    # LOGGING_DIC第一层的所有的键不能改变
    
    LOGGING_DIC = {
        'version': 1,  # 版本号
        'disable_existing_loggers': False,  # 固定写法
        'formatters': {
            'standard': {
                'format': standard_format
            },
            'simple': {
                'format': simple_format
            },
            'id_simple':{
                'format': id_simple_format
            }
        },
        'filters': {},
        'handlers': {
            #打印到终端的日志
            'sh': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',  # 打印到屏幕
                'formatter': 'id_simple'
            },
            #打印到文件的日志,收集info及以上的日志
            'fh': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                'formatter': 'standard',
                'filename': logfile_path_staff,  # 日志文件
                'maxBytes': 5000,  # 日志大小 5M
                'backupCount': 5,
                'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
            },
            'boss':
                {
                    'level': 'DEBUG',
                    'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                    'formatter': 'id_simple',
                    'filename': logfile_path_boss,  # 日志文件
                    'maxBytes': 5000,  # 日志大小 5M
                    'backupCount': 5,
                    'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
                },
        },
        'loggers': {
            #logging.getLogger(__name__)拿到的logger配置
            '': {
                'handlers': ['sh', 'fh', 'boss'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
                'level': 'DEBUG',
                'propagate': True,  # 向上(更高level的logger)传递
            },
        },
    }
    
    
    def md_logger():
        logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
        logger = logging.getLogger()  # 生成一个log实例
        return logger
        # logger.debug('It works!')  # 记录该文件的运行状态
    
    dic = {
        'username': '小黑'
    }
    
    
    def login():
        # print('登陆成功')
        md_logger().info(f"{dic['username']}登陆成功")
    
    
    login()
    
posted @ 2019-07-20 18:57  God_with_us  阅读(111)  评论(0编辑  收藏  举报