我在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
,则会产生问题。此外,它看起来不太“干”。
有人能建议更好的方法来解决这个问题吗?
答案 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'