This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
file_logger.go
86 lines (76 loc) · 1.71 KB
/
file_logger.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
package loggers
import (
"bytes"
"fmt"
"os"
"text/template"
"time"
"github.com/go-kit/kit/log"
"github.com/hyperledger/burrow/logging/structure"
)
type FileLogger struct {
path string
file *os.File
formatName string
streamLogger log.Logger
}
type FileTemplateParams struct {
Date time.Time
}
func NewFileTemplateParams() *FileTemplateParams {
return &FileTemplateParams{
Date: time.Now(),
}
}
const timeFormat = "2006-01-02_15h04m05s"
func (ftp *FileTemplateParams) Timestamp() string {
return ftp.Date.Format(timeFormat)
}
func NewFileLogger(path string, formatName string) (*FileLogger, error) {
tmpl, err := template.New("file-logger").Parse(path)
if err != nil {
return nil, fmt.Errorf("could not parse path string '%s' as Go text/template: %v", path, err)
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, NewFileTemplateParams())
if err != nil {
return nil, err
}
fl := &FileLogger{
path: buf.String(),
formatName: formatName,
}
err = fl.Reload()
if err != nil {
return nil, err
}
return fl, nil
}
func (fl *FileLogger) Log(keyvals ...interface{}) error {
switch structure.Signal(keyvals) {
case structure.SyncSignal:
return fl.file.Sync()
case structure.ReloadSignal:
return fl.Reload()
default:
return fl.streamLogger.Log(keyvals...)
}
}
func (fl *FileLogger) Reload() error {
if fl.file != nil {
err := fl.file.Close()
if err != nil {
return fmt.Errorf("could not close file %v: %v", fl.file, err)
}
}
var err error
fl.file, err = os.OpenFile(fl.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
fl.streamLogger, err = NewStreamLogger(fl.file, fl.formatName)
if err != nil {
return err
}
return nil
}