-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
88 lines (72 loc) · 1.69 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
86
87
88
package log
import (
"fmt"
"io"
"os"
"time"
)
func (p *logFile) logDefault(level int, format string, args ...interface{}) {
w := p.flog
fmt.Fprintf(w, "%s %s ", time.Now().Local().Format(timeFormatDefault), levelNames[level])
fmt.Fprintf(w, format, args...)
fmt.Fprintf(w, "\n")
}
func (p *logFile) Fatalf(format string, args ...interface{}) {
if p.level >= LogLevelFatal {
p.log(LogLevelFatal, format, args...)
os.Exit(1)
}
}
func (p *logFile) Errorf(format string, args ...interface{}) {
if p.level >= LogLevelError {
p.log(LogLevelError, format, args...)
}
}
func (p *logFile) Infof(format string, args ...interface{}) {
if p.level >= LogLevelInfo {
p.log(LogLevelInfo, format, args...)
}
}
func (p *logFile) Debugf(format string, args ...interface{}) {
if p.level >= LogLevelDebug {
p.log(LogLevelDebug, format, args...)
}
}
func (p *logFile) Write(b []byte) (int, error) {
return p.flog.Write(b)
}
func (p *logFile) Close() error {
if p.flog != nil {
if p.flog != os.Stdout && p.flog != os.Stderr {
p.flog.Close()
}
p.flog = nil
}
return nil
}
func NewFile(name string, minLevel int) (l Log, err error) {
var flog *os.File
if flog, err = os.OpenFile(name, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666); err == nil {
l = newFile(minLevel, flog)
}
return
}
func NewStdout(minLevel int) Log {
return newFile(minLevel, os.Stdout)
}
func newFile(minLevel int, file io.WriteCloser) Log {
ret := &logFile{
logBase: logBase{level: minLevel},
flog: file,
}
ret.log = ret.logDefault
return ret
}
type logFile struct {
logBase
flog io.WriteCloser
log func(level int, format string, args ...interface{})
}
const (
timeFormatDefault = "2006-01-02 15:04:05"
)