django 1.3 的简单日志到文件示例

发布于 2024-11-02 08:26:16 字数 613 浏览 0 评论 0原文

发行说明说:

Django 1.3 添加了框架级别 支持 Python 的日志记录模块。

那很好。我想利用这一点。不幸的是 文档 并没有将所有内容都放在银盘上交给我完整的工作示例代码的形式,展示了这是多么简单和有价值。

我如何设置这个时髦的新功能,以便我可以在我的代码中添加

logging.debug('really awesome stuff dude: %s' % somevar)

并查看文件“/tmp/application.log”填充

18:31:59 Apr 21 2011 awesome stuff dude: foobar
18:32:00 Apr 21 2011 awesome stuff dude: foobar
18:32:01 Apr 21 2011 awesome stuff dude: foobar

默认Python日志记录和“框架级支持”之间的区别是什么?

The release notes say:

Django 1.3 adds framework-level
support for Python’s logging module.

That's nice. I'd like to take advantage of that. Unfortunately the documentation doesn't hand it all to me on a silver platter in the form of complete working example code which demonstrates how simple and valuable this is.

How do I set up this funky new feature such that I can pepper my code with

logging.debug('really awesome stuff dude: %s' % somevar)

and see the file "/tmp/application.log" fill up with

18:31:59 Apr 21 2011 awesome stuff dude: foobar
18:32:00 Apr 21 2011 awesome stuff dude: foobar
18:32:01 Apr 21 2011 awesome stuff dude: foobar

What's the difference between the default Python logging and this 'framework-level support'?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蝶…霜飞 2024-11-09 08:26:16

我真的非常喜欢这个,这是你的工作示例!说真的,这太棒了!

首先将其放入您的 settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': SITE_ROOT + "/logfile",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'MYAPP': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    }
}

现在这一切意味着什么?

  1. 格式化程序 我喜欢它与 ./manage.py runserver 处理程序具有相同的风格
  2. - 我想要两个日志 - 一个调试文本文件和一个信息控制台。这使我能够真正深入(如果需要)并查看文本文件以了解幕后发生的情况。
  3. 记录器 - 这是我们确定要记录的内容的地方。一般来说,django 会收到 WARN 及以上警告 - 例外(因此传播)是后端,我喜欢在其中看到 SQL 调用,因为它们可能会变得疯狂。最后是我的应用程序,我有两个处理程序并将所有内容推送到它。

现在如何让 MYAPP 使用它...

根据 文档< /a> 将其放在文件的顶部(views.py)..

import logging
log = logging.getLogger(__name__)

然后为了得到一些东西,请执行此操作。

log.debug("Hey there it works!!")
log.info("Hey there it works!!")
log.warn("Hey there it works!!")
log.error("Hey there it works!!")

此处解释了日志级别以及纯 python < a href="http://docs.python.org/library/logging.html" rel="noreferrer">此处。

I truly love this so much here is your working example! Seriously this is awesome!

Start by putting this in your settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': SITE_ROOT + "/logfile",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'MYAPP': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    }
}

Now what does all of this mean?

  1. Formaters I like it to come out as the same style as ./manage.py runserver
  2. Handlers - I want two logs - a debug text file, and an info console. This allows me to really dig in (if needed) and look at a text file to see what happens under the hood.
  3. Loggers - Here is where we nail down what we want to log. In general django gets WARN and above - the exception (hence propagate) is the backends where I love to see the SQL calls since they can get crazy.. Last is my app were I have two handlers and push everything to it.

Now how do I enable MYAPP to use it...

Per the documentation put this at the top of your files (views.py)..

import logging
log = logging.getLogger(__name__)

Then to get something out do this.

log.debug("Hey there it works!!")
log.info("Hey there it works!!")
log.warn("Hey there it works!!")
log.error("Hey there it works!!")

Log levels are explained here and for pure python here.

赏烟花じ飞满天 2024-11-09 08:26:16

部分基于 rh0dium 建议的日志配置和我自己做的一些更多研究,我开始组装一个具有良好日志记录默认值的示例 Django 项目 – 失败-nicely-django

示例日志文件输出:

2016-04-05 22:12:32,984 [Thread-1    ] [INFO ] [djangoproject.logger]  This is a manually logged INFO string.
2016-04-05 22:12:32,984 [Thread-1    ] [DEBUG] [djangoproject.logger]  This is a manually logged DEBUG string.
2016-04-05 22:12:32,984 [Thread-1    ] [ERROR] [django.request      ]  Internal Server Error: /
Traceback (most recent call last):
  File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/kermit/projekti/git/fail-nicely-django/djangoproject/brokenapp/views.py", line 12, in brokenview
    raise Exception('This is an exception raised in a view.')
Exception: This is an exception raised in a view.

详细用法在 README 中进行了解释,但本质上,您复制 logger 模块添加到您的 Django 项目中,并在您的 settings.py 底部添加 from .logger import LOGGING

Based partially on the logging config suggested by rh0dium and some more research I did myself, I started assembling an example Django project with nice logging defaults – fail-nicely-django.

Sample logfile output:

2016-04-05 22:12:32,984 [Thread-1    ] [INFO ] [djangoproject.logger]  This is a manually logged INFO string.
2016-04-05 22:12:32,984 [Thread-1    ] [DEBUG] [djangoproject.logger]  This is a manually logged DEBUG string.
2016-04-05 22:12:32,984 [Thread-1    ] [ERROR] [django.request      ]  Internal Server Error: /
Traceback (most recent call last):
  File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/kermit/projekti/git/fail-nicely-django/djangoproject/brokenapp/views.py", line 12, in brokenview
    raise Exception('This is an exception raised in a view.')
Exception: This is an exception raised in a view.

The detailed usage is explained in the README, but essentially, you copy the logger module to your Django project and add from .logger import LOGGING at the bottom of your settings.py.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文