program story

Python / Django : runserver에서 콘솔에 로그, Apache에서 파일에 로그

inputbox 2020. 8. 7. 08:22
반응형

Python / Django : runserver에서 콘솔에 로그, Apache에서 파일에 로그


에서 printDjango 앱을 실행할 때 추적 메시지 (예 :)를 콘솔에 보내려면 어떻게 manage.py runserver해야합니까?하지만 Apache에서 앱을 실행할 때 해당 메시지를 로그 파일로 보내도록해야합니까?

Django 로깅을 검토 한 결과 고급 사용을위한 유연성과 구성 가능성에 감명을 받았지만 여전히 간단한 사용 사례를 처리하는 방법에 어리둥절합니다.


stderr에 인쇄 된 텍스트는 mod_wsgi에서 실행할 때 httpd의 오류 로그에 표시됩니다. print직접 사용하거나 logging대신 사용할 수 있습니다 .

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

다음은 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']

자세한 내용은 https://docs.djangoproject.com/en/dev/topics/logging/ 을 참조하십시오.


settings.py파일 에서 로깅을 구성 할 수 있습니다 .

한 가지 예 :

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'
    )

그러나 이는 DEBUG 설정에 따라 다르며 설정 방법에 대해 걱정할 필요가 없을 수도 있습니다. Django 애플리케이션이 개발 서버에서 실행 중인지 여부어떻게 알 수 있습니까?에 대한이 답변을 참조하십시오 . 조건문을 작성하는 더 좋은 방법입니다. 편집 : 위의 예제는 Django 1.1 프로젝트에서 가져온 것입니다. Django의 로깅 구성은 해당 버전 이후 약간 변경되었습니다.


나는 이것을 사용한다 :

logging.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:

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()

You can do this pretty easily with 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.

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

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.


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

from .settings import *

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

참고URL : https://stackoverflow.com/questions/4558879/python-django-log-to-console-under-runserver-log-to-file-under-apache

반응형