Django Development Logging HttpResponses to dev se

2019-07-16 17:54发布

I am creating an API using Django. Every view responds in JSON. I would like to log each HttpResponse JSON to the dev servers output.

So far I have added a handler:

 'console': {
        'level':'DEBUG',
        'class':'logging.StreamHandler',
 }   

and then added a logger:

'to_console': {
        'handlers': ['console'],
        'level': 'DEBUG',
    }   

In my view I get the logger logger = logging.getLogger('to_console')

and for each json response logger.debug(json_str)

For the first view this was fine. But I'm wondering is it possible to turn debug off when I deploy the app to production. It looks like https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.RequireDebugFalse could work. But then that leads my code littered with these logging statements. I have never needed to log somethign like this so I am wondering what the most maintainable way to handle it is.

What is the correct way to handle development logging so that it can be "turned-off" when code is on production? Or is there some sort of built in functionality or app that I am missing that automatically logs all HttpResponse's to the dev server?

1条回答
聊天终结者
2楼-- · 2019-07-16 18:18

Logging functionality can be turned off and on by varying the configuration you provide to logging. You might think of the logging statements as "littering" your code, but once the server's running in production, you have (in general) very few ways of knowing what's going on inside, other than logging.

If necessary, you can send a running server a POST with JSON data containing a new configuration, which then gets put into effect by the view handling the POST request. But it's advisable to leave the logging statements in place, as they are quite cheap when logging levels are such that nothing is actually output (as you might expect, the actual I/O of writing to console/file/socket etc. takes most of the time, but if levels are set high enough, little or nothing is actually output).

When everything runs fine in development and test but unaccountably fails in production, logging can sometimes be the only diagnostic tool available.

I think the use of RequireDebugFalse is quite reasonable for the scenario you describe, but you can also write your own filter which fits in more closely with your specific needs (writing Filters is quite easy to do).

查看更多
登录 后发表回答