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

时间:2009-07-18 15:28:16

标签: python django logging

我在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,则会产生问题。此外,它看起来不太“干”。

有人能建议更好的方法来解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

为什么不将这些语句放在settings.py的末尾并使用DEBUG flal es指标进行开发?

这样的事情:

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)

答案 1 :(得分:1)

找到合理的“DRY”解决方案。感谢Python logging in Django

我现在有一个看起来像这样的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'