File: text.go

package info (click to toggle)
golang-github-bep-logg 0.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 256 kB
  • sloc: makefile: 9
file content (50 lines) | stat: -rw-r--r-- 1,020 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Package text implements a development-friendly textual handler.
package text

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/bep/logg"
)

// Default handler outputting to stderr.
var Default = New(os.Stderr, Options{})

// Handler implementation.
type Handler struct {
	opts Options
	w    io.Writer
}

// Options holds options for the text handler.
type Options struct {
	// Separator is the separator between fields.
	// Default is " ".
	Separator string
}

// New handler.
func New(w io.Writer, opts Options) *Handler {
	if opts.Separator == "" {
		opts.Separator = " "
	}
	return &Handler{
		w:    w,
		opts: opts,
	}
}

// HandleLog implements logg.Handler.
func (h *Handler) HandleLog(e *logg.Entry) error {
	fields := make([]string, len(e.Fields))
	for i, f := range e.Fields {
		fields[i] = fmt.Sprintf("%s=%v", f.Name, f.Value)
	}

	fmt.Fprintf(h.w, "%s%s%s%s%s\n", strings.ToUpper(e.Level.String()), h.opts.Separator, e.Message, h.opts.Separator, strings.Join(fields, h.opts.Separator))

	return nil
}