django中日志使用学习记录

在setting中加入以下代码

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'standard': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter':'standard',
        },
        'my_handler': {
            'level': 'WRANING',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/logging/my_handler.log',
            'formatter': 'standard',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'my_logger': {
            'handlers': ['my_handler'],
            'level': 'WARNNING',
            'propagate': False,
        },
    },
}

简化版

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
    },
    'filters': {
    },
    'handlers': {
        'default': {
            'level': 'WRANING',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'os.path.join(BASE_DIR+'/static/logs/','all.log')',
            'formatter': 'standard',
        },
    },
    'loggers': {
        'default': {
            'handlers': ['default'],
            'level': 'WARNNING',
            'propagate': False,
        },
    },
}

使用import logging

logger = logging.getLogger('default')

logger.warnning('test')

version表示版本,一般不用改

disable_existing_loggers表示弃用已经存在的日志,True表示弃用,False表示不弃用。

fomatters表示多个格式化格式,verbose表示详细的格式化,包括文件名,时间,模块,进程,线程,信息,standard表示标准的格式化包括文件名,时间和信息,simple就是简单的只有文件名和信息

filters表示过滤器,如果有需要可以添加,如何添加查看官方文档,一般不需要。

handlers表示处理日志程序定义了两个一个是把日志发送给站点管理员,一个是自定义的。level表示等级,一共五个

DEBUG:用于调试目的的底层系统信息

INFO:普通的系统信息

WARNING:表示出现一个较小的问题。

ERROR:表示出现一个较大的问题。

CRITICAL:表示出现一个致命的问题。

class表示的意思大概是python自带的处理程序吧,filename表示文件位置,formater表示使用哪种格式

以下来自官方文档,翻译的不是很准确,rotate不明白啥意思

In addition to the base Handler class, many useful subclasses are provided:出了基础的handler类,还提供了许多有用的子类

  1. StreamHandler instances send messages to streams (file-like objects).实例对象,发送信息给流对象类似文件的对象
  2. FileHandler instances send messages to disk files.实例对象,发送信息给硬盘文件
  3. BaseRotatingHandler is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.基础的类,回溯日志文件到某个特定的点,一般不直接使用,而是使用其他两个类代替
  4. RotatingFileHandler instances send messages to disk files, with support for maximum log file sizes and log file rotation.实例对象,发送信息给硬盘文件,支持最大日志文件大小和日志文件回溯
  5. TimedRotatingFileHandler instances send messages to disk files, rotating the log file at certain timed intervals.实例对象,发送信息给硬盘文件,隔一段时间回溯到日志文件某个点
  6. SocketHandler instances send messages to TCP/IP sockets.实例对象,发送信息给TCP/IP套接字
  7. DatagramHandler instances send messages to UDP sockets.实例对象,发送信息给UDP套接字
  8. SMTPHandler instances send messages to a designated email address.实例对象,发送给特定的email地址
  9. SysLogHandler instances send messages to a Unix syslog daemon, possibly on a remote machine.实例对象,发送日志给unix中syslog守护进程,发送到远程unix机器上使用
  10. NTEventLogHandler instances send messages to a Windows NT/2000/XP event log.实例对象,发送信息给window event日志
  11. MemoryHandler instances send messages to a buffer in memory, which is flushed whenever specific criteria are met.实例对象,发送信息给内存的缓冲,满足特定条件将刷新
  12. HTTPHandler instances send messages to an HTTP server using either GET or POST semantics.实例对象,发送信息给使用post或get的http服务
  13. WatchedFileHandler instances watch the file they are logging to. If the file changes, it is closed and reopened using the file name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used.实例对象,查看登录文件。如果文件更改,则使用文件名关闭并重新打开。此处理程序仅适用于类Unix系统; Windows不支持使用的底层机制
  14. NullHandler instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the ‘No handlers could be found for logger XXX’ message which can be displayed if the library user has not configured logging. See Configuring Logging for a Library for more information实例对象,不对错误信息做处理。想要使用日志记录的图书馆开发人员,但是希望避免如果库用户没有配置日志记录,则可以显示“无记录器XXX的处理程序”消息。的时候使用

New in version 2.7: The NullHandler class.

The NullHandlerStreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers. (There is also another sub-module, logging.config, for configuration functionality.)

Logged messages are formatted for presentation through instances of the Formatter class. They are initialized with a format string suitable for use with the % operator and a dictionary.

For formatting multiple messages in a batch, instances of BufferingFormatter can be used. In addition to the format string (which is applied to each message in the batch), there is provision for header and trailer format strings.

When filtering based on logger level and/or handler level is not enough, instances of Filter can be added to both Logger and Handler instances (through their addFilter() method). Before deciding to process a message further, both loggers and handlers consult all their filters for permission. If any filter returns a false value, the message is not processed further.

The basic Filter functionality allows filtering by specific logger name. If this feature is used, messages sent to the named logger and its children are allowed through the filter, and all others dropped.

loggers是日志记录器,用来记录日志,handler表示使用哪个的处理日志程序,level表示等级同上,propergate表示是否向上传递错误信息

默认情况下,Django 的logging 配置如下:

DEBUG 为True 时:

django的全局logger会向控制台发送级别等于或高于INFO的所有消息。Django 此时不会做任何日志调用(所有的日志要么为DEBUG级别,要么被django.request 和django.security logger 处理)。

py.warnings logger,它处理来自warnings.warn()的消息,会向控制台发送消息。

DEBUG 为False 时:

django.request 和django.security loggers 向AdminEmailHandler发送带有ERROR 或 CRITICAL级别的消息。这些logger 会忽略任何级别等于或小于WARNING的信息,被记录的日志不会传递给其他logger(它们不会传递给django的全局 logger,即使DEBUG 为 True)。

另见配置日志来了解如何补充或者替换默认的日志配置。

原文地址:https://www.cnblogs.com/lgh344902118/p/6893991.html