golang 日志

佐手、 提交于 2019-12-02 11:10:44
  • log库利用全局变量std来调用标准日志命令
  • 可以根据需要创建自己的日志变量
    • 通过New函数
//log.go in package log

// 每种格式占据一个bit,所以可以通过|设置格式
const (
	Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)


// 日志变量类型
// 互斥锁保证多个goroutine的线程安全
type Logger struct {
	mu     sync.Mutex // ensures atomic writes; protects the following fields
	prefix string     // prefix to write at beginning of each line
	flag   int        // properties
	out    io.Writer  // destination for output
	buf    []byte     // for accumulating text to write
}

// 全局变量
var std = New(os.Stderr, "", LstdFlags)

// 标准日志命令是通过std调用的
func Println(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
}
// 创建自己的日志变量
var (
	Info2  *log.Logger
	Error2 *log.Logger
)

func init() {
	Info2 = log.New(os.Stdout, "[info]", log.Ldate|log.Ltime|log.Lshortfile)
	Error2 = log.New(io.MultiWriter(os.Stdout, os.Stderr, "[Error]", log.Ldate|log.Ltime|log.Lshortfile)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!