| 1 |
// Package text implements a development-friendly textual handler. |
| 2 |
package text |
| 3 |
|
| 4 |
import ( |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"os" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"github.com/bep/logg" |
| 11 |
) |
| 12 |
|
| 13 |
// Default handler outputting to stderr. |
| 14 |
var Default = New(os.Stderr, Options{}) |
| 15 |
|
| 16 |
// Handler implementation. |
| 17 |
type Handler struct { |
| 18 |
opts Options |
| 19 |
w io.Writer |
| 20 |
} |
| 21 |
|
| 22 |
// Options holds options for the text handler. |
| 23 |
type Options struct { |
| 24 |
// Separator is the separator between fields. |
| 25 |
// Default is " ". |
| 26 |
Separator string |
| 27 |
} |
| 28 |
|
| 29 |
// New handler. |
| 30 |
func New(w io.Writer, opts Options) *Handler { |
| 31 |
if opts.Separator == "" { |
| 32 |
opts.Separator = " " |
| 33 |
} |
| 34 |
return &Handler{ |
| 35 |
w: w, |
| 36 |
opts: opts, |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// HandleLog implements logg.Handler. |
| 41 |
func (h *Handler) HandleLog(e *logg.Entry) error { |
| 42 |
fields := make([]string, len(e.Fields)) |
| 43 |
for i, f := range e.Fields { |
| 44 |
fields[i] = fmt.Sprintf("%s=%v", f.Name, f.Value) |
| 45 |
} |
| 46 |
|
| 47 |
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)) |
| 48 |
|
| 49 |
return nil |
| 50 |
} |