jackc / pgx

PostgreSQL driver and toolkit for Go
MIT License
10.77k stars 837 forks source link

Access current request context from `Config.ConnConfig.OnNotice` #2122

Open anazcodes opened 1 month ago

anazcodes commented 1 month ago

Failed to get context.Context from Config.ConnConfig.OnNotice

I have implemented log tracing mechanism using a correlationID and I am accessing it everywhere to relate the logs.

Example

func (tracer *PGXQueryTracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
    log := logger.GetFromCtx(ctx)

    log.Trace().
        Str("Database Query Result", data.CommandTag.String()).
        Err(data.Err).
        Msg("Database Query ended")
}

The above example will log the executing query by attaching a common ID used for the all logs in the current request. BTW easily we can track all the steps happened in a particular request. `

Only the place I am not able to track the raise notice logging from the db using correlationID is this place, The reason for it is I didn't get a way to access the current request context that we are passing in every query from pgconn.PgConn.

Config.ConnConfig.OnNotice = func(pc *pgconn.PgConn, n *pgconn.Notice) {
                 log := logger.GetFromCtx(context.Background())     // doing this 

                // log := logger.GetFromCtx(ctx) // want to do this

                  log.Trace().
                    Uint32("pid", pc.PID()).
            Str("message", n.Message).
            Str("severity", n.Severity).
            Msg("Database notice")
    }

@jackc

jackc commented 1 month ago

This might be possible, but it also could be difficult and a significant change.

A notice could be received at any time. Not just while receiving query results. In addition, the notice may not have any connection to a query that happened to be executing at that time.

That's why it does not include a ctx now. However, it should be possible to store a currentCtx on *pgconn.PgConn`. This would have to be set and cleared by every method that potentially could receive a notice while it was executing.

I'm not opposed to this change, but it may be a fair amount of work, and it's not something I will get to anytime soon.


But as far as your immediate need, I think you can work around the issue by using https://pkg.go.dev/github.com/jackc/pgx/v5@v5.7.1/pgconn#PgConn.CustomData. You could use TraceQueryStart to set your current request context and TraceQueryEnd to clear it.