forked from fluxio/logging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
text_writer.go
56 lines (48 loc) · 1.22 KB
/
text_writer.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
package logging
import (
"bytes"
"fmt"
"io"
"path/filepath"
"sync"
"time"
"github.com/fluxio/iohelpers/line"
)
// If long lines wrap multiple lines, use this prefix for each continuation line
const continuation = " "
type TextWriter struct {
Writer io.Writer
mutex sync.Mutex
}
func (t *TextWriter) fmtTimestamp(ts time.Time) string { return ts.Format("0102 15:04:05.000Z0700") }
func (t *TextWriter) fmtOrigin(file string, line int) string {
if file == "" {
file = "???"
} else {
file = filepath.Base(file)
}
if line == -1 {
return file
}
return fmt.Sprintf("%s:%d", file, line)
}
func (t *TextWriter) Write(e Entry) error {
// First we construct an in-memory string of the of entry. This
// can be done in parallel for all calling threads.
var buf bytes.Buffer
w := line.PrefixWriter{&buf, []byte(continuation), true}
// Prefix
fmt.Fprintf(&w, "%s%s %s (%s): ", e.Level, t.fmtTimestamp(e.Time),
t.fmtOrigin(e.File, e.Line), e.Context)
// Content
if e.Fmt == kNO_FORMAT {
fmt.Fprintln(&w, e.Args...)
} else {
fmt.Fprintf(&w, e.Fmt+"\n", e.Args...)
}
// Then we lock and write to the final output writer in one go.
t.mutex.Lock()
_, err := buf.WriteTo(t.Writer)
t.mutex.Unlock()
return err
}