Open Spaceman2019 opened 1 year ago
Hello.
The documentation is here https://pkg.go.dev/github.com/jackc/pgx/v5#hdr-Tracing_and_Logging Example of zap adapter:
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/tracelog"
"go.uber.org/zap"
zapadapter "github.com/jackc/pgx-zap"
)
func main() {
logger, err := zap.NewDevelopmentConfig().Build()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, fmt.Sprintf("failed to build logger %s", err))
os.Exit(1)
}
if err := app(context.Background(), logger); err != nil {
logger.Error("app failed", zap.Error(err))
os.Exit(1)
}
}
func app(ctx context.Context, logger *zap.Logger) error {
config, err := pgx.ParseConfig("postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable")
if err != nil {
return fmt.Errorf("failed to parse config %w", err)
}
config.Tracer = &tracelog.TraceLog{
Logger: zapadapter.NewLogger(logger),
LogLevel: tracelog.LogLevelTrace,
}
conn, err := pgx.ConnectConfig(ctx, config)
if err != nil {
return fmt.Errorf("unable to connection to database: %w", err)
}
rows, err := conn.Query(ctx, "SELECT * FROM generate_series (1,$1)", 5)
if err != nil {
return fmt.Errorf("failed to execute query %w", err)
}
res, err := pgx.CollectRows(rows, pgx.RowTo[int])
if err != nil {
return fmt.Errorf("failed to scan rows %w", err)
}
logger.Info("success", zap.Ints("data", res))
return nil
}
Output
2022-11-17T11:37:56.208+0700 INFO tracelog/tracelog.go:302 Connect {"host": "localhost", "port": 5432, "database": "postgres", "time": "11.546676ms", "pid": 47}
2022-11-17T11:37:56.211+0700 INFO tracelog/tracelog.go:302 Query {"time": "2.315614ms", "commandTag": "SELECT 5", "pid": 47, "sql": "SELECT * FROM generate_series (1,$1)", "args": [5]}
2022-11-17T11:37:56.211+0700 INFO log/main.go:51 success {"data": [1, 2, 3, 4, 5]}
@mcdoker18 The documentation you pointed at is very thin on details, but the example you wrote is great. It would be great if the documentation could provide something similar to this snippet:
config.Tracer = &tracelog.TraceLog{
Logger: zapadapter.NewLogger(logger),
LogLevel: tracelog.LogLevelTrace,
}
As well as pointers to https://pkg.go.dev/github.com/jackc/pgx/v5#readme-adapters-for-3rd-party-tracers and https://pkg.go.dev/github.com/jackc/pgx/v5#readme-adapters-for-3rd-party-loggers
One note to add to the above example, I think it's config.ConnConfig.Tracer
not config.Tracer
as far as the v5 *pgxpool.Config
type goes.
Hi, I use the v4 version together with the Zap Logger. Now I want to switch to version v5. For this version there is also an adapter for the Zap Logger. Unfortunately, I have not found a description / example of how I can link this adapter to the database connection. My question is: how can I connect the adapter? Thanks for help