-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_receiver.go
228 lines (191 loc) · 5.23 KB
/
file_receiver.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright (c) Jeevanandam M (https://github.com/jeevatkm)
// go-aah/log source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"time"
"aahframework.org/config.v0"
"aahframework.org/essentials.v0"
)
const defaultRotatePolicy = "daily"
var (
// backupTimeFormat is used for timestamp with filename on rotation
backupTimeFormat = "2006-01-02-15-04-05.000"
_ Receiver = (*FileReceiver)(nil)
)
// FileReceiver writes the log entry into file.
type FileReceiver struct {
filename string
out io.Writer
formatter string
flags []ess.FmtFlagPart
isCallerInfo bool
stats *receiverStats
mu sync.Mutex
isClosed bool
rotatePolicy string
openDay int
isUTC bool
maxSize int64
maxLines int64
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// FileReceiver methods
//___________________________________
// Init method initializes the file receiver instance.
func (f *FileReceiver) Init(cfg *config.Config) error {
// File
f.filename = cfg.StringDefault("log.file", "")
if err := f.openFile(); err != nil {
return err
}
f.formatter = cfg.StringDefault("log.format", "text")
if !(f.formatter == textFmt || f.formatter == jsonFmt) {
return fmt.Errorf("log: unsupported format '%s'", f.formatter)
}
if policy, found := cfg.String("log.rotate.mode"); found {
f.rotatePolicy = policy
if ess.IsStrEmpty(f.rotatePolicy) {
f.rotatePolicy = defaultRotatePolicy
}
// DEPRECATED, to be removed in v1.0
Warnf("DEPRECATED: Config 'log.rotate.mode' is deprecated in v0.7, use 'log.rotate.policy = \"%s\"' instead. Deprecated config will not break your functionality, its good to update to latest config.", f.rotatePolicy)
} else {
f.rotatePolicy = cfg.StringDefault("log.rotate.policy", defaultRotatePolicy)
}
switch f.rotatePolicy {
case defaultRotatePolicy:
f.openDay = f.getDay()
case "lines":
f.maxLines = int64(cfg.IntDefault("log.rotate.lines", 0))
case "size":
maxSize, err := ess.StrToBytes(cfg.StringDefault("log.rotate.size", "512mb"))
if err != nil {
return err
}
f.maxSize = maxSize
}
f.mu = sync.Mutex{}
return nil
}
// SetPattern method initializes the logger format pattern.
func (f *FileReceiver) SetPattern(pattern string) error {
flags, err := ess.ParseFmtFlag(pattern, FmtFlags)
if err != nil {
return err
}
f.flags = flags
if f.formatter == textFmt {
f.isCallerInfo = isCallerInfo(f.flags)
}
f.isUTC = isFmtFlagExists(f.flags, FmtFlagUTCTime)
f.openDay = f.getDay()
return nil
}
// SetWriter method sets the given writer into file receiver.
func (f *FileReceiver) SetWriter(w io.Writer) {
f.out = w
}
// IsCallerInfo method returns true if log receiver is configured with caller info
// otherwise false.
func (f *FileReceiver) IsCallerInfo() bool {
return f.isCallerInfo
}
// Log method logs the given entry values into file.
func (f *FileReceiver) Log(entry *Entry) {
f.mu.Lock()
defer f.mu.Unlock()
if f.isRotate() {
_ = f.rotateFile()
// reset rotation values
f.openDay = f.getDay()
f.stats.lines = 0
f.stats.bytes = 0
}
var msg []byte
if f.formatter == textFmt {
msg = textFormatter(f.flags, entry)
} else {
msg, _ = json.Marshal(entry)
msg = append(msg, '\n')
}
size, _ := f.out.Write(msg)
// calculate receiver stats
f.stats.bytes += int64(size)
f.stats.lines++
}
// Writer method returns the current log writer.
func (f *FileReceiver) Writer() io.Writer {
return f.out
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// FileReceiver Unexported methods
//___________________________________
func (f *FileReceiver) isRotate() bool {
switch f.rotatePolicy {
case "daily":
return f.openDay != f.getDay()
case "lines":
return f.maxLines != 0 && f.stats.lines >= f.maxLines
case "size":
return f.maxSize != 0 && f.stats.bytes >= f.maxSize
default:
return false
}
}
func (f *FileReceiver) rotateFile() error {
if _, err := os.Lstat(f.filename); err == nil {
f.close()
if err = os.Rename(f.filename, f.backupFileName()); err != nil {
return err
}
}
return f.openFile()
}
func (f *FileReceiver) openFile() error {
dir := filepath.Dir(f.filename)
_ = ess.MkDirAll(dir, filePermission)
file, err := os.OpenFile(f.filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, filePermission)
if err != nil {
return err
}
fileStat, err := file.Stat()
if err != nil {
return err
}
f.SetWriter(file)
f.isClosed = false
f.stats = &receiverStats{}
f.stats.bytes = fileStat.Size()
f.stats.lines = int64(ess.LineCntr(file))
return nil
}
func (f *FileReceiver) close() {
if !f.isClosed {
ess.CloseQuietly(f.out)
f.isClosed = true
}
}
func (f *FileReceiver) backupFileName() string {
dir := filepath.Dir(f.filename)
fileName := filepath.Base(f.filename)
ext := filepath.Ext(fileName)
baseName := ess.StripExt(fileName)
t := time.Now()
if f.isUTC {
t = t.UTC()
}
return filepath.Join(dir, fmt.Sprintf("%s-%s%s", baseName, t.Format(backupTimeFormat), ext))
}
func (f *FileReceiver) getDay() int {
if f.isUTC {
return time.Now().UTC().Day()
}
return time.Now().Day()
}