go文件日志重构

【go文件日志重构】书史足自悦,安用勤与劬。这篇文章主要讲述go文件日志重构相关的知识,希望能为你提供帮助。
重定义go文件日志file.go

package loggingimport ( "fmt" "log" "os" "time" )var ( LogSavePath = "runtime/logs/" LogSaveName = "log" LogFileExt = "log" TimeFormat = "20060102" )func getLogFilePath() string { return fmt.Sprintf("%s",LogSavePath) } func getLogFileFullPath() string{ prefixPath := getLogFilePath() suffixPath := fmt.Sprintf("%s%s.%s",LogSaveName,time.Now().Format(TimeFormat),LogFileExt) return fmt.Sprintf("%s%s",prefixPath,suffixPath) } func mkDir(){ dir,_:=os.Getwd() err := os.MkdirAll(dir + "/" + getLogFilePath(),os.ModePerm) if err != nil { panic(err) } } func openLogFile(filePath string) *os.File{ _,err := os.Stat(filePath) switch{ case os.IsNotExist(err): mkDir() case os.IsPermission(err): log.Fatalf("Permission:% v",err)} handle, err := os.OpenFile(filePath,os.O_APPEND | os.O_CREATE | os.O_WRONLY,0644) if err != nil { log.Fatalf("fail to openfile :%v",err) } return handle}

log.go
package loggingimport ( "fmt" "log" "os" "path/filepath" "runtime" )type Level intvar ( 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 init(){ filePath := getLogFileFullPath() F = openLogFile(filePath) logger = log.New(F,DefaultPrefix,log.LstdFlags) } func Debug( v ...interface{}){ log.SetPrefix(string(DEBUG)) logger.Println(v) } func Info( v ...interface{}){ log.SetPrefix(string(INFO)) logger.Println(v) } func Warn( v ...interface{}){ log.SetPrefix(string(WARNING)) logger.Println(v) } func Error( v ...interface{}){ log.SetPrefix(string(ERROR)) logger.Println(v) } func Fatal( v ...interface{}){ log.SetPrefix(string(FATAL)) logger.Println(v) } func setPrefix(level Level) { _, file, line, ok := runtime.Caller(DefaultCallerDepth) if ok { logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line) } else { logPrefix = fmt.Sprintf("[%s]", levelFlags[level]) } logger.SetPrefix(logPrefix) }


    推荐阅读