From fd1a75bc0a2a8346cdcd871c18570f74b5ffe403 Mon Sep 17 00:00:00 2001 From: zicla Date: Fri, 26 Apr 2019 01:26:37 +0800 Subject: [PATCH] Fix the file line number in logger. --- rest/logger.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/rest/logger.go b/rest/logger.go index c913d76..40974b0 100644 --- a/rest/logger.go +++ b/rest/logger.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "os" + "runtime" "sync" "time" ) @@ -28,14 +29,25 @@ type Logger struct { //处理日志的统一方法。 func (this *Logger) log(prefix string, format string, v ...interface{}) { - //控制台中打印日志 - var consoleFormat = fmt.Sprintf("%s%s %s\r\n", prefix, ConvertTimeToTimeString(time.Now()), format) - fmt.Printf(consoleFormat, v...) + content := fmt.Sprintf(format+"\r\n", v...) + + //控制台中打印日志,记录行号。 + _, file, line, ok := runtime.Caller(2) + if !ok { + file = "???" + line = 0 + } + + var consoleFormat = fmt.Sprintf("%s%s %s:%d %s", prefix, ConvertTimeToTimeString(time.Now()), GetFilenameOfPath(file), line, content) + fmt.Printf(consoleFormat) this.goLogger.SetPrefix(prefix) + //每一行我们加上换行符 - var fileFormat = fmt.Sprintf("%s\r\n", format) - this.goLogger.Printf(fileFormat, v...) + err := this.goLogger.Output(3, content) + if err != nil { + fmt.Printf("occur error while logging %s \r\n", err.Error()) + } } //处理日志的统一方法。