Skip to content

Commit

Permalink
Add logger func wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
ubiuser authored and jackc committed Jun 24, 2022
1 parent a814153 commit 3961954
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
33 changes: 33 additions & 0 deletions conn_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package pgx_test

import (
"bytes"
"context"
"log"
"os"
"strings"
"sync"
Expand Down Expand Up @@ -837,6 +839,37 @@ func TestLogPassesContext(t *testing.T) {
}
}

func TestLoggerFunc(t *testing.T) {
t.Parallel()

const testMsg = "foo"

buf := bytes.Buffer{}
logger := log.New(&buf, "", 0)

createAdapterFn := func(logger *log.Logger) pgx.LoggerFunc {
return func(ctx context.Context, level pgx.LogLevel, msg string, data map[string]interface{}) {
logger.Printf("%s", testMsg)
}
}

config := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE"))
config.Logger = createAdapterFn(logger)

conn := mustConnect(t, config)
defer closeConn(t, conn)

buf.Reset() // Clear logs written when establishing connection

if _, err := conn.Exec(context.TODO(), ";"); err != nil {
t.Fatal(err)
}

if strings.TrimSpace(buf.String()) != testMsg {
t.Errorf("Expected logger function to return '%s', but it was '%s'", testMsg, buf.String())
}
}

func TestIdentifierSanitize(t *testing.T) {
t.Parallel()

Expand Down
8 changes: 8 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ type Logger interface {
Log(ctx context.Context, level LogLevel, msg string, data map[string]interface{})
}

// LoggerFunc is a wrapper around a function to satisfy the pgx.Logger interface
type LoggerFunc func(ctx context.Context, level LogLevel, msg string, data map[string]interface{})

// Log delegates the logging request to the wrapped function
func (f LoggerFunc) Log(ctx context.Context, level LogLevel, msg string, data map[string]interface{}) {
f(ctx, level, msg, data)
}

// LogLevelFromString converts log level string to constant
//
// Valid levels:
Expand Down

0 comments on commit 3961954

Please sign in to comment.