Skip to content

Instantly share code, notes, and snippets.

@lzap
Created September 23, 2022 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lzap/d6e6cc619170d0cddeb57fc502fd0791 to your computer and use it in GitHub Desktop.
Save lzap/d6e6cc619170d0cddeb57fc502fd0791 to your computer and use it in GitHub Desktop.
OpenTelemetry provisioning patch for pgx/v5
Index: internal/db/connection.go
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/internal/db/connection.go b/internal/db/connection.go
--- a/internal/db/connection.go (revision c976e66ddccd4ba8ed8cb5e7e82686161aa305cb)
+++ b/internal/db/connection.go (date 1663920062746)
@@ -1,15 +1,20 @@
package db
import (
+ "context"
"fmt"
"net/url"
"github.com/RHEnVision/provisioning-backend/internal/config"
- "github.com/jackc/pgx/v4"
- "github.com/jackc/pgx/v4/log/zerologadapter"
- "github.com/jackc/pgx/v4/stdlib"
+ "github.com/RHEnVision/provisioning-backend/internal/ctxval"
+ "github.com/exaring/otelpgx"
+ zerologadapter "github.com/jackc/pgx-zerolog"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/stdlib"
+ "github.com/jackc/pgx/v5/tracelog"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
+ "github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
@@ -49,9 +54,26 @@
if err != nil {
return errors.Wrap(err, "unable to parse database configuration")
}
- if config.Database.LogLevel > 0 {
- connConfig.Logger = zerologadapter.NewLogger(log.Logger)
- connConfig.LogLevel = pgx.LogLevel(config.Database.LogLevel)
+ if config.Telemetry.Enabled {
+ connConfig.Tracer = otelpgx.NewTracer()
+ } else {
+ logLevel, err := tracelog.LogLevelFromString(config.Database.LogLevel)
+ if err != nil {
+ errors.Wrap(err, "unknown database log level config option")
+ }
+ if logLevel > 0 {
+ zeroLogger := zerologadapter.NewLogger(log.Logger,
+ zerologadapter.WithContextFunc(func(ctx context.Context, logWith zerolog.Context) zerolog.Context {
+ traceId := ctxval.TraceId(ctx)
+ accountId := ctxval.AccountId(ctx)
+ logWith.Str("trace_id", traceId).Int64("account_id", accountId)
+ return logWith
+ }))
+ connConfig.Tracer = &tracelog.TraceLog{
+ Logger: zeroLogger,
+ LogLevel: logLevel,
+ }
+ }
}
connStrRegistered := stdlib.RegisterConnConfig(connConfig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment