go中實現簡單日誌功能

語言: CN / TW / HK

1.定義日誌對象

package mylogger

import (
	"errors"
	"fmt"
	"path"
	"runtime"
	"strings"
)

type LOGLEVEL int32

const (
	UNKNOW LOGLEVEL = iota
	DEBUG
	TRACE
	INFO
	WARNING
	ERROR
	FATAL
)

type Logger struct {
	Level LOGLEVEL
}

func parseLevel(s string) (LOGLEVEL, error) {
	s = strings.ToLower(s)
	switch s {
	case "debug":
		return DEBUG, nil
	case "trace":
		return TRACE, nil
	case "info":
		return INFO, nil
	case "warning":
		return WARNING, nil
	case "error":
		return ERROR, nil
	case "FATAL":
		return FATAL, nil
	default:
		err := errors.New("錯誤是的日誌級別")
		return UNKNOW, err

	}
}

func getLogLevelString(l LOGLEVEL) string {
	switch l {
	case DEBUG:
		return "DEBUG"
	case INFO:
		return "INFO"
	case TRACE:
		return "TRACE"
	case ERROR:
		return "ERROR"
	default:
		return ""
	}
}
func NewLog(levelStr string) Logger {
	level, err := parseLevel(levelStr)
	if err != nil {
		panic(err)
	}
	return Logger{
		Level: level,
	}

}

//獲取運行時信息
func getInfo(n int) (funcName, fileName string, lineNo int) {
	pc, file, line, ok := runtime.Caller(n)
	if !ok {
		fmt.Println("runtime caller error ! ")
		return
	}
	funcName = runtime.FuncForPC(pc).Name()
	fileName = path.Base(file)
	funcName = strings.Split(funcName, ".")[1]
	return funcName, fileName, line
}

2. 根據日誌級別向控制枱打印日誌

package mylogger

import (
	"fmt"
	"time"
)

func (l Logger) enable(level LOGLEVEL) bool {
	return level >= l.Level
}

func log(level LOGLEVEL, msg string) {
	now := time.Now()
	funcName, fileName, lineNo := getInfo(3)
	fmt.Printf("[%s] [%s] [%s:%s:%d] %s \n ", now.Format("2006-01-02 15:04:05"), getLogLevelString(level), fileName, funcName, lineNo, msg)
}

func (l Logger) Info(msg string) {
	if l.enable(INFO) {
		log(INFO, msg)
	}
}
func (l Logger) Trace(msg string) {
	if l.enable(TRACE) {
		log(TRACE, msg)
	}
}
func (l Logger) Error(msg string) {
	if l.enable(ERROR) {
		log(ERROR, msg)
	}
}
func (l Logger) Debug(msg string) {
	if l.enable(DEBUG) {
		log(DEBUG, msg)
	}
}