"/>
侧边栏壁纸
博主头像
PySuper博主等级

千里之行,始于足下

  • 累计撰写 204 篇文章
  • 累计创建 14 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录
Web

Django 在终端根据日志级别显示不同颜色

PySuper
2020-09-29 / 0 评论 / 0 点赞 / 6 阅读 / 6686 字
温馨提示:
所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊

配置日志

import os
from .base import BASE_DIR
from utils import log_theme

# 日志配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用日志器

    # 日志格式
    'formatters': {
        # 详细格式,名字可随意取
        'verbose': {
            # 格式:	    报错等级	       报错时间	   模块	       行号	  信息
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        # 简单格式
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },

    # 过滤器
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',  # 过滤掉调试信息
        },
    },

    # 处理错误信息的对象
    'handlers': {
        'console': {  # 处理错误信息的控制台对象,即我们在pycharm中看到的调试信息由此控制
            'level': 'DEBUG',  # DEBUG以上级别报错信息都会出现在控制台
            'filters': ['require_debug_true'],  # 设定过滤器
            'class': 'logging.StreamHandler',  # 日志处理器
            'formatter': 'verbose'  # 日志格式设为详细格式
        },
        'file': {  # 处理错误信息的file对象
            'level': 'INFO',  # 记录INFO级别以上的报错信息
            'class': 'logging.handlers.RotatingFileHandler',  # 日志处理器

            # 日志位置,日志文件名,日志保存目录logs必须手动创建,一般创建在项目根目录下
            'filename': os.path.join(os.path.dirname(BASE_DIR), "logs/cms.log"),
            'maxBytes': 300 * 1024 * 1024,  # 日志文件的最大值,这里我们设置300M
            'backupCount': 10,  # 日志文件的数量,设置最大日志数量为10
            'formatter': 'verbose'  # 日志格式:详细格式,日志格式在上面定义了
        },
    },

    # 日志对象
    'loggers': {
        # 日志器名
        'django': {
            'handlers': ['console', 'file'],  # 处理对象有两个:conosle、file对象;在上面的handlers中进行了定义和配置;
            'propagate': True,  # 是否让日志信息继续冒泡给其他的日志处理系统,子级向父级传播
        },
    }
}

显示颜色

import logging


def add_coloring_to_emit_windows(fn):
    def _out_handle(self):
        import ctypes
        return ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)

    out_handle = property(_out_handle)

    def _set_color(self, code):
        import ctypes

        self.STD_OUTPUT_HANDLE = -11
        hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
        ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code)

    setattr(logging.StreamHandler, '_set_color', _set_color)

    def new(*args):
        FOREGROUND_BLUE = 0x0001  # text color contains blue.
        FOREGROUND_GREEN = 0x0002  # text color contains green.
        FOREGROUND_RED = 0x0004  # text color contains red.
        FOREGROUND_INTENSITY = 0x0008  # text color is intensified.
        FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED

        # winbase.h
        STD_INPUT_HANDLE = -10
        STD_OUTPUT_HANDLE = -11
        STD_ERROR_HANDLE = -12

        # wincon.h
        FOREGROUND_BLACK = 0x0000
        FOREGROUND_BLUE = 0x0001
        FOREGROUND_GREEN = 0x0002
        FOREGROUND_CYAN = 0x0003
        FOREGROUND_RED = 0x0004
        FOREGROUND_MAGENTA = 0x0005
        FOREGROUND_YELLOW = 0x0006
        FOREGROUND_GREY = 0x0007
        FOREGROUND_INTENSITY = 0x0008  # foreground color is intensified.

        BACKGROUND_BLACK = 0x0000
        BACKGROUND_BLUE = 0x0010
        BACKGROUND_GREEN = 0x0020
        BACKGROUND_CYAN = 0x0030
        BACKGROUND_RED = 0x0040
        BACKGROUND_MAGENTA = 0x0050
        BACKGROUND_YELLOW = 0x0060
        BACKGROUND_GREY = 0x0070
        BACKGROUND_INTENSITY = 0x0080  # background color is intensified.

        levelno = args[1].levelno
        if (levelno >= 50):
            color = BACKGROUND_YELLOW | FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY
        elif (levelno >= 40):
            color = FOREGROUND_RED | FOREGROUND_INTENSITY
        elif (levelno >= 30):
            color = FOREGROUND_YELLOW | FOREGROUND_INTENSITY
        elif (levelno >= 20):
            color = FOREGROUND_GREEN
        elif (levelno >= 10):
            color = FOREGROUND_MAGENTA
        else:
            color = FOREGROUND_WHITE
        args[0]._set_color(color)

        ret = fn(*args)
        args[0]._set_color(FOREGROUND_WHITE)
        # print "after"
        return ret

    return new


def add_coloring_to_emit_ansi(fn):
    # add methods we need to the class
    def new(*args):
        levelno = args[1].levelno
        if (levelno >= 50):
            color = '\x1b[31m'  # red
        elif (levelno >= 40):
            color = '\x1b[31m'  # red
        elif (levelno >= 30):
            color = '\x1b[33m'  # yellow
        elif (levelno >= 20):
            color = '\x1b[32m'  # green
        elif (levelno >= 10):
            color = '\x1b[35m'  # pink
        else:
            color = '\x1b[0m'  # normal
        try:
            args[1].msg = color + args[1].msg + '\x1b[0m'  # normal
        except Exception as e:
            pass
        # print "after"
        return fn(*args)

    return new


import platform

if platform.system() == 'Windows':
    logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
else:
    logging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
    # log = logging.getLogger()
    # log.addFilter(log_filter())
    # //hdlr = logging.StreamHandler()
    # //hdlr.setFormatter(formatter())


class Color:
    Black = 0
    Red = 1
    Green = 2
    Yellow = 3
    Blue = 4
    Magenta = 5
    Cyan = 6
    White = 7


class Mode:
    Foreground = 30
    Background = 40
    ForegroundBright = 90
    BackgroundBright = 100


def tcolor(c, m=Mode.Foreground):
    return '\033[{}m'.format(m + c)


def treset():
    return '\033[0m'
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区