-
Notifications
You must be signed in to change notification settings - Fork 22
/
logger.go
92 lines (80 loc) · 2.19 KB
/
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
87
88
89
90
91
92
package task
import (
"fmt"
"os"
"syscall"
"time"
)
const (
defaultDateFormatForFileName = "2006_01_02"
defaultDateLayout = "2006-01-02"
defaultFullTimeLayout = "2006-01-02 15:04:05.999999"
)
type (
Logger interface {
Error(err error, v interface{})
Warn(v interface{})
Info(v interface{})
Debug(v interface{})
}
fileLogger struct {
filePath string
}
fmtLogger struct{}
)
/************************* FmtLogger *******************************/
func NewFmtLogger() *fmtLogger {
return &fmtLogger{}
}
func (logger *fmtLogger) Debug(v interface{}) {
logger.writeLog(fmt.Sprint(v), "debug")
}
func (logger *fmtLogger) Info(v interface{}) {
logger.writeLog(fmt.Sprint(v), "info")
}
func (logger *fmtLogger) Warn(v interface{}) {
logger.writeLog(fmt.Sprint(v), "warn")
}
func (logger *fmtLogger) Error(err error, v interface{}) {
logger.writeLog(fmt.Sprint(v, err), "error")
}
func (logger *fmtLogger) writeLog(log string, level string) {
logStr := time.Now().Format(defaultFullTimeLayout) + " " + log
fmt.Println(logStr)
}
/************************* FileLogger *******************************/
func NewFileLogger(filePath string) *fileLogger {
if filePath == "" || !fileExists(filePath) {
filePath = getCurrentDirectory()
}
logger := &fileLogger{filePath: filePath}
return logger
}
func (logger *fileLogger) Debug(v interface{}) {
logger.writeLog(fmt.Sprint(v), "debug")
}
func (logger *fileLogger) Info(v interface{}) {
logger.writeLog(fmt.Sprint(v), "info")
}
func (logger *fileLogger) Warn(v interface{}) {
logger.writeLog(fmt.Sprint(v), "warn")
}
func (logger *fileLogger) Error(err error, v interface{}) {
logger.writeLog(fmt.Sprint(v, err), "error")
}
func (logger *fileLogger) writeLog(log string, level string) {
filePath := logger.filePath + "dottask_" + level
filePath += "_" + time.Now().Format(defaultDateFormatForFileName) + ".log"
logStr := time.Now().Format(defaultFullTimeLayout) + " " + log
logStr += "\r\n"
var mode os.FileMode
flag := syscall.O_RDWR | syscall.O_APPEND | syscall.O_CREAT
mode = 0666
file, err := os.OpenFile(filePath, flag, mode)
defer file.Close()
if err != nil {
fmt.Println(filePath, err)
return
}
file.WriteString(logStr)
}