Go标准库日志打印,以及同时输出到控制台和文件 | 您所在的位置:网站首页 › linux默认标准错误文件是什么格式的 › Go标准库日志打印,以及同时输出到控制台和文件 |
打印
在使用go写一些小程序时,我们没必要引入额外的包,直接使用fmt标准包打印即可: import "fmt" func main() { fmt.Println("line1") fmt.Print("line2") fmt.Printf("line%d \n", 3) str1 := fmt.Sprintln("hello", 3) str2 := fmt.Sprint("hello ", 1, " 2") str3 := fmt.Sprintf("hello %d", 1) fmt.Print(str1, str2, str3) } line1 line2line3 hello 3 hello 1 2hello 1那么,有些场景下,我们希望能同时打印到日志文件中要怎么办呢? log包标准库提供了log组件,用法和fmt一致,有3种方式: import “log" func main() { log.Println("line1") log.Print("line2") log.Printf("line%d \n", 3) }和fmt的区别就是多了时间: 2021/08/25 17:23:47 line1 2021/08/25 17:23:47 line2 2021/08/25 17:23:47 line3我们通过SetFlag函数,可以设置打印的格式: // For example, flags Ldate | Ltime (or LstdFlags) produce, // 2009/01/23 01:23:23 message // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce, // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message const ( Ldate = 1 |
CopyRight 2018-2019 实验室设备网 版权所有 |