Logging

By default, embedded-postgres writes all logs from the PostgreSQL server process (both stdout and stderr) to os.Stdout.

You can customize this behavior by providing any io.Writer to the Logger configuration option.

Disabling Logs

To completely silence the output from PostgreSQL, you can use io.Discard (available in Go 1.16+) or ioutil.Discard for older versions.

import "io"

// Go 1.16+
config := DefaultConfig().Logger(io.Discard)

Writing Logs to a File

You can easily redirect logs to a file.

import (
    "log"
    "os"
)

func main() {
    logFile, err := os.Create("postgres.log")
    if err != nil {
        log.Fatal(err)
    }
    defer logFile.Close()

    config := DefaultConfig().Logger(logFile)
    postgres := NewDatabase(config)
    // ...
}

Integrating with a Structured Logger (zap)

For more advanced logging, you can integrate embedded-postgres with a structured logging library like zap. The examples directory demonstrates this using zapio, which provides an io.Writer interface for a zap.Logger.

Here is a complete example:

import (
    "testing"

    embeddedpostgres "github.com/fergusstrange/embedded-postgres"
    "go.uber.org/zap"
    "go.uber.org/zap/zapio"
)

func Test_WithZapLogger(t *testing.T) {
    // Create a zap logger
    logger, err := zap.NewProduction()
    if err != nil {
        t.Fatal(err)
    }

    // Create a writer that pipes to the logger
    writer := &zapio.Writer{Log: logger, Level: zap.InfoLevel}

    // Configure embedded-postgres to use this writer
    config := embeddedpostgres.DefaultConfig().Logger(writer)

    database := embeddedpostgres.NewDatabase(config)
    if err := database.Start(); err != nil {
        t.Fatal(err)
    }

    defer func() {
        if err := database.Stop(); err != nil {
            t.Fatal(err)
        }
    }()

    // Your test logic here...
    // All PostgreSQL server logs will now be processed by zap.
}

This approach allows you to capture PostgreSQL's output within your application's existing logging infrastructure, adding timestamps, log levels, and other structured context.