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

dad*_*yad 10 python cassandra cassandra-python-driver

我正试图找到一种方法来记录从python代码在Cassandra上完成的所有查询.特别是日志记录,因为他们使用a执行 BatchStatement

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

ffe*_*ast 5

2个选项:

  1. 依照 session.add_request_init_listener

    从源代码:

    一个) BoundStatement

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

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

    b) BatchStatement

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

    它存储用于构造此对象的所有语句和参数_statements_and_parameters.虽然它不是公共财产,但似乎可以获取它

    c)只调用此钩子,我没有设法找到任何其他钩子 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

    通过在Session.execute_async()中设置trace = True,可以为任何请求打开请求跟踪.通过等待将来查看结果,然后是ResponseFuture.get_query_trace()

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

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 
Run Code Online (Sandbox Code Playgroud)

它产生以下输出:

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'
Run Code Online (Sandbox Code Playgroud)