Logging Mudel

A quick logging primer

Django uses Python’s builtin logging module 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
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 purposes
INFO: General system information
WARNING: 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 particular 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 could 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 could install a filter that only allows ERROR messages from a particular source to be emitted.
Filters can also be used to modify the logging record prior to being emitted. For example, you could write a filter that downgrades ERROR log records to WARNING records if a particular 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.

源码示例:

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']
}
}
}

解析:

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.

使用方式:

import logging
logger = logging.getLogger("django") # 为loggers中定义的名称
logger.info("some info...")

运行测试:

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'}
# 日志格式
},
'filters': {
},
'handlers': {
'default': { # 默认
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'log/all.log', # 日志输出文件
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份份数
'formatter': 'standard', # 使用哪种formatters日志格式
},
'error': { # 错误
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'log/error.log',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'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': { # script请求
'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',
'propagate': False
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False,
},
'scripts': {
'handlers': ['scprits_handler'],
'level': 'INFO',
'propagate': False
},
'blog.views': {
'handlers': ['default', 'error','console'],
'level': 'DEBUG',
'propagate': True
},
}
}

views.py:

# -*- coding: utf-8 -*-
from django.shortcuts import render
import logging logger = logging.getLogger('blog.views') # 使用自定义的logger def index(request):
try:
raise Exception
except Exception as e:
logger.debug('views.index()....')
return render(request, 'index.html', {})

运行

官方文档(https://docs.djangoproject.com/en/dev/topics/logging/#topic-logging-parts-loggers

Django日志器的使用的更多相关文章

  1. django 开发之自定义日志器(二)

    2016-08-24 需求 在我们的真实环境中当我们出现错误的时候我们要记录下来,便于我们分析差错. 关于日志的代码文件 # 自定义日志输出信息 LOGGING = { 'version': 1, ' ...

  2. django日志,django-crontab,django邮件模块

    django 日志 四大块,格式器,过滤器,处理器,日志管理器 LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatt ...

  3. Django日志系统

    在Django中使用的日志系统是基于Python中的loggin模块. 首先简单介绍下logging. 一 Loggin模块简介 loggin模块主要包含以下四个部分: Loggers        ...

  4. 18:django 日志系统

    django使用python内建的logging模块去建造自己的系统日志的,如果你想详细了解这个模块的话,请自己去看python的说明文档,这里仅仅介绍django中的日志系统 日志配置包括四个部分: ...

  5. django日志的设置

    关于django的日志设置详细可以看下官方文档:https://yiyibooks.cn/xx/Django_1.11.6/topics/logging.html 示例: # 日志文件配置 LOGGI ...

  6. 07.django日志配置

    https://docs.djangoproject.com/en/3.0/topics/logging/ https://yiyibooks.cn/xx/python_352/library/log ...

  7. Django(37)配置django日志

    前言   django框架的日志通过python内置的logging模块实现的,既可以记录自定义的一些信息描述,也可以记录系统运行中的一些对象数据,还可以记录包括堆栈跟踪.错误代码之类的详细信息.   ...

  8. Django 日志配置

    Django日志处理 settings配置 ########### # LOGGING # ########### BASE_LOG_DIR = os.path.join(os.path.dirnam ...

  9. django 日志logging的配置以及处理

    django日志官方文档https://docs.djangoproject.com/en/1.11/topics/logging/ 本文摘自http://davidbj.blog.51cto.com ...

随机推荐

  1. SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇

    Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全 ...

  2. 洛谷——P1823 音乐会的等待

    https://www.luogu.org/problem/show?pid=1823 题目描述 N个人正在排队进入一个音乐会.人们等得很无聊,于是他们开始转来转去,想在队伍里寻找自己的熟人.队列中任 ...

  3. Redis-消费模式

    一 . 两种模式简介 发布消息通常有两种模式:队列模式(queuing)和发布订阅模式(qublish-subscribe).队列模式中,consumers可以同时从服务端读取消息,每个消息纸杯其中一 ...

  4. 使用solr的DIHandler 构建mysql大表全量索引,内存溢出问题的解决方法

    solr官方给出的解决方式是: DataImportHandler is designed to stream row one-by-one. It passes a fetch size value ...

  5. invalid syntax 无效语法

    python用的是spyder编译器, 再出现上一行少了个括号的时候. 在下一行显示有错误.

  6. jedate-开始使用一款好用的时间插件

    jeDate日期控件 -(原生JS版)jeDate V6.5.0 是一款原生JS开发的 不依赖任何第三方库 大众化的日期控件,包含 多语言.设定年月(YYYY-MM).日期范围限制.开始日期设定.自定 ...

  7. windows下配置mycat与常见问题解决

    mycat官网:http://www.mycat.org.cn/ wiki:https://github.com/MyCATApache/Mycat-Server/wiki MyCat使用Mysql的 ...

  8. Python 极简教程(二)编码工具

    Python 的编码工具很多.目前最流行的是 pycharm,关于 pycharm 的安装使用请参考 PyCharm安装使用教程. 而学习过程中,我觉得最好用的,还是 Python 自带的练习工具 I ...

  9. Day2:数据类型

    一.数字 1.整型(int),无长整型.python3.x,不论多大的数都是int #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuh ...

  10. C++ tab键实现自动补全输入功能

    一.简介 由于项目中写了个测试的控制台程序,是每次读取一行,即通过getline()来实现的,所以每次必须输入全路径名称,才能实现运行. 大家都觉得麻烦,就写了个tab键自动选择补全的. 目前基本可实 ...