zoukankan      html  css  js  c++  java
  • python logging模块

    Logging模块简介

    Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。

    logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。

    handler:将日志记录发送到合适的目的地,比如文件,标准输出等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。

    filter:提供一种优雅的方式决定一个日志记录是否发送到handler。

    formatter指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。

      

    Logging用法解析

    1. 初始化 logger = logging.getLogger("endlesscode"),getLogger()方法后面最好加上所要日志记录的模块名字,后面的日志格式中的%(name)s 对应的是这里的模块名字

    2. 设置日志级别 logger.setLevel(logging.DEBUG),Logging中有NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL这几种级别,日志会记录设置级别以上的日志

    3. 设置日志目标 Handler,常用的是StreamHandler和FileHandler,一个打印在当前窗口上,一个记录在一个文件里。

    4. 设置日志格式 formatter,定义了最终log信息的顺序,结构和内容,我喜欢用这样的格式 "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"

    %(name)s Logger的名字
    %(levelname)s 文本形式的日志级别
    %(message)s 用户输出的消息
    %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
    %(levelno)s 数字形式的日志级别
    %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
    %(filename)s 调用日志输出函数的模块的文件名
    %(module)s  调用日志输出函数的模块名
    %(funcName)s 调用日志输出函数的函数名
    %(lineno)d 调用日志输出函数的语句所在的代码行
    %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
    %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
    %(thread)d 线程ID。可能没有
    %(threadName)s 线程名。可能没有
    %(process)d 进程ID。可能没有

    示例

    例1:下面来写一个实例,在屏幕上只打出error以上级别的日志,但是在日志文件中写入debug以上的信息

    import logging
    
    logger = logging.getLogger("simple_example")
    logger.setLevel(logging.DEBUG)
    
    fh = logging.FileHandler("spam.log")   # 将日志发送到文件
    fh.setLevel(logging.DEBUG) # 日志级别
    
    ch = logging.StreamHandler() # 将日志发送到屏幕
    ch.setLevel(logging.ERROR) # 日志级别
    
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # 定义日志格式
    ch.setFormatter(formatter) # 将日志格式传给ch
    fh.setFormatter(formatter) # 将日志格式传给fh
    
    logger.addHandler(ch) 
    logger.addHandler(fh)
    
    logger.debug("debug message")
    logger.info("info message")
    
    logger.warn("warn message")
    logger.error("error message")

    例2:Django项目中使用logging日志

    1. 在Setting.py中添加以下内容

    # 日志配置
    cur_path = os.path.dirname(os.path.realpath(__file__))  # log_path是存放日志的路径
    log_path = os.path.join(os.path.dirname(cur_path), 'logs')
    if not os.path.exists(log_path):
        os.mkdir(log_path)  # 如果不存在这个logs文件夹,就自动创建一个
    
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            # 日志格式
            'standard': {
                'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
                          '[%(levelname)s]- %(message)s'},
            'simple': {  # 简单格式
                'format': '%(levelname)s %(message)s'
            },
        },
        # 过滤
        'filters': {
        },
        # 定义具体处理日志的方式
        'handlers': {
            # 默认记录所有日志
            'default': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(log_path, 'all-{}.log'.format(time.strftime('%Y-%m-%d'))),
                'maxBytes': 1024 * 1024 * 5,  # 文件大小
                'backupCount': 5,  # 备份数
                'formatter': 'standard',  # 输出格式
                'encoding': 'utf-8',  # 设置默认编码,否则打印出来汉字乱码
            },
            # 输出错误日志
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(log_path, 'error-{}.log'.format(time.strftime('%Y-%m-%d'))),
                'maxBytes': 1024 * 1024 * 5,  # 文件大小
                'backupCount': 5,  # 备份数
                'formatter': 'standard',  # 输出格式
                'encoding': 'utf-8',  # 设置默认编码
            },
            # 控制台输出
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'standard'
            },
            # 输出info日志
            'info': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(log_path, 'info-{}.log'.format(time.strftime('%Y-%m-%d'))),
                'maxBytes': 1024 * 1024 * 5,
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',  # 设置默认编码
            },
        },
        # 配置用哪几种 handlers 来处理日志
        'loggers': {
            # 类型 为 django 处理所有类型的日志, 默认调用
            'django': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False
            },
            # log 调用时需要当作参数传入
            'log': {
                'handlers': ['error', 'info', 'console', 'default'],
                'level': 'INFO',
                'propagate': True
            },
        }
    }

    2. 在View中调用

    import logging
    
    logger = logging.getLogger('log')
    
    def log(request):
        logger.debug("log debug test")
        logger.info("log info test")
        logger.error("log error test")
        return HttpResponse(status=200)

    3.实际效果

  • 相关阅读:
    SDWebImage
    ios面试题
    IOS推送功能push
    NSString什么时候用copy,什么时候用strong
    OC点语法和变量作用域
    iOS 常用几种数据存储方式
    JSON与XML的区别比较
    IOS开发——网络编程OC篇&Socket编程
    IOS-UI控件大全
    使用sql语句备份一张表
  • 原文地址:https://www.cnblogs.com/vincenshen/p/6179741.html
Copyright © 2011-2022 走看看