-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathltsvlog.go
108 lines (92 loc) · 1.68 KB
/
ltsvlog.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
// Copyright 2017 Shunsuke Michii. All rights reserved.
package ltsvlog
import (
"bytes"
"encoding"
"fmt"
"io"
"os"
"strconv"
"sync"
ltsv "github.com/Songmu/go-ltsv"
)
type Field struct {
Key string
Value interface{}
}
func F(key string, value interface{}) Field {
return Field{key, value}
}
const (
format1 = "%s:%s"
format2 = "\t%s:%s"
delim = "\n"
)
type Logger struct {
m sync.Mutex
w io.Writer
}
func (l *Logger) Logf(fields ...Field) {
buf := bytes.NewBuffer(nil)
fmt.Fprintf(buf, format1, fields[0].Key, l.format(fields[0].Value))
for _, f := range fields[1:] {
fmt.Fprintf(buf, format2, f.Key, l.format(f.Value))
}
fmt.Fprintf(buf, delim)
l.m.Lock()
defer l.m.Unlock()
buf.WriteTo(l.w)
}
func (l *Logger) Log(v interface{}) {
buf := bytes.NewBuffer(nil)
ltsv.MarshalTo(buf, v)
fmt.Fprintf(buf, delim)
l.m.Lock()
defer l.m.Unlock()
buf.WriteTo(l.w)
}
func (l *Logger) format(v interface{}) string {
var s string
switch v := v.(type) {
case string:
s = v
case encoding.TextMarshaler:
b, err := v.MarshalText()
if err != nil {
// TODO: handling error
return "(failed to marshal)"
}
s = string(b)
default:
s = fmt.Sprint(v)
}
if needQuote(s) {
s = strconv.Quote(s)
}
return s
}
func needQuote(s string) bool {
for _, c := range s {
if !(0x21 <= c && c <= 0x7f && c != '"' && c != '\\') {
return true
}
}
return false
}
func (l *Logger) SetOutput(w io.Writer) {
l.m.Lock()
defer l.m.Unlock()
l.w = w
}
var DefaultLogger = &Logger{
w: os.Stdout,
}
func Log(v interface{}) {
DefaultLogger.Log(v)
}
func Logf(fields ...Field) {
DefaultLogger.Logf(fields...)
}
func SetOutput(w io.Writer) {
DefaultLogger.SetOutput(w)
}