-
Notifications
You must be signed in to change notification settings - Fork 1
/
logging.go
101 lines (83 loc) · 1.88 KB
/
logging.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
package logging
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/glennsarti/blog-wasm-vscode/lsp/internal/pathtpl"
)
func NewLogger(w io.Writer) *log.Logger {
return log.New(w, "", log.LstdFlags|log.Lshortfile)
}
type fileLogger struct {
l *log.Logger
f *os.File
}
func NewFileLogger(rawPath string) (*fileLogger, error) {
path, err := parseLogPath(rawPath)
if err != nil {
return nil, fmt.Errorf("failed to parse path: %w", err)
}
if !filepath.IsAbs(path) {
return nil, fmt.Errorf("please provide absolute log path to prevent ambiguity (given: %q)",
path)
}
mode := os.O_TRUNC | os.O_CREATE | os.O_WRONLY
file, err := os.OpenFile(path, mode, 0600)
if err != nil {
return nil, err
}
return &fileLogger{
l: NewLogger(file),
f: file,
}, nil
}
func parseLogPath(rawPath string) (string, error) {
tpl, err := pathtpl.NewPath("log-file").Parse(rawPath)
if err != nil {
return "", err
}
buf := &strings.Builder{}
err = tpl.Execute(buf, nil)
if err != nil {
return "", err
}
return buf.String(), nil
}
func ValidateExecLogPath(rawPath string) error {
_, err := parseExecLogPathTemplate("", rawPath)
return err
}
func ParseExecLogPath(method string, rawPath string) (string, error) {
tpl, err := parseExecLogPathTemplate(method, rawPath)
if err != nil {
return "", err
}
buf := &strings.Builder{}
err = tpl.Execute(buf, nil)
if err != nil {
return "", err
}
return buf.String(), nil
}
func parseExecLogPathTemplate(method string, rawPath string) (pathtpl.TemplatedPath, error) {
tpl := pathtpl.NewPath("tf-log-file")
methodFunc := func() string {
return method
}
tpl = tpl.Funcs(template.FuncMap{
"method": methodFunc,
// DEPRECATED
"args": methodFunc,
})
return tpl.Parse(rawPath)
}
func (fl *fileLogger) Logger() *log.Logger {
return fl.l
}
func (fl *fileLogger) Close() error {
return fl.f.Close()
}