在 Go 專案建立客製化日誌模組

做法

新增一個 logger 檔,使用 log.New() 方法定義日誌處理器。

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
package logger

import (
"fmt"
"github.com/memochou1993/github-rankings/util"
"github.com/spf13/viper"
"log"
"os"
"reflect"
"strings"
"time"
)

// 宣告重複使用的日誌處理器
var (
infoLogger *log.Logger
successLogger *log.Logger
warningLogger *log.Logger
errorLogger *log.Logger
debugLogger *log.Logger
)

// 宣告不同的日誌處理器的前綴
const (
typeInfo = "INFO"
typeSuccess = "SUCCESS"
typeWarning = "WARNING"
typeError = "ERROR"
typeDebug = "DEBUG"
)

// 宣告不同的顏色
var (
blue = color("\033[1;34m%s\033[0m")
green = color("\033[1;32m%s\033[0m")
yellow = color("\033[1;33m%s\033[0m")
red = color("\033[1;31m%s\033[0m")
purple = color("\033[1;35m%s\033[0m")
)

func Init() {
// 使用當天日期做為檔名
name := fmt.Sprintf("./storage/logs/%s.txt", time.Now().Format("2006-01-02"))
file, err := os.OpenFile(name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}

// 初始化不同的日誌處理器
infoLogger = log.New(file, prefix(typeInfo), log.Ldate|log.Ltime)
successLogger = log.New(file, prefix(typeSuccess), log.Ldate|log.Ltime)
warningLogger = log.New(file, prefix(typeWarning), log.Ldate|log.Ltime)
errorLogger = log.New(file, prefix(typeError), log.Ldate|log.Ltime)
debugLogger = log.New(file, prefix(typeDebug), log.Ldate|log.Ltime)
}

func Info(v interface{}) {
infoLogger.Println(v)
log.Println(blue(prefix(typeInfo) + v))
}

func Success(v interface{}) {
successLogger.Println(v)
log.Println(green(prefix(typeSuccess) + v))
}

func Warning(v interface{}) {
warningLogger.Println(v)
log.Println(yellow(prefix(typeWarning) + v))
}

func Error(v interface{}) {
errorLogger.Println(v)
log.Println(red(prefix(typeError) + v))
}

func Debug(v interface{}) {
debugLogger.Println(v)
log.Println(purple(prefix(typeDebug) + v))
}

func prefix(prefix string) string {
return fmt.Sprintf("[%s.%s] ", strings.ToUpper(viper.GetString("APP_ENV")), prefix)
}

func color(color string) func(...interface{}) string {
return func(args ...interface{}) string {
return fmt.Sprintf(color, fmt.Sprint(args...))
}
}

使用如下:

1
2
3
4
5
logger.Info("Hello, World!")
logger.Success("Hello, World!")
logger.Warning("Hello, World!")
logger.Error("Hello, World!")
logger.Debug("Hello, World!")