Django 日志输出及打印--logging

2023-07-31,,

Django使用python自带的logging作为日志打印工具。

logging是线程安全的,主要分为4部分:

    Logger 
    用户使用的直接接口,将日志传递给Handler
    Handler 
    控制日志输出到哪里,console,file… 
    一个logger可以有多个Handler
    Filter 
    控制哪些日志可以从logger流向Handler
    Formatter 
    控制日志的格式

在使用 django 开发过程中,默认的日志输出是不能满足我们去排查问题的,往往需要自定义的日志输出,帮助我们去排查程序BUG,定位问题原因。Django通过在settings文件中使用LOGGING来定制日志输出(包括定义logger, handler, formatter等),例如,settings文件中定义如下:

BASE_LOG_DIR = os.path.join(BASE_DIR, "log")
LOGGING = {
'version': , # 保留字
'disable_existing_loggers': False, # 禁用已经存在的logger实例
# 日志文件的格式
'formatters': {
# 详细的日志格式
'standard': {
'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
'[%(levelname)s][%(message)s]'
},
# 简单的日志格式
'simple': {
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
# 定义一个特殊的日志格式
'collect': {
'format': '%(message)s'
}
},
# 过滤器
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
# 处理器
'handlers': {
# 在终端打印
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'], # 只有在Django debug为True时才在屏幕打印日志
'class': 'logging.StreamHandler', #
'formatter': 'simple'
},
# 默认的
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件
'maxBytes': * * , # 日志大小 50M
'backupCount': , # 最多备份几个
'formatter': 'standard',
'encoding': 'utf-8',
},
# 专门用来记错误日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件
'maxBytes': * * , # 日志大小 50M
'backupCount': ,
'formatter': 'standard',
'encoding': 'utf-8',
},
# 专门定义一个收集特定信息的日志
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
'maxBytes': * * , # 日志大小 50M
'backupCount': ,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': {
# 默认的logger应用如下配置
'': {
'handlers': ['default', 'console', 'error'], # 上线之后可以把'console'移除
'level': 'DEBUG',
'propagate': True, # 向不向更高级别的logger传递
},
# 名为 'collect'的logger还单独处理
'collect': {
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
}

使用方法:

import logging
# 生成一个以当前文件名为名字的logger实例
logger = logging.getLogger(__name__)
def index(request):
logger.debug("一个萌萌的请求过来了。。。。")
logger.info("一个更萌的请求过来了。。。。")
logger.debug("这是app01里面的index视图函数") return HttpResponse("OK")

Django 日志输出及打印--logging的相关教程结束。

《Django 日志输出及打印--logging.doc》

下载本文的Word格式文档,以方便收藏与打印。