zoukankan      html  css  js  c++  java
  • Django中Logging日志配置

    Django日志配置

    1. django中的log需要在settings.py中配置

      import time
           
      LOGGING_DIR = os.path.join(BASE_DIR, "logs")    # LOGGING_DIR 日志文件存放目录
      if not os.path.exists(LOGGING_DIR):
          os.mkdir(LOGGING_DIR)
      
      LOGGING = {
          'version': 1,
          'disable_existing_loggers': True,   # 禁用已存在的log,详情见下面
          '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(LOGGING_DIR, '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(LOGGING_DIR, '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(LOGGING_DIR, '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. 脚本中调用:

      import logging
       
      logger = logging.getLogger('log')
      ...
      logger.info('请求成功! response_code:{};response_headers:{};response_body:{}'.format(response_code, response_headers, response_body[:251]))
       
      logger.error('请求出错:{}'.format(error))
      

    禁用日志配置

    LOGGING_CONFIG=None,禁用。
    

    Django自带的记录器

    django记录器是捕捉所有消息的记录器,没有消息是直接发往django记录器的,而是使用下面的记录器:
    
    - django.request记录器
    
        5XX会引发一个error消息,4XX会引发一个warning消息,这个记录器还附带有额外的上下文:
    
        status_code:HTTP响应吗
        request:生成这个消息的request对象
    
    - django.db.backends记录器
    
        所有的由请求运行的sql语句都会记录一条debug的消息,每个记录器还附带有额外的上下文:
    
        duration:sql语句运行的时间
        sql:运行的sql语句
        params:sql语句调用的参数
    
        处于网站运行的表现原因,仅当settings.DEBUG=True的时候,这个处理器才生效,否则即使配置了也无效。
    

    Django自带的过滤器

    • class CallBackFilter(callback)

      这个过滤器接受一个回调函数(这个函数接受一个参数,被记录的信息),每个记录通过过滤器的时候都会调用这个回调函数,当回调函数返回False的时候,不处理这个记录。下面是一个示例:

      from django.http import UnreadablePostError
      
      def skip_unreadable_post(record):
          if record.exc_info:
              exc_type, exc_value = record.exc_info[:2]
              if isinstance(exc_value, UnreadablePostError):
                  return False
          return True
      
      'filters': {
          'skip_unreadable_posts': {
              '()': 'django.utils.log.CallbackFilter',
              'callback': skip_unreadable_post,
          }
      },
      'handlers': {
          'mail_admins': {
              'level': 'ERROR',
              'filters': ['skip_unreadable_posts'],
              'class': 'django.utils.log.AdminEmailHandler'
          }
      },
      
    • class RequireDebugFalse

      此过滤器仅在settings.DEBUG为False时传递记录。

    • class RequireDebugTrue

      此过滤器仅当settings.DEBUG为True时传递记录。

  • 相关阅读:
    C++开源库
    Boost ASIO proactor 浅析
    ehcache
    http://www.servicestack.net/
    hortonworks
    (总结)Nginx 502 Bad Gateway错误触发条件与解决方法
    VMware vSphere虚拟化学习手册下部
    精确字符串匹配(BM算法) [转]
    Linux下基本TCP socket编程之服务器端
    How To Use Linux epoll with Python
  • 原文地址:https://www.cnblogs.com/JeromeLong/p/13196020.html
Copyright © 2011-2022 走看看