| |
如何显示执行代码所在文件和行号?
使用go中的log.Println()
实现
实现在控制台和日志文件中打印日志?
使用log.SetOutput()
实现
package main
import (
"io"
"log"
"os"
"runtime"
"time"
)
type Logger struct{}
func main() {
logger := Logger{}
logger.Log()
}
// Logs the message to both console and log file.
func (c Logger) Log() {
// If logs.txt doesn't exist, it will be created.
file, err := os.OpenFile("./logs/logs_"+time.Now().Format("2006-01-02")+".txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.SetOutput(io.MultiWriter(file, os.Stdout)) // Sets the output to both file and console
log.Println("log is working!")
}
// Gets the name of the running function.
func (c Logger) runFuncName() string {
pc := make([]uintptr, 1)
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
return f.Name()
}
log包可以完成系统打印数据的详细输出
94 服务端 ↦ Go开发技巧 __ 110 字