-
Notifications
You must be signed in to change notification settings - Fork 0
/
logFile.go
203 lines (188 loc) · 5.13 KB
/
logFile.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
package logging
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const dateString = "06-01-02::03:04:05"
// is pointing to to file and carries all LogFile methods
type LogFile struct {
name string
path string
maxLines uint16 // max 65535 // with 100 chars per line 10 000 lines ~= 1mb // 0 ==> max
lines uint16
flag int
logger *log.Logger
currentFile string
}
// creates new file if necessary and returns new LogFile, if maxLines is 0, defaults to 65535
func New(name, path string, maxLines, flag int) (LogFile, error) {
if maxLines > math.MaxUint16 || maxLines == 0 {
maxLines = math.MaxUint16
}
l := LogFile{name: name, path: path, lines: 0, maxLines: uint16(maxLines), flag: flag}
err := l.new(1)
return l, err
}
// logs message like log.Println()
func (l *LogFile) Log(messages ...interface{}) {
s := fmt.Sprintln(messages...)
l.update(countLineEnds(s))
l.logger.Print(s)
}
// logs error like log.Println() with debug info about caller and caller's caller
func (l *LogFile) Error(messages ...interface{}) {
s := "error:\n"
s += debugInfo()
s += fmt.Sprintln(messages...)
l.update(countLineEnds(s))
l.logger.Print(s)
}
// initiates and logs panic like log.Panic() with debug info about caller and caller's caller
func (l *LogFile) Panic(messages ...interface{}) {
s := "PANIC:\n"
s += debugInfo()
s += fmt.Sprintln(messages...)
fmt.Println(s)
l.update(countLineEnds(s))
l.logger.Panic(s)
}
// calls and logs os.Exit like log.Fatal() with debug info about caller and caller's caller
func (l *LogFile) Fatal(messages ...interface{}) {
s := "FATAL:\n"
s += fmt.Sprintln(messages...)
s = debugInfo() + s
fmt.Println(s)
l.update(countLineEnds(s))
l.logger.Fatal(s)
}
// keeps logFile struct up to date
func (l *LogFile) update(n int) {
if n < 0 {
n = -n
}
l.lines += uint16(n)
if fileExists(l.currentFile) && l.lines < l.maxLines {
return
}
err := l.new(n)
if err != nil {
panic(err)
}
}
// scans target folder and either uses valid log file or creates new log file
func (l *LogFile) new(n int) error {
fis, err := ioutil.ReadDir(l.path)
if err != nil {
return err
}
for _, fi := range fis {
if strings.Contains(fi.Name(), l.name) {
if fi.IsDir() {
continue
}
f, err := os.Open(filepath.Join(l.path, fi.Name()))
if err != nil {
continue
}
lines, err := lineCounter(f)
if lines+n < int(l.maxLines) {
l.lines = uint16(lines)
l.currentFile = filepath.Join(l.path, fi.Name())
f, err := os.OpenFile(l.currentFile, os.O_APPEND|os.O_WRONLY, 0644)
l.logger = log.New(f, "", l.flag)
return err
}
err = f.Close()
if err != nil {
return err
}
}
}
l.currentFile = fmt.Sprint(l.name, time.Now().Format(dateString), ".log")
f, err := os.Create(filepath.Join(l.path, l.currentFile))
if err != nil {
return err
}
l.logger = log.New(f, "", l.flag)
l.Log("file started", time.Now().String())
l.update(1 + n)
return err
}
// counts lines of file, taken from:
// https://stackoverflow.com/questions/24562942/golang-how-do-i-determine-the-number-of-lines-in-a-file-efficiently
func lineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
func countLineEnds(s string) int {
count := 0
lineSep := []byte{'\n'}
count += bytes.Count([]byte(s), lineSep)
return count
}
// fileExists checks if a file exists and is not a directory
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// adds caller and caller's caller info to sting
func debugInfo() string {
var info string
caller := getFrame(2)
callersCaller := getFrame(3)
info += fmt.Sprintln("current:", cutSrcPath(caller.Function), cutSrcPath(caller.File), caller.Line)
info += fmt.Sprintln("caller:", cutSrcPath(callersCaller.Function), cutSrcPath(callersCaller.File), callersCaller.Line)
return info
}
// cuts all path before "src" like in ~/go/src/...
func cutSrcPath(s string) string {
cutset := string(filepath.Separator) + "src" + string(filepath.Separator) //src as is common in go
if strings.Contains(s, cutset) {
i := strings.Index(s, cutset)
return s[i+len(cutset):]
}
return s
}
// get frames of callers
func getFrame(skipFrames int) runtime.Frame {
// We need the frame at index skipFrames+2, since we never want runtime.Callers and getFrame
targetFrameIndex := skipFrames + 2
// Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need
programCounters := make([]uintptr, targetFrameIndex+2)
n := runtime.Callers(0, programCounters)
frame := runtime.Frame{Function: "unknown"}
if n > 0 {
frames := runtime.CallersFrames(programCounters[:n])
for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {
var frameCandidate runtime.Frame
frameCandidate, more = frames.Next()
if frameIndex == targetFrameIndex {
frame = frameCandidate
}
}
}
return frame
}