Logging from pgx

16 Apr 2021

One way to log SQL queries from pgx

type qLogger struct {
}

func (l *qLogger) Log(ctx context.Context, level pgx.LogLevel, msg string, data map[string]interface{}) {
  if level == pgx.LogLevelInfo && msg == "Query" {
    fmt.Printf("SQL:\n%s\nARGS:%v\n", data["sql"], data["args"])
  }
}

// somewhere in main, presumably...

  // For DSN format, see 33.1.1.2, "Connection URIs", of
  // https://www.postgresql.org/docs/current/libpq-connect.html
  dsn := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s", dbuser, pass, dbhost, dbport, dbname)

  config, err := pgx.ParseConfig(dsn)
  if err != nil {
    return nil, fmt.Errorf("Unable to parse configuration: %w", err)
  }
  config.Logger = &qLogger{}

  conn, err := pgx.ConnectConfig(ctx, config)
  if err != nil {
    return nil, fmt.Errorf("Unable to establish connection: %w", err)
  }