Django rest框架在不同文件上记录不同级别 [英] Django rest framework logging different levels on different files

查看:81
本文介绍了Django rest框架在不同文件上记录不同级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django REST框架,并且我希望有单独的文件来记录数据

I am working on Django REST framework and I want to have separate files for logging data.

我想要一个用于简单交易的文件,例如GET,PUT,POST等文件,以及一个包含错误的文件,如果发生错误,我将收集这些错误.

I want to have a file for the simple transactions e.g. GET, PUT, POST etc. and one file with the errors that I will collect in case of an error.

我一直在阅读 Django日志记录文档,关于如何记录信息数据的一些配置.以下是配置示例:

I have been reading the Django Logging Documentation and I came up with some configurations on how to log the info data. Sample of configurations bellow:

settings.py

STATIC_URL = '/static/'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
LOGGING_ROOT = os.path.join(STATIC_ROOT, 'logging')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': LOGGING_ROOT + "/info.log",
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

它可以作为文件中数据的预期样本:

It works as expected sample of data in file:

"PUT /upload/dat.txt HTTP/1.1" 204 14
"OPTIONS / HTTP/1.1" 200 10020
"GET / HTTP/1.1" 200 9916

我试图在settings.py文件中应用另一个处理程序,例如:

I tried to apply another handler in the settings.py file e.g.:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'fileInfo': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': LOGGING_ROOT + "/info.log",
        },
        'fileDebug': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': LOGGING_ROOT + "/debbug.log",
        },
    },
    'loggers': {
        'django': {
            'handlers': ['fileInfo'],
            'level': 'INFO',
            'propagate': True,
        },
        'django': {
            'handlers': ['fileDebug'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

我无法按预期工作,现在我将所有数据(INFO和DEBUG)存储在同一文件debug.log中.因此,我决定通过日志记录库采用另一种方法.我不知道的是如何将这些日志错误的输出通过管道传递到目录中. (路径/errors.log).

I does not work as expected, now I am getting all the data (INFO and DEBUG) on the same file debug.log. So I decided to have another approach through the logging library. What I can not figure out is how to pipe the output of these log errors into the directory e.g. (path/errors.log).

从文档中:

# import the logging library
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def my_view(request, arg1, arg):
    ...
    if bad_mojo:
        # Log an error message
        logger.error('Something went wrong!')

我发现了类似的问题找不到用于记录程序的处理程序,如果我应用以下内容,它将起作用:

I found this similar question No handlers could be found for logger and it works if I apply the following:

import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.error('Something went wrong!')

现在一切都记录在标准输出上(INFO和ERROR).有没有办法组合这些配置?

Now everything is logged on the stdout (INFO and ERROR). Is there a way to combine those configurations?

我想将所有请求记录到info.log文件中,并在选择文件时将错误记录在error.log文件中.

I want to log all requests into the info.log file, and log errors in the error.log file when I choose on my file.

更新:

bruno desthuilliers 示例波纹管提供的解决方案:

Solution provided by bruno desthuilliers sample bellow:

settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'fileInfo': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_ROOT, "info.log"),
        },
        'fileDebug': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_ROOT, "debug.log")
        },
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'fileInfo', 'fileDebug'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

我还发现制作Python除日志外,记录器还将所有消息输出到stdout.我当前的修改示例:

I also found Making Python loggers output all messages to stdout in addition to log. Sample of my current modifications:

import logging
from thanosTest import settings
logging.basicConfig(filename=os.path.join(settings.LOGGING_ROOT, "error.log"))
stderrLogger = logging.StreamHandler()
stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logging.getLogger().addHandler(stderrLogger)
logging.error('Something went wrong!')

现在所有内容都记录在error.log上.我想我需要进行一些过滤或其他操作.我会设法弄清楚的.

Now everything gets logged on the error.log. I guess I need to apply some filtering or something. I will try to figure it out.

推荐答案

此处:

'loggers': {
    'django': {
        'handlers': ['fileInfo'],
        'level': 'INFO',
        'propagate': True,
    },
    'django': {
        'handlers': ['fileDebug'],
        'level': 'DEBUG',
        'propagate': True,
    },

您两次定义了"django"键,因此第二个覆盖第一个.

You define the 'django' key twice, so the second overwrite the first.

作为一般规则,如果您想要给定记录器的特定设置,请将其配置为单独的记录器(即,每个软件包或django应用程序一个记录器).还要注意,记录器的处理程序"是列表,因此每个记录器可以有多个处理程序(即,一个用于调试,一个用于信息). logging库有点复杂,但是要花一些时间阅读完整的文档进行一些尝试确实值得.

As a general rule, if you want specific settings for a given logger, configure it as a distinct logger (ie one logger per package or django app). Also note that the logger's "handlers" are lists so you can have more than one handler per logger (ie one for debug and one for info). The logging lib is a bit complex but taking time to read the full doc and experimenting a bit is worth the effort, really.

其他一些注意事项:

  1. 为多进程应用程序使用文件处理程序(在生产中django通常由多进程前端服务器提供服务)通常不是一个坏主意(对文件的并发写入访问永远不会真正起作用).

  1. using file handlers for multiprocess apps (in production django is most often served by multiprocess front servers) is more often than not a bad idea (concurrent write accesses to a file never really work).

这种'filename': LOGGING_ROOT + "/info.log"击败了使用os.path的全部要点-您希望使用os.path.join(LOGGING_ROOT, "info.log")代替

this 'filename': LOGGING_ROOT + "/info.log" kind of defeats the whole point of using os.path - you want os.path.join(LOGGING_ROOT, "info.log") instead

这篇关于Django rest框架在不同文件上记录不同级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