python - 使用 cassandra-python-driver 记录所有查询

标签 python cassandra cassandra-python-driver

我试图找到一种方法来记录从 python 代码在 Cassandra 上完成的所有查询。使用 BatchStatement

执行时专门记录日志

我可以使用任何钩子(Hook)或回调来记录这个吗?

最佳答案

2个选项:

  1. 坚持session.add_request_init_listener

    来自源代码:

    a) 绑定(bind)语句

    https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L560

    传递的值存储在raw_values中,你可以尝试提取它

    b) 批处理语句

    https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L676

    它将用于构造该对象的所有语句和参数存储在_statements_and_parameters中。 虽然它不是公共(public)属性(property),但似乎可以获取它

    c) 只有这个钩子(Hook)被调用了,我没有设法找到任何其他钩子(Hook) https://github.com/datastax/python-driver/blob/master/cassandra/cluster.py#L2097

    但它与查询的实际执行无关——它只是一种检查构造了何种查询并可能添加额外回调/错误反馈的方法

  2. 从不同的角度接近它并使用痕迹

    https://datastax.github.io/python-driver/faq.html#how-do-i-trace-a-request https://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResponseFuture.get_all_query_traces

    Request tracing can be turned on for any request by setting trace=True in Session.execute_async(). View the results by waiting on the future, then ResponseFuture.get_query_trace()

这是使用选项 2 进行跟踪的 BatchStatement 示例:

bs = BatchStatement()                                                        
bs.add_all(['insert into test.test(test_type, test_desc) values (%s, %s)',   
            'insert into test.test(test_type, test_desc) values (%s, %s)',   
            'delete from test.test where test_type=%s',
            'update test.test set test_desc=%s where test_type=%s'],
           [['hello1', 'hello1'],                                            
            ['hello2', 'hello2'],                                            
            ['hello2'],
            ['hello100', 'hello1']])     
res = session.execute(bs, trace=True)                                        
trace = res.get_query_trace()                                                
for event in trace.events:                                                   
    if event.description.startswith('Parsing'):                              
        print event.description 

它产生以下输出:

Parsing insert into test.test(test_type, test_desc) values ('hello1', 'hello1')
Parsing insert into test.test(test_type, test_desc) values ('hello2', 'hello2')
Parsing delete from test.test where test_type='hello2'
Parsing update test.test set test_desc='hello100' where test_type='hello1'

关于python - 使用 cassandra-python-driver 记录所有查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773522/

相关文章:

python - 如何使用 Huey 创建带有参数的任务函数?

python - 区分 WSGI 应用程序中的调试环境和生产环境

configuration - 为什么在 Cassandra 2.1.8 配置中禁用 commitlog_total_space_in_mb

Cassandra 复合主键 CQL3

python - 如何从 python cassandra 驱动程序传递 cassandra 函数?

python - 如何将numpy数组中的元素随机设置为0

python - 池模块和漂亮的汤出现奇怪的错误 : Invalid URL 'h'

cassandra - 关闭 Cassandra 服务器,然后在 Windows 7 中重新启动它

kubernetes - Cassandra群集连接每两次使用NoHostAvailable失败

python - 如何使用 cassandra python-driver 实现基于 token 的分页?