This repository has been archived by the owner on Oct 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter_filehandle.go
113 lines (103 loc) · 2.5 KB
/
writer_filehandle.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
package log
import (
"encoding/json"
"fmt"
"io"
"strings"
"sync"
"time"
)
func newFileHandleWriter(fh io.Writer, format Format, lock *sync.Mutex) *fileHandleWriter {
return &fileHandleWriter{
fh: fh,
lock: lock,
format: format,
}
}
type fileHandleWriter struct {
lock *sync.Mutex
fh io.Writer
format Format
}
func (f *fileHandleWriter) Write(level Level, message Message) error {
f.lock.Lock()
defer f.lock.Unlock()
levelString, err := level.Name()
if err != nil {
return err
}
line, err := f.createLine(levelString, message)
if err != nil {
return Wrap(err, ELogWriteFailed, "failed to write log message")
}
if _, err := f.fh.Write(append(line, '\n')); err != nil {
return Wrap(err, ELogWriteFailed, "failed to write log message")
}
return nil
}
func (f *fileHandleWriter) Rotate() error {
return nil
}
func (f *fileHandleWriter) Close() error {
return nil
}
func (f *fileHandleWriter) createLine(levelString LevelString, message Message) (line []byte, err error) {
switch f.format {
case FormatLJSON:
line, err = f.createLineLJSON(levelString, message)
if err != nil {
return nil, err
}
case FormatText:
line = f.createLineText(levelString, message)
default:
return nil, fmt.Errorf("log format not supported: %s", f.format)
}
return line, nil
}
func (f *fileHandleWriter) createLineText(levelString LevelString, message Message) []byte {
msg := message.Explanation()
var labels []string
for labelName, labelValue := range message.Labels() {
labels = append(labels, fmt.Sprintf("%s=%s", labelName, labelValue))
}
if len(labels) > 0 {
msg += fmt.Sprintf(" (%s)", strings.Join(labels, " "))
}
line := []byte(fmt.Sprintf(
"%s\t%s\t%s\n",
time.Now().Format(time.RFC3339),
levelString,
msg,
))
return line
}
func (f *fileHandleWriter) createLineLJSON(levelString LevelString, message Message) (
[]byte,
error,
) {
details := map[string]interface{}{}
for label, value := range message.Labels() {
details[string(label)] = value
}
line, err := json.Marshal(
jsonLine{
Time: time.Now().Format(time.RFC3339),
Code: message.Code(),
Level: string(levelString),
Message: message.Explanation(),
Details: details,
},
)
if err != nil {
return nil, err
}
return line, nil
}
type jsonLine struct {
Time string `json:"timestamp"`
Level string `json:"level"`
Code string `json:"code"`
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
}