返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Django

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

曦远 (DealiAxy)约 18 分钟
目录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:

  1. formatters: Configure the log print format
  2. 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.
  3. 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:

  1. A logger of type "django" will handle all types of logs.
  2. 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.

LevelValueDescription
CRITICAL50Critical error/message
ERROR40Error
WARNING30Warning message
INFO20Informational message
DEBUG10Debug
NOTSET0No 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-TinyMCE组件支持上传图片功能

Django自带的Admin后台,好用,TinyMCE作为富文本编辑器,也蛮好用的,这两者结合起来在做博客的时候很方便(当然博客可能更适合用Markdown来写),但是Django-TinyMCE这个组件默认没有图片上传功能的,需要我们自己实现,本文将一步步带大家实现这个图片上传功能。 读者也可以举一反三实现其他需要和Django结合的功能。 编写上传图片逻辑 在任一views.py里添加代码:

2021-12-18 · Django · 约 1 分钟

Django探索验证码功能的实现 - DjangoStarter项目模板里的封装

前言 依然是最近在做的这个项目,用Django做后端,App上提交信息的时候需要一个验证码来防止用户乱提交,正好我的「DjangoStarter」项目脚手架也有封装了验证码功能,不过我发现好像里面只是把验证码作为admin后台登录的校验手段,并没有给出前后端分离项目的验证码相关接口。 所以本文介绍验证码功能实现的同时,也对「DjangoStarter」的验证码模块做一层封装,使其更方便使用~ 用哪

2022-04-09 · Django · 约 1 分钟

Django中间件之实现Admin后台IP白名单

前言 Django自带的Admin管理后台很方便,但是实际生产环境真的会有挺多安全问题的,在admin的安全防护这方面,我之前就研究实现了给admin加上登录验证码和限流功能,可以参考这篇文章:给Django Admin添加验证码和多次登录尝试限制 不过就在内部使用的话就好很多,因此我们可以通过Django的中间件来实现IP过滤,所以本文中涉及到两个知识点,一个是Django的中间件,另外一个是P

2022-08-26 · Django · 约 1 分钟

Django数据库性能优化之使用Python集合操作

前言 最近有个新需求: 人员基础信息(记作人员A),10w 某种类型的人员信息(记作人员B),1000 要求在后台上(Django Admin)分别展示:已录入A的人员B列表、未录入的人员B列表 团队的DBA提议使用视图可以解决这个问题(不愧是搞数据库的) PS:起先我觉得Django的Model是直接管理数据库表的,使用Model来映射数据库模型怕是有一定的麻烦,不过查了一下资料发现并不会~ 只

2022-08-26 · Django · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…