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)。

另見配置日志來了解如何補充或者替換默認的日志配置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM