随心一记

一二三四五,上山打老鼠


  • 首页

  • 归档

  • 标签
ywcsb

ywcsb

游戏可以不玩,小说不能不看。

153 日志
3 分类
42 标签
RSS
GitHub 知乎 随心一记
Links
  • 随心一记
  • 追梦人物的
  • MSDN

Django 异常日志输出到一行

发表于 2022-04-03 | 阅读 1142 | 分类于 Python |

一些常见的跨平台日志收集平台,如阿里云日志、efk,一般都是按一行作为一条日志记录。

Python默认的输出会将消息原样输出,如果有异常的话,会将异常堆栈多行形式返回。不方便进行日志的收集分析。所以需要将其输出为一行。

创建MyFormatter格式化类

参考官方

import logging

class MyFormatter(logging.Formatter):
    def formatException(self, exc_info):
        """
        格式化异常,使其打印在一行上。
        """
        result = super().formatException(exc_info)
        return repr(result)  
     def format(self, record):
        record.message = record.getMessage()
        if self.usesTime():
            record.asctime = self.formatTime(record, self.datefmt)
        s = self.formatMessage(record)
        if record.exc_info:
            # Cache the traceback text to avoid converting it multiple times
            # (it's constant anyway)
            if not record.exc_text:
                record.exc_text = self.formatException(record.exc_info)
        if record.stack_info:
            if s[-1:] != "\n":
                s = s + "\n"
            s = s + self.formatStack(record.stack_info)
        if record.exc_text:
            # 在log最后追加异常信息
            s = s + " " + record.exc_text
        return s

Django LOGGING更改

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
             # 加载刚刚编写的MyFormatter类
            '()': 'blog.jsonLog.MyFormatter',
            'format': '[%(asctime)s] %(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
    'handlers': {
        # 默认记录所有日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': f'{Path.joinpath(log_path, "default.log")}',  # 日志输出文件
            'maxBytes': 1024 * 1024 * 1024 * 2,  # 文件大小
            'backupCount': 5,  # 备份份数
            'formatter': 'simple',  # 使用哪种formatters日志格式
            'encoding': 'utf-8',
            # 'filters': ['require_debug_false']
        },

        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'sql_db': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': f'{Path.joinpath(log_path, "sql_db.log")}',
            'maxBytes': 1024 * 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'simple',
            'encoding': 'utf-8',
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False
        },
        'scripts': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['sql_db'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}

验证

Djangolog

觉得不错,支持一下!
geerniya WeChat Pay

微信打赏

geerniya Alipay

支付宝打赏

# Python # Django
EFK 收集 Ingress Nginx 日志
Python 装饰器 运行时间

发表评论

共 0 条评论

    暂无评论
© 2018 - 2022 ywcsb
冀ICP备17022045号-1
Supported by 腾讯云