12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package logging
- import (
- "fmt"
- "log"
- "lttc-go-adm-znaf/pkg/file"
- "os"
- "path/filepath"
- "runtime"
- )
- type Level int
- var (
- F *os.File
- DefaultPrefix = ""
- DefaultCallerDepth = 2
- logger *log.Logger
- logPrefix = ""
- levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
- )
- const (
- DEBUG Level = iota
- INFO
- WARNING
- ERROR
- FATAL
- )
- // 初始化
- func Setup() {
- var err error
- filePath := getLogFilePath()
- fileName := getLogFileName()
- F, err := file.MustOpen(fileName, filePath)
- if err != nil {
- log.Fatalf("logging.Setup err: %v", err)
- }
- logger = log.New(F, DefaultPrefix, log.LstdFlags)
- }
- func setPrefix(level Level) {
- _, f, line, ok := runtime.Caller(DefaultCallerDepth)
- if ok {
- logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(f), line)
- } else {
- logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
- }
- logger.SetPrefix(logPrefix)
- }
- // debug 模式下输出日志
- func Debug(v ...interface{}) {
- setPrefix(DEBUG)
- logger.Println(v)
- }
- // Info 模式下输出日志
- func Info(v ...interface{}) {
- setPrefix(INFO)
- logger.Println(v)
- }
- // warning 模式下输出日志
- func Warn(v ...interface{}) {
- setPrefix(WARNING)
- logger.Println(v)
- }
- // Error 模式下输出日志
- func Error(v ...interface{}) {
- setPrefix(ERROR)
- logger.Println(v)
- }
- // Fatal 模式下输出日志
- func Fatal(v ...interface{}) {
- setPrefix(FATAL)
- logger.Println(v)
- }
|