多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## log 语法 ``` type Logger func New(out io.Writer, prefix string, flag int) *Logger func (l *Logger) Flags() int func (l *Logger) SetFlags(flag int) func (l *Logger) Prefix() string func (l *Logger) SetPrefix(prefix string) func (l *Logger) Output(calldepth int, s string) error func (l *Logger) Printf(format string, v ...interface{}) func (l *Logger) Print(v ...interface{}) func (l *Logger) Println(v ...interface{}) func (l *Logger) Fatalf(format string, v ...interface{}) func (l *Logger) Fatal(v ...interface{}) func (l *Logger) Fatalln(v ...interface{}) func (l *Logger) Panic(v ...interface{}) func (l *Logger) Panicf(format string, v ...interface{}) func (l *Logger) Panicln(v ...interface{}) ``` ### 可以设置日志文件所在位置 当你调用第三方日志库时,可以通过设置 callpath来确定正确的位置 ``` var ( buf bytes.Buffer logger = log.New(&buf, "INFO: ", log.Lshortfile) // infof callpath 为堆栈层级 // callpath 代表的层级关系 // main ->demo1 ->demo2->demo3->info // 5 ->4 ->3 ->2 ->1 infof = func(info string) { logger.Output(2, info) } ) func demo1() { demo2() } func demo2() { demo3() } func demo3() { infof("Hello world") } func main() { demo1() fmt.Print(buf.String()) } ``` ### log.SetFlags ``` Ldate = 1 << iota Ltime Lmicroseconds Llongfile //显示觉得路径 Lshortfile // 显示文件名 LUTC LstdFlags = Ldate | Ltime // 显示日期加时间 ``` ``` log.SetFlags(log.Lshortfile | log.Ltime) log.Print("hello wrod") //13:45:38 test.go:16: hello wrod ``` ### log.SetPrefix ``` log.Print("hello world") // 2020/12/27 13:57:08 hello world log.SetPrefix("[debug]") log.Print("hello world") // [debug]2020/12/27 13:57:08 hello world ``` ### log.SetOutput 设置 Writer 重定向到文件 ``` f, err := os.Create("1.log") if err != nil { log.Fatal(err) } defer f.Close() log.Print("err1") log.SetOutput(f) log.Print("err2") log.Panic("err3") ```