Django+Logging: Logging Configuration and Usage
Introduction Logging is indispensable in program development. Through logs, we can analyze where errors occur and what exceptions there are. It is very useful in production environments. In Java development, third-party components such as log4j and logback are commonly used. So how is logging handled in Django? Django uses the logging module provided by Python, but to use logging in Django, there are certain configuration rules that need to be set in settings. Logging Module The Logging module provides applications with
目录8 个章节
Introduction
Logging is indispensable in program development. Through logs, we can analyze where errors occur and what exceptions there are. It is very useful in production environments. In Java development, third-party components such as log4j and logback are commonly used. So how is logging handled in Django? Django uses the logging module provided by Python, but to use logging in Django, there are certain configuration rules that need to be set in settings.
Logging Module
The logging module provides applications with a flexible means of recording events, errors, warnings, and debug information. This information can be collected, filtered, written to files, sent to the system log, and even sent over the network to a remote computer.
First, Here Is My Logging Configuration
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s] %(message)s'}
# 日志格式
},
'filters': {
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '{}/Log/QWebFX_{}.log'.format(BASE_DIR, datetime.datetime.now().date()), # 日志输出文件
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份份数
'formatter': 'standard', # 使用哪种formatters日志格式
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '{}/Log/Error/QWebFX_Error_{}.log'.format(BASE_DIR, datetime.datetime.now().date()),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'request_handler': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '{}/Log/Request/QWebFX_Request_{}.log'.format(BASE_DIR, datetime.datetime.now().date()),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'scripts_handler': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '{}/Log/Script/QWebFX_Script_{}.log'.format(BASE_DIR, datetime.datetime.now().date()),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
}
},
'loggers': {
'django': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': False
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False,
},
'scripts': {
'handlers': ['scripts_handler'],
'level': 'INFO',
'propagate': False
},
'console': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True
},
# API/Views 模块的日志处理
'views': {
'handlers': ['default', 'error'],
'level': 'DEBUG',
'propagate': True
},
'util': {
'handlers': ['error'],
'level': 'ERROR',
'propagate': True
},
}
}
Explanation:
- formatters: Configure the log print format
- handler: Used to define how logs are specifically processed. Multiple handlers can be defined. "default" is the default method, and "console" is the method that prints to the console.
- loggers: Used to configure which handlers to use to process logs, for example when you need to output logs to both a file and the console.
Note:
- A logger of type "django" will handle all types of logs.
- sourceDns.webdns.views the application's py file
How to Record Logs
See the code example:
import logging
logger = logging.getLogger("console")
def index(request):
logger.debug("hello")
Note: The name used with getLogger is the logger we defined above in loggers.
Next, some parameters will be introduced and explained.
Logging Level Level
The focus of the logging module is generating and processing log messages. Each message consists of some text and an associated level indicating its severity. Levels include a symbolic name and a numeric value.
| Level | Value | Description |
|---|---|---|
| CRITICAL | 50 | Critical error/message |
| ERROR | 40 | Error |
| WARNING | 30 | Warning message |
| INFO | 20 | Informational message |
| DEBUG | 10 | Debug |
| NOTSET | 0 | No level |
Logger Logger
The logger is responsible for managing the default behavior of log messages, including the logging level, output destination, message format, and other basic details.
Keyword arguments:
- filename Append log messages to a file with the specified filename
- filemode Specify the mode used to open the file
- format Format string used to generate log messages
- datefmt Format string used to output the date and time
- level Set the logger's level
- stream Provide an open file used to send log messages to a file.
Log Message Format format
- %(name)s Logger name
- %(levelno)s Numeric logging level
- %(levelname)s Text name of the logging level
- %(filename)s Filename of the source file that made the logging call
- %(pathname)s Pathname of the source file that made the logging call
- %(funcName)s Function name that made the logging call
- %(module)s Module name that made the logging call
- %(lineno)s Line number that made the logging call
- %(created)s Time when the logging call was made
- %(asctime)s Date and time
- %(msecs)s Millisecond portion
- %(thread)d Thread ID
- %(threadName)s Thread name
- %(process)d Process ID
- %(message)s The logged message
Built-in Handlers handler
The logging module provides some handlers that can process log messages in various ways. Use the addHandler() method to add these handlers to a Logger object. You can also configure each handler with its own filtering and level.
- handlers.DatagramHandler(host,port): Send log messages to a UDP server at the specified host and port.
- handlers.FileHandler(filename): Write log messages to the file filename.
- handlers.HTTPHandler(host, url): Upload log messages to an HTTP server using HTTP GET or POST methods.
- handlers.RotatingFileHandler(filename): Write log messages to the file filename. If the file size exceeds the value specified by maxBytes, it will be backed up as filename1.
There are many more built-in handlers. If you want to learn more in depth, you can check the official manual.
Now that you roughly understand how to use logging, you can combine it with the previous examples.
_EOF_
Django+Logging: Logging Configuration and Usage
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Django数据导入导出神器django-import-export使用
前言 Django以快速开发闻名,但是如果处理数据的导出导入还需要自己写脚本,那就有违“Python之禅”了…… 而且导数据通常需要不同的格式,Excel、csv、json等,每种格式的数据就要写一个脚本太麻烦了,这时直接祭出django-import-export这个神器,官方一句话介绍:django-import-export is a Django application and libra
2021-12-18 · Django · 约 1 分钟
实测 Django 6.0:模版片段、后台任务、CSP 安全,三大特性体验报告
呵,连WebSocket都没塞进去就敢叫大版本更新?不过模版片段和内置后台任务总算让Django像个现代框架了,至少写HTMX时不用再到处塞碎片文件。原生CSP?早该有了。至于抛弃Python 3.11——跟不上时代的版本留着也是累赘。
2026-01-20 · Django · 约 1 分钟
Django的信号机制入门
概念 django自带一套信号机制来帮助我们在框架的不同位置之间传递信息。也就是说,当某一事件发生时,信号系统可以允许一个或多个发送者(senders)将通知或信号(signals)发送给一组接受者(receivers)。 (感觉就很像Qt的信号与槽机制) 信号系统包含以下三要素: 发送者-信号的发出方 信号-信号本身 接收者-信号的接受者 Django内置了一整套信号,下面是一些比较常用的: 在
2022-08-26 · Django · 约 1 分钟
一小时完成后台开发:DjangoRestFramework开发实践
DjangoRestFramework开发实践 在这之前我写过一篇关于Django与Drf快速开发实践的博客,Django快速开发实践:Drf框架和xadmin配置指北,粗略说了一下Drf配置和基本使用,不过里面只是涉及到最基本的CRUD,在正常的后端开发中涉及的诸如认证和权限、消息队列、缓存之类的操作,上一篇博客并没有涉及,这次开发我仔细了看了官方文档的这几个部分,把这部分的功能完善了起来。 D
2021-12-18 · Django · 约 1 分钟
讨论
共 0 条加载评论中…