-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutput.go
147 lines (120 loc) · 2.43 KB
/
output.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package vlog
import (
"fmt"
"os"
"path"
"strings"
"time"
)
type LogFormat int
const (
LogFormatText = iota
LogFormatJson
LogFormatColoredText
)
type Output interface {
print(line *Line)
printRaw(line string)
open() error
close() error
}
func WithOutputStd() func(l *Logger) {
return func(l *Logger) {
*l.outputs = append(*l.outputs, OutputStd{
stdout: os.Stdout,
stderr: os.Stderr,
})
}
}
func WithOutputFunc(format LogFormat, fc func(line string)) func(l *Logger) {
return func(l *Logger) {
*l.outputs = append(*l.outputs, &OutputFunc{
format: format,
fc: fc,
})
}
}
func WithOutputFile(format LogFormat, dir string) func(l *Logger) {
return func(l *Logger) {
output := &OutputFile{
dir: dir,
format: format,
}
switch format {
case LogFormatText:
output.ext = ".txt"
case LogFormatJson:
output.ext = ".jsonl"
default:
output.ext = ".txt"
}
err := output.open()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to open log file: %v\n", err)
return
}
*l.outputs = append(*l.outputs, output)
}
}
type OutputFile struct {
dir string
ext string
format LogFormat
file *os.File
}
func (out *OutputFile) print(l *Line) {
out.printRaw(l.ToFormat(out.format))
}
func (out *OutputFile) printRaw(line string) {
_, _ = fmt.Fprintln(out.file, line)
}
func (out *OutputFile) open() error {
err := os.MkdirAll(out.dir, os.ModePerm)
if err != nil && !os.IsExist(err) {
return err
}
filename := fmt.Sprintf("vertex_logs_%s%s", time.Now().Format(time.DateOnly), out.ext)
out.file, err = os.OpenFile(path.Join(out.dir, filename), os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
return err
}
func (out *OutputFile) close() error {
return out.file.Close()
}
type OutputStd struct {
stdout *os.File
stderr *os.File
}
func (o OutputStd) print(l *Line) {
o.printRaw(l.ToColoredText())
}
func (o OutputStd) printRaw(line string) {
var file *os.File
if strings.Contains(line, "ERR") {
file = o.stderr
} else {
file = o.stdout
}
_, _ = fmt.Fprintln(file, line)
}
func (o OutputStd) open() error {
return nil
}
func (o OutputStd) close() error {
return nil
}
type OutputFunc struct {
format LogFormat
fc func(line string)
}
func (o *OutputFunc) print(l *Line) {
o.printRaw(l.ToFormat(o.format))
}
func (o *OutputFunc) printRaw(line string) {
o.fc(line)
}
func (o *OutputFunc) open() error {
return nil
}
func (o *OutputFunc) close() error {
return nil
}