Use of Django logger, use of Django Logger

Source: Internet
Author: User

Use of Django logger, use of Django Logger

Logging Mudel

A quick logging primer

Django uses Python's builtinloggingModule to perform system logging. the usage of this module is discussed in detail in Python's own documentation. however, if you 've never used Python's logging framework (or even if you have), here's a quick primer.

The cast of players

A Python logging configuration consists of four parts:

  • Loggers
  • Handlers
  • Filters
  • Formatters

Loggers
A logger is the entry point into the logging system. each logger is a named bucket to which messages can be written for processing. A logger is configured to have a log level. this log level describes the severity of the messages that the logger will handle. python defines the following log levels: DEBUG: Low level system information for debugging purposesINFO: General system informationWARNING: Information describing a minor problem that has occurred. ERROR: Information describing a major problem that has occurred. CRITICAL: Information describing a critical problem that has occurred. each message that is written to the logger is a Log Record. each log record also has a log level indicating the severity of that specific message. A log record can also contain useful metadata that describes the event that is being logged. this can include details such as a stack trace or an error code. when a message is given to the logger, the log level of the message is compared to the log level of the logger. if the log level of the message meets or exceeds the log level of the logger itself, the message will undergo further processing. if it doesn' t, the message will be ignored. once a logger has determined that a message needs to be processed, it is passed to a Handler.

 

Handlers

The handler is the engine that determines what happens to each message in a logger. it describes a participating logging behavior, such as writing a message to the screen, to a file, or to a network socket. like loggers, handlers also have a log level. if the log level of a log record doesn't meet or exceed the level of the handler, the handler will ignore the message. A logger can have multiple handlers, and each handler can have a different log level. in this way, it is possible to provide different forms of notification depending on the importance of a message. for example, you can install one handler that forwards ERROR and CRITICALmessages to a paging service, while a second handler logs all messages (including ERROR and CRITICAL messages) to a file for later analysis.

Filters

A filter is used to provide additional control over which log records are passed from logger to handler. by default, any log message that meets log level requirements will be handled. however, by installing a filter, you can place additional criteria on the logging process. for example, you can install a filter that only allows ERROR messages from a particle source to be emitted. filters can also be used to modify the logging record prior to being emitted. for example, you can write a filter that downgrades ERROR log records to WARNING records if a particle set of criteria are met. filters can be installed on loggers or on handlers; multiple filters can be used in a chain to perform multiple filtering actions.

Formatters

Ultimately, a log record needs to be rendered as text. formatters describe the exact format of that text. A formatter usually consists of a Python formatting string containing LogRecord attributes; however, you can also write custom formatters to implement specific formatting behavior.

Source code example:

LOGGING = {    'version': 1,    'disable_existing_loggers': False,    'formatters': {        'verbose': {            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'        },        'simple': {            'format': '%(levelname)s %(message)s'        },    },    'filters': {        'special': {            '()': 'project.logging.SpecialFilter',            'foo': 'bar',        },        'require_debug_true': {            '()': 'django.utils.log.RequireDebugTrue',        },    },    'handlers': {        'console': {            'level': 'INFO',            'filters': ['require_debug_true'],            'class': 'logging.StreamHandler',            'formatter': 'simple'        },        'mail_admins': {            'level': 'ERROR',            'class': 'django.utils.log.AdminEmailHandler',            'filters': ['special']        }    },    'loggers': {        'django': {            'handlers': ['console'],            'propagate': True,        },        'django.request': {            'handlers': ['mail_admins'],            'level': 'ERROR',            'propagate': False,        },        'myproject.custom': {            'handlers': ['console', 'mail_admins'],            'level': 'INFO',            'filters': ['special']        }    }}

Resolution:

Identifies the configuration as being in ‘dictConfig version 1’ format. At present, this is the only dictConfig format version.Defines two formatters:simple, that just outputs the log level name (e.g., DEBUG) and the log message.The format string is a normal Python formatting string describing the details that are to be output on each logging line. The full list of detail that can be output can be found in Formatter Objects.verbose, that outputs the log level name, the log message, plus the time, process, thread and module that generate the log message.Defines two filters:project.logging.SpecialFilter, using the alias special. If this filter required additional arguments, they can be provided as additional keys in the filter configuration dictionary. In this case, the argument foo will be given a value of bar when instantiating SpecialFilter.django.utils.log.RequireDebugTrue, which passes on records when DEBUG is True.Defines two handlers:console, a StreamHandler, which will print any INFO (or higher) message to stderr. This handler uses the simple output format.mail_admins, an AdminEmailHandler, which will email any ERROR (or higher) message to the site admins. This handler uses the special filter.Configures three loggers:django, which passes all messages to the console handler.django.request, which passes all ERROR messages to the mail_admins handler. In addition, this logger is marked to not propagate messages. This means that log messages written to django.request will not be handled by the django logger.myproject.custom, which passes all messages at INFO or higher that also pass the special filter to two handlers – the console, and mail_admins. This means that all INFO level messages (or higher) will be printed to the console; ERROR and CRITICAL messages will also be output via email.

Usage:

Import logginglogger = logging. getLogger ("django") # enter the name logger.info ("some info...") defined in loggers ...")

Run the test:

 

LOGGING = {'version': 1, 'Disable _ existing_loggers ': False, 'formatters': {'standard': {'format': '% (asctime) s [% (threadName) s: % (thread) d] [% (name) s: % (lineno) d] [% (module) s: % (funcName) s] [% (levelname) s]-% (message) s '} # log format}, 'filters' :{}, 'handlers': {'default ': {# default 'level': 'debug', 'class': 'logging. handlers. rotatingFileHandler ', 'filename': 'Log/all. log', # log output file 'maxbytes ': 1024*1024*5, # file size 'backupcount': 5, # Number of backup copies 'formatter': 'standard ', # formatters log format}, 'error': {# error 'level': 'error', 'class': 'logging. handlers. rotatingFileHandler ', 'filename': 'Log/error. log ', 'maxbytes': 1024*1024*5, 'backupcount': 5, 'formatter ': 'standard',}, 'console': {# console 'level ': 'debug', 'class': 'logging. streamHandler ', 'formatter': 'standard'}, 'mail _ admins': {'level': 'error', 'class': 'django. utils. log. adminEmailHandler ', 'include _ html': True,}, 'request _ handler': {# request 'level': 'debug', 'class': 'logging. handlers. rotatingFileHandler ', 'filename': 'Log/script. log', 'maxbytes ': 1024*1024*5, 'backupcount': 5, 'formatter': 'standard',}, 'scprits _ handler ': {# 'level': 'debug', 'class': 'logging. handlers. rotatingFileHandler ', 'filename': 'Log/script. log ', 'maxbytes': 1024*1024*5, 'backupcount': 5, 'formatter ': 'standard', }}, 'loggers': {'django ': {'handlers': ['default', 'console'], 'level': 'debug', 'pagate': False}, 'django. request ': {'handlers': ['request _ handler'], 'level': 'debug', 'pagate': False,}, 'scripts ': {'handlers': ['scprits _ handler'], 'level': 'info', 'pagate': False}, 'blog. views ': {'handlers': ['default', 'error', 'console'], 'level': 'debug', 'pagate': True },}}

Views. py:

#-*-Coding: UTF-8-*-from django. shortcuts import renderimport logginglogger = logging. getLogger ('blog. views ') # Use the custom loggerdef index (request): try: raise exceptiontionexcept Exception as e: logger. debug ('Views. index ().... ') return render (request, 'index.html ',{})

Run

Official documentation (https://docs.djangoproject.com/en/dev/topics/logging/#topic-logging-parts-loggers)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.