本文介绍了在Django和Gunicorn中记录错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到错误时,我想登录Django和Gunicorn.我使用Python进行TDD研究, http://chimera.labs.oreilly.com/books/1234000000754/ch17.html#_setting_up_logging

这是我的代码./etc/init/gunicorn-superlists-staging.mysite.com.conf

 说明"superlists-staging.mysite.com的Gunicorn服务器"从网络设备启动在关机时停止重生Setuid Junsuchdir/home/junsu/sites/superlists-staging.mysite.com/sourceexec ../virtualenv/bin/gunicorn \--bind unix:/tmp/superlists-staging.mysite.com.socket \--access-logfile ../access.log \--error-logfile ../error.log \superlists.wsgi:应用程序 

accounts/authentication.py

 导入请求导入日志从django.contrib.auth导入get_user_model用户= get_user_model()PERSONA_VERIFY_URL ='https://verifier.login.persona.org/verify'域 = '本地主机'类PersonaAuthenticationBackend(object):def authenticate(自我,断言):logging.warning('验证功能')响应= request.post(PERSONA_VERIFY_URL,data = {'assertion':断言,'audience':settings.DOMAIN})logging.warning('获取响应表单角色')logging.warning(response.content.decode())如果 response.ok 和 response.json()['status'] == 'ok':email = response.json()['email']尝试:返回User.objects.get(email = email)除了User.DoesNotExist:返回User.objects.create(email = email)def get_user(自己,电子邮件):尝试:返回User.objects.get(email = email)除了User.DoesNotExist:不返回 

superlists/settings.py

  [....]记录= {'版本':1,'disable_existing_logger':否,处理程序":{'安慰': {'level':'DEBUG','class':'logging.StreamHandler',},},记录器":{'django':{'handlers':['console'],},},'root':{'level':'INFO'},} 

我的"error.log"只是记录下来.

  [2016-02-08 14:42:56 +0900] [3355] [INFO]侦听:Unix:/tmp/superlists-staging.mysite.com.socket(3355)[2016-02-08 14:42:56 +0900] [3355] [INFO]使用worker:同步[2016-02-08 14:42:56 +0900] [3359] [INFO]使用pid启动工人:3359[2016-02-08 14:58:22 +0900] [3355] [INFO]处理信号:术语[2016-02-08 14:58:22 +0900] [3355] [INFO]正在关机:大师[2016-02-08 14:58:22 +0900] [3470] [INFO]开始使用Gunicorn 19.4.3[2016-02-08 14:58:22 +0900] [3470] [INFO]收听:Unix:/tmp/superlists-staging.mysite.com.socket(3470)[2016-02-08 14:58:22 +0900] [3470] [INFO]使用worker:同步[2016-02-08 14:58:22 +0900] [3474] [INFO]使用pid引导的工作人员:3474 

我想查看错误记录,该怎么办?

解决方案

tl; dr您的代码没有错

似乎您正确地遵循了链接的教程,并且可能会在/home/junsu/sites/superlists-staging.mysite.com/目录中找到您的日志文件.

无论如何,在您的问题中有几点要解决,我会尽力做到这一点.

记录器和处理程序

您在上面引用的设置模块设置了一个日志记录处理程序控制台( StreamHandler )和一个可以使用该处理程序的 django 记录器.

root 记录器未定义任何处理程序,并且"django"会将任何内容记录到 stderr 中,并且仅记录INFO或更高级别.我进行了一个快速测试, root 记录器还默认定义了 StreamHandler .

您的 authentication.py 模块当前调用 logging.warning 记录到 root logger (即,它执行 logger = logging.getLogger(); logger.warning('stuff')).但是,您可能需要定义一个更具体的处理程序,以更轻松地定位模块的日志.在本教程的这一部分中进行了解释./p>

Gunicorn 默认重定向标准错误

默认情况下已设置为捕获 stderr ,您目前将其重定向到日志文件.但是,我的建议是使用守护程序(好像您正在使用 upstart )来记录stderr/out.

新贵记录

gunicorn文档中所述,配置 upstart非常简单.

如果在/etc/init/gunicorn-superlists-staging.mysite.com.conf 配置中删除-error-logfile 选项,gunicorn将默认将其输出记录到 stderr ,然后可以由新贵以任何您喜欢的方式捕获.

如果您使用的是新贵1.7或更高版本,则默认情况下应启用 stdout/err捕获.但是,如果您使用的是新贵的较早版本,我的建议是在您的计算机上添加 console log 选项配置,所有输出(stdout/stderr)将被简单地记录到(我假设)/var/log/upstart/gunicorn-superlists-staging.mysite.com.log

