golang log

  • log std libraries use global variables to call the standard log command
  • You can create your own log variable according to
    • By New function
//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)
}
  • log.PanicAnd log.Fatalwill stop the program after the kick logs, except that the Panic function before stopping calls defer
Published 161 original articles · won praise 19 · views 50000 +

Guess you like

Origin blog.csdn.net/winter_wu_1998/article/details/102754949
log
log