formatter.go 985 Bytes
Newer Older
package log

import (
	"fmt"
	"strings"
	"time"
)

// A Formatter formats an entry.
type Formatter interface {
	Format(*Entry) ([]byte, error)
}

// A FormatterFunc implements Formatter using a single function.
type FormatterFunc func(*Entry) ([]byte, error)

// Format implements Formatter.
func (f FormatterFunc) Format(entry *Entry) ([]byte, error) { return f(entry) }

// TextFormatter formats an entry as one-line text.
var TextFormatter = FormatterFunc(func(entry *Entry) (output []byte, err error) {
	var builder strings.Builder

	if _, err = fmt.Fprintf(
		&builder,
		"%s %s [%s]: %s",
		entry.Time.Format(time.RFC3339),
		entry.Category,
		entry.Level,
		entry.Message,
	); err != nil {
		return
	}

	entry.Fields.ForEach(func(name string, value interface{}) bool {
		_, err = fmt.Fprintf(&builder, " %s=%v", name, value)
		return err == nil
	})
	if err != nil {
		return
	}

	if err = builder.WriteByte('\n'); err == nil {
		output = []byte(builder.String())
	}

	return
})