This repository has been archived by the owner on Jul 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_terminal.go
117 lines (91 loc) · 2.34 KB
/
backend_terminal.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Copyright (c) 2022 Exograd SAS.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package log
import (
"bytes"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
type TerminalBackendCfg struct {
Color bool `json:"color"`
DomainWidth int `json:"domain_width"`
}
type TerminalBackend struct {
Cfg TerminalBackendCfg
domainWidth int
}
func NewTerminalBackend(cfg TerminalBackendCfg) *TerminalBackend {
domainWidth := 24
if cfg.DomainWidth > 0 {
domainWidth = cfg.DomainWidth
}
b := &TerminalBackend{
Cfg: cfg,
domainWidth: domainWidth,
}
return b
}
func (b *TerminalBackend) Log(msg Message) {
domain := fmt.Sprintf("%-*s", b.domainWidth, msg.domain)
level := string(msg.Level)
if msg.Level == LevelDebug {
level += "." + strconv.Itoa(msg.DebugLevel)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "%-7s %s %s\n",
level, b.Colorize(ColorGreen, domain), msg.Message)
if len(msg.Data) > 0 {
fmt.Fprintf(&buf, " ")
keys := make([]string, len(msg.Data))
i := 0
for k := range msg.Data {
keys[i] = k
i++
}
sort.Strings(keys)
for i, k := range keys {
if i > 0 {
fmt.Fprintf(&buf, " ")
}
fmt.Fprintf(&buf, "%s=%s",
b.Colorize(ColorBlue, k), formatDatum(msg.Data[k]))
i++
}
fmt.Fprintf(&buf, "\n")
}
io.Copy(os.Stderr, &buf)
}
func (b *TerminalBackend) Colorize(color Color, s string) string {
if !b.Cfg.Color {
return s
}
return Colorize(color, s)
}
func formatDatum(datum Datum) string {
switch v := datum.(type) {
case fmt.Stringer:
return formatDatum(v.String())
case string:
if !strings.Contains(v, " ") {
return v
}
return fmt.Sprintf("%q", v)
default:
return fmt.Sprintf("%v", v)
}
}