-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
85 lines (67 loc) · 1.61 KB
/
file.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
package logy
import (
"io"
"os"
"path/filepath"
"sync/atomic"
)
type FileHandler struct {
commonHandler
name atomic.Value
path atomic.Value
underTest atomic.Value
}
func newFileHandler(underTest bool) *FileHandler {
handler := &FileHandler{}
handler.initializeHandler()
handler.SetEnabled(false)
handler.SetLevel(LevelInfo)
handler.setWriter(newSyncWriter(nil, true))
handler.underTest.Store(underTest)
return handler
}
func (h *FileHandler) setFileName(name string) {
h.name.Store(name)
}
func (h *FileHandler) FileName() string {
return h.name.Load().(string)
}
func (h *FileHandler) setFilePath(path string) {
h.path.Store(path)
}
func (h *FileHandler) FilePath() string {
return h.path.Load().(string)
}
func (h *FileHandler) createLogFile(dir, name string) (*os.File, error) {
path := filepath.FromSlash(filepath.Join(dir, name))
return os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0755)
}
func (h *FileHandler) OnConfigure(config Config) error {
h.SetEnabled(config.File.Enabled)
h.SetLevel(config.File.Level)
h.SetFormat(config.File.Format)
h.setFileName(config.File.Name)
h.setFilePath(config.File.Path)
underTest := h.underTest.Load().(bool)
var (
file io.Writer
err error
)
discarded := false
if !underTest {
file, err = h.createLogFile(config.File.Path, config.File.Name)
if err != nil {
h.SetEnabled(false)
discarded = true
}
} else {
discarded = true
}
fileWriter := h.writer.(*syncWriter)
defer fileWriter.mu.Unlock()
fileWriter.mu.Lock()
fileWriter.writer = file
fileWriter.setDiscarded(discarded)
h.applyJsonConfig(config.File.Json)
return err
}