Python/Django:在 runserver 下登录到控制台,在 Apache 下登录到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4558879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:18:30  来源:igfitidea点击:

Python/Django: log to console under runserver, log to file under Apache

pythondjangologging

提问by Justin Grant

How can I send trace messages to the console (like print) when I'm running my Django app under manage.py runserver, but have those messages sent to a log file when I'm running the app under Apache?

print当我在 下运行我的 Django 应用程序时manage.py runserver,如何将跟踪消息发送到控制台(如),但是当我在 Apache 下运行应用程序时将这些消息发送到日志文件?

I reviewed Django loggingand although I was impressed with its flexibility and configurability for advanced uses, I'm still stumped with how to handle my simple use-case.

我回顾了Django 日志记录,虽然我对其高级用途的灵活性和可配置性印象深刻,但我仍然对如何处理我的简单用例感到困惑。

采纳答案by Ignacio Vazquez-Abrams

Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use printdirectly, or use logginginstead.

在 mod_wsgi 下运行时,打印到 stderr 的文本将显示在 httpd 的错误日志中。可以print直接使用,也可以logging改用。

print >>sys.stderr, 'Goodbye, cruel world!'

回答by Ben Lopatin

You can configure logging in your settings.pyfile.

您可以在settings.py文件中配置日志记录。

One example:

一个例子:

if DEBUG:
    # will output to your console
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
    )
else:
    # will output to logging file
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
        filename = '/my_log_file.log',
        filemode = 'a'
    )

However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not?for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.

然而,这取决于设置 DEBUG,也许您不想担心它是如何设置的。请参阅有关如何判断我的 Django 应用程序是否在开发服务器上运行的答案以更好的方式编写该条件。编辑:上面的示例来自 Django 1.1 项目,自该版本以来,Django 中的日志记录配置发生了一些变化。

回答by Kyle Wild

You can do this pretty easily with tagalog(https://github.com/dorkitude/tagalog)

您可以使用tagalog(https://github.com/dorkitude/tagalog)轻松完成此操作

For instance, while the standard python module writes to a file object opened in append mode, the App Engine module (https://github.com/dorkitude/tagalog/blob/master/tagalog_appengine.py) overrides this behavior and instead uses logging.INFO.

例如,虽然标准 python 模块写入以追加模式打开的文件对象,但 App Engine 模块 (https://github.com/dorkitude/tagalog/blob/master/tagalog_appengine.py) 会覆盖此行为,而是使用logging.INFO.

To get this behavior in an App Engine project, one could simply do:

要在 App Engine 项目中获得这种行为,只需执行以下操作:

import tagalog.tagalog_appengine as tagalog
tagalog.log('whatever message', ['whatever','tags'])

You could extend the module yourself and overwrite the log function without much difficulty.

您可以自己扩展模块并轻松覆盖日志功能。

回答by m01

Here's a Django logging-based solution. It uses the DEBUG setting rather than actually checking whether or not you're running the development server, but if you find a better way to check for that it should be easy to adapt.

这是一个基于 Django 日志的解决方案。它使用 DEBUG 设置而不是实际检查您是否正在运行开发服务器,但是如果您找到更好的检查方法,它应该很容易适应。

LOGGING = {
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your/file.log',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

if DEBUG:
    # make all loggers use the console.
    for logger in LOGGING['loggers']:
        LOGGING['loggers'][logger]['handlers'] = ['console']

see https://docs.djangoproject.com/en/dev/topics/logging/for details.

有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/logging/

回答by xuejunliang

I use this:

我用这个:

logging.conf:

记录.conf:

[loggers]
keys=root,applog
[handlers]
keys=rotateFileHandler,rotateConsoleHandler

[formatters]
keys=applog_format,console_format

[formatter_applog_format]
format=%(asctime)s-[%(levelname)-8s]:%(message)s

[formatter_console_format]
format=%(asctime)s-%(filename)s%(lineno)d[%(levelname)s]:%(message)s

[logger_root]
level=DEBUG
handlers=rotateFileHandler,rotateConsoleHandler

[logger_applog]
level=DEBUG
handlers=rotateFileHandler
qualname=simple_example

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=applog_format
args=('applog.log', 'a', 10000, 9)

[handler_rotateConsoleHandler]
class=StreamHandler
level=DEBUG
formatter=console_format
args=(sys.stdout,)

testapp.py:

测试应用程序.py:

import logging
import logging.config

def main():
    logging.config.fileConfig('logging.conf')
    logger = logging.getLogger('applog')

    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    #logging.shutdown()

if __name__ == '__main__':
    main()

回答by jmoz

This works quite well in my local.py, saves me messing up the regular logging:

这在我的 local.py 中工作得很好,省去了我弄乱常规日志记录的麻烦:

from .settings import *

LOGGING['handlers']['console'] = {
    'level': 'DEBUG',
    'class': 'logging.StreamHandler',
    'formatter': 'verbose'
}
LOGGING['loggers']['foo.bar'] = {
    'handlers': ['console'],
    'propagate': False,
    'level': 'DEBUG',
}