I want logging in Django and Gunicorn, when I get error.I study with TDD with Python, http://chimera.labs.oreilly.com/books/1234000000754/ch17.html#_setting_up_logging

this is my code./etc/init/gunicorn-superlists-staging.mysite.com.conf

description "Gunicorn server for superlists-staging.mysite.com"

start on net-device-up
stop on shutdown

respawn

setuid junsu
chdir /home/junsu/sites/superlists-staging.mysite.com/source

exec ../virtualenv/bin/gunicorn \
    --bind unix:/tmp/superlists-staging.mysite.com.socket \
    --access-logfile ../access.log \
    --error-logfile ../error.log \
    superlists.wsgi:application

accounts/authentication.py

import requests
import logging
from django.contrib.auth import get_user_model
User = get_user_model()

PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify'
DOMAIN = 'localhost'

class PersonaAuthenticationBackend(object):

    def authenticate(self, assertion):
        logging.warning('authenticate function')
        response = requests.post(
            PERSONA_VERIFY_URL,
            data={'assertion': assertion, 'audience': settings.DOMAIN}
        )
        logging.warning('got response form persona')
        logging.warning(response.content.decode())
        if response.ok and response.json()['status'] == 'okay':
            email = response.json()['email']
            try:
                return User.objects.get(email=email)
            except User.DoesNotExist:
                return User.objects.create(email=email)

    def get_user(self, email):
        try:
            return User.objects.get(email=email)
        except User.DoesNotExist:
            return None

superlists/settings.py

[....]
LOGGING = {
    'version': 1,
    'disable_existing_logger': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
        },
    },
    'root': {'level': 'INFO'},
}

my "error.log" just log this.

[2016-02-08 14:42:56 +0900] [3355] [INFO] Listening at: unix:/tmp/superlists-staging.mysite.com.socket (3355)
[2016-02-08 14:42:56 +0900] [3355] [INFO] Using worker: sync
[2016-02-08 14:42:56 +0900] [3359] [INFO] Booting worker with pid: 3359
[2016-02-08 14:58:22 +0900] [3355] [INFO] Handling signal: term
[2016-02-08 14:58:22 +0900] [3355] [INFO] Shutting down: Master
[2016-02-08 14:58:22 +0900] [3470] [INFO] Starting gunicorn 19.4.3
[2016-02-08 14:58:22 +0900] [3470] [INFO] Listening at: unix:/tmp/superlists-staging.mysite.com.socket (3470)
[2016-02-08 14:58:22 +0900] [3470] [INFO] Using worker: sync
[2016-02-08 14:58:22 +0900] [3474] [INFO] Booting worker with pid: 3474

I want see error loging, What can I do?

解决方案

tl;dr there's nothing wrong with your code

It seems you've followed the linked tutorial correctly, and would probably find your log files in the /home/junsu/sites/superlists-staging.mysite.com/ dir.

Regardless, there are a few points to address in your question, I'll try to do that.

Loggers and handlers

The settings module you reference above sets up a single logging handler console (StreamHandler), and a single django logger which can use that handler.

The root logger does not define any handlers, and "django" will log anything to stderr, and only for level INFO and above. I ran a quick test, and the root logger also has a StreamHandler defined by default.

Your authentication.py module currently calls logging.warning which logs to root logger (i.e it does logger = logging.getLogger(); logger.warning('stuff')). However, you may want to define a more specific handler to easier locate the log of your module. This is explained in this section of the referenced tutorial.

Gunicorn redirects stderr by default

It seems by default is set up to capture the stderr stream, which you currently redirect to a log file. However, my suggestion is to use your daemonizing app (seems like you're using upstart) to log the stderr/out.

Upstart logging

As explained in gunicorn docs, configuring upstart is pretty simple.

If you remove the --error-logfile option in your /etc/init/gunicorn-superlists-staging.mysite.com.conf config, gunicorn will default to logging it's output to stderr which can then be captured by upstart in whatever manner you prefer.

If you are using upstart 1.7 or greater, stdout/err capturing should be enabled by default. If, however, you use an earlier version of upstart, my suggestion is to add a console log option in your config and all output (stdout/stderr) will simply be logged to (I assume) /var/log/upstart/gunicorn-superlists-staging.mysite.com.log

这篇关于在Django和Gunicorn中记录错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 20:51