记录MongoEngine生成的原始查询

Shi*_*pra 7 python django logging mongodb mongoengine

我需要在我的Django应用程序中记录MongoEngine生成的所有查询.

我无法使用,cursor._query()因为我需要记录所有MongoEngine文档的查询.

日志记录应该在应用程序级别而不是数据库级别完成,因此将MongoDB分析级别设置为2将无济于事.

我找到了这个要点,这似乎有帮助,但我不明白.

是否有更简单的方法来编写中间件或任何其他方式我可以记录所有查询.

Pet*_*ter 4

pymongo.monitoring在我的项目中使用过。

import logging
from pymongo import monitoring

class CommandLogger(monitoring.CommandListener):

    def started(self, event):
        log.debug("Command {0.command}".format(event))
        logging.info("Command {0.command_name} with request id "
                 "{0.request_id} started on server "
                 "{0.connection_id}".format(event))

    def succeeded(self, event):
        logging.info("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "succeeded in {0.duration_micros} "
                 "microseconds".format(event))

    def failed(self, event):
        logging.info("Command {0.command_name} with request id "
                 "{0.request_id} on server {0.connection_id} "
                 "failed in {0.duration_micros} "
                 "microseconds".format(event))

monitoring.register(CommandLogger())
Run Code Online (Sandbox Code Playgroud)

更详细的请看: