如何在应用程序端记录Cassandra查询?

I'm using gocql driver in my application. Is there a way for the driver to log queries on the console? How do I configure the logger to print complete queries (along with data bindings)

package main

import (
    "fmt"

    "github.com/gocql/gocql"
)

var Session *gocql.Session

type Emp struct {
    id        string
    firstName string
    lastName  string
    age       int
}

func init() {
    var err error

    cluster := gocql.NewCluster("localhost")
    cluster.Keyspace = "cms"
    Session, err = cluster.CreateSession()
    if err != nil {
        panic(err)
    }
    fmt.Println("cassandra init done")
}

func main() {
    e := Emp{
        id:        "1",
        firstName: "John",
        lastName:  "DOe",
        age:       88,
    }
    createEmp(e)
}
func createEmp(emp Emp) {
    fmt.Println(" **** Creating new emp ****
", emp)
    if err := Session.Query("INSERT INTO emps(empid, first_name, last_name, age) VALUES(?, ?, ?, ?)",
        emp.id, emp.firstName, emp.lastName, emp.age).Exec(); err != nil {
        fmt.Println("Error while inserting Emp")
        fmt.Println(err)
    }
}

This is how we do it in Java. We define a custom LatencyTracker:

private LatencyTracker getLatencyTracker() {
    return new LatencyTracker() {
        @Override
        public void update(Host host, Statement statement, Exception e, long l) {
            LOGGER.info(statement.toString());
        }

        @Override
        public void onRegister(Cluster cluster1) {

        }

        @Override
        public void onUnregister(Cluster cluster1) {

        }
    };
}

Then register it in the cluster:

cluster.register(getLatencyTracker());

The go driver has a QueryObserver that you can implement to time queries: https://github.com/gocql/gocql/blob/master/session.go#L1891-L1926

It would be up to you check that the execution time breached a threshold and then printed as needed, but it looks like it gives you access to the statement object, host and timings which is all you need for debugging.

Here is some sample code that shows a QueryObserver in action in the context of timing the impact of speculative execution: https://github.com/instaclustr/sample-GoCql-Speculative-Execution/blob/master/spectest.go

The above example comes from the following blog post on speculative execution: https://www.instaclustr.com/speculative-query-executions-gocql/

(If you are having tail latency issues, you should probably consider using client-side speculative execution, but this is a different topic :)

Additionally, there is a test case in tree that uses a QueryObserver for verification: https://github.com/gocql/gocql/blob/16cf9ea1b3e28090d416d36528f304e4553e6b56/cassandra_test.go#L140

Might be a good place to start playing around with it.