Django日志器的使用

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

时间: 2024-10-15 05:21:35

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

django 开发之自定义日志器

需求 在我们的真实环境中当我们出现错误的时候我们要记录下来,便于我们分析差错. 关于日志的代码文件 1 # 自定义日志输出信息 2 LOGGING = { 3 'version': 1, 4 'disable_existing_loggers': True, 5 'formatters': { 6 'standard': { 7 'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s

18:django 日志系统

django使用python内建的logging模块去建造自己的系统日志的,如果你想详细了解这个模块的话,请自己去看python的说明文档,这里仅仅介绍django中的日志系统 日志配置包括四个部分:记录器,处理器,过滤器和格式器,下面我们来一一讲解 记录器 一个记录器是日志系统的一个实体,每一个记录器是一个已经命名好的可以将消息为进程写入的“桶”. 每一个记录器都会有一个日志等级,每个等级描述了记录器即将处理的信息的严重性,python定义了以下五个等级: debug:出于调试目的的低层次系统

django 日志logging的配置以及处理

日志在程序开发中是少不了的,通过日志我们可以分析到错误在什么地方,有什么异常.在生产环境下有很大的用途.在Java开发中通常用log4j,logback等第三方组件.那么在django中是怎么处理日志?django利用的就是Python提供的logging模块,但django中要用logging,还得有一定的配置规则,需要在setting中设置. logging模块 logging模块为应用程序提供了灵活的手段记录事件.错误.警告和调试信息.对这些信息可以进行收集.筛选.写入文件.发送给系统日志

django日志写入文件

直接运行django,日志会直接打印到屏幕上,怎么样才能保存到文件中呢 首先看到了这篇文章http://www.360doc.com/content/14/0708/10/16044571_392797799.shtml 按照正常做就可以保存到文件中了,但是保存的格式非常乱,接下来看看怎么修改日志保存的格式. 找到官网的文档 https://docs.djangoproject.com/en/dev/topics/logging/#topic-logging-parts-formatters '

log4J日志器

在应用程序中输出日志有有三个目的: (1)监视代码中变量的变化情况,把数据周期性地记录到文件中供其他应用进行统计分析工作. (2)跟踪代码运行进轨迹,作为日后审计的依据. (3)担当集成开发环境中的调试器,向文件或控制台打印代码的调试信息. log4J日志器(http://jakarta.apache.org/log4j) JDK1.4 Logging日志器(JDK1.4自带) SimpleLog日志器(把日志消息输出到标准系统错误流System.err) NoOpLog(不输出任何日志信息)

Django日志信息路径的设置

django日志信息路径的设置, 因为我们经常在代码业务上线时候 需要进行调试,查看代码的后台运行情况,就需要设置django项目的具体的日志信息运维的路径了 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'standa

Django 日志

Django使用Python内置的logging模块实现它自己的日志系统. 如果你没有使用过logging模块,请参考Python教程中的相关章节. 直达链接<logging模块详解>. 在Python的logging模块中,主要包含下面四大金刚: Loggers: 记录器 Handlers:处理器 Filters: 过滤器 Formatters: 格式化器 下文假定你已经对logging模块有一定的了解.否则,可能真的像看天书...... 一.在Django视图中使用logging 使用方法

Apache下部署Django日志时区显示不正确的问题

django 1.5的settings.py 里面默认的时区设置与1.8的默认不一样 1.8下默认TIME_ZONE = 'UTC' 如果部署到Apache上,access.log下时间如 [23/Jun/2017:04:15:05 +0000] 那么与本地时区不一致, 改成TIME_ZONE = 'Asin/Shanghai' 日志显示东八区的时间 24/Jun/2017:11:47:40 +0800

[转]django 日志logging的配置以及处理

http://davidbj.blog.51cto.com/4159484/1433741 日志在程序开发中是少不了的,通过日志我们可以分析到错误在什么地方,有什么异常.在生产环境下有很大的用途.在Java开发中通常用log4j,logback等第三方组件.那么在django中是怎么处理日志?django利用的就是Python提供的logging模块,但django中要用logging,还得有一定的配置规则,需要在setting中设置. logging模块 logging模块为应用程序提供了灵活