django 为不同设置配置不同日志文件位置的干式方法是什么?

wgx48brx  于 2023-04-07  发布在  Go
关注(0)|答案(2)|浏览(117)

我在一个django项目中使用python的logging模块。我在我的settings.py文件中执行基本的日志配置。如下所示:

import logging   
import logging.handlers
logger = logging.getLogger('project_logger')
logger.setLevel(logging.INFO)

LOG_FILENAME = '/path/to/log/file/in/development/environment'
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight')
formatter = logging.Formatter(LOG_MSG_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)

我有一个单独的生产设置文件。这个文件(production.py)从settings导入所有内容并覆盖某些选项(将DEBUG设置为False,例如)。我希望在生产环境中使用不同的LOG_FILENAME。我应该怎么做?我可以在production.py中重复整个配置部分,但如果生产机器中没有/path/to/log/file/in/development/environment,就会产生问题。
有人能提出一个更好的方法来解决这个问题吗?

mefy6pfw

mefy6pfw1#

你为什么不把这句话放在www.example.com的末尾settings.py,并使用DEBUG标志进行开发?
就像这样:

import logging   
import logging.handlers
logger = logging.getLogger('project_logger')
logger.setLevel(logging.INFO)

[snip]
if DEBUG:
    LOG_FILENAME = '/path/to/log/file/in/development/environment'
else:
    LOG_FILENAME = '/path/to/log/file/in/production/environment'

handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight')
formatter = logging.Formatter(LOG_MSG_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)
dxxyhpgq

dxxyhpgq2#

找到了一个合理的“DRY”解决方案。感谢Django中的Python日志
我现在有一个log.py,它看起来像这样:

import logging, logging.handlers
from django.conf import settings

LOGGING_INITIATED = False
LOGGER_NAME = 'project_logger'

def init_logging():
    logger = logging.getLogger(LOGGER_NAME)
    logger.setLevel(logging.INFO)
    handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_FILENAME, when = 'midnight')
    formatter = logging.Formatter(LOG_MSG_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

if not LOGGING_INITIATED:
    LOGGING_INITIATED = True
    init_logging()

我的settings.py现在包含

LOG_FILENAME = '/path/to/log/file/in/development/environment

production.py包含:

from settings import *
LOG_FILENAME = '/path/to/log/file/in/production/environment'

相关问题