Django使用多个处理程序记录命令和视图,具有共享功能

时间:2014-09-07 08:33:08

标签: python django logging

是否可以将命令和视图记录到单独的日志文件中,同时使用从命令和视图调用的常用函数?将记录器作为函数参数传递肯定不是一个好的设计。

settings.py

'loggers': {
    'Web': {
        'handlers': ['logfile_website'], # -> views.log
    'Commands': {
        'handlers': ['logfile_commands'], # -> commands.log
}

views.py - >转到 views.log

log = logging.getLogger('Web')
def index(request):
    log.info('In view')
    my_common.common_function(1)

command.py - >转到 commands.log

log = logging.getLogger('Commands')
class Command(BaseCommand):
    def handle(self, *args, **options):
        log.info('In command')
        my_common.common_function(2)

my_common.py - >根据来电者

前往需要的地方
def common_function(param):
    log = How to get logger based on current call stack?
    log.info('In common function')

1 个答案:

答案 0 :(得分:0)

您可以使用单个处理程序,该处理程序根据环境使用文件名。例如,在POSIX上,

LOG_FILENAME = os.environ.get('LOGFILE', 'views.log')

# then use the filename in your configuration

然后使用

运行命令
LOGFILE=commands.log python manage.py syncdb

我使用syncdb作为命令的一个示例。

相关问题