golang log标准库

不喜饶过

源码部分

type Logger struct {
	mu        sync.Mutex  // ensures atomic writes; protects the following fields
	prefix    string      // prefix on each line to identify the logger (but see Lmsgprefix)
	flag      int         // properties
	out       io.Writer   // destination for output
	buf       []byte      // for accumulating text to write
	isDiscard atomic.Bool // whether out == io.Discard
}


func New(out io.Writer, prefix string, flag int) *Logger {
	l := &Logger{out: out, prefix: prefix, flag: flag}
	if out == io.Discard {
		l.isDiscard.Store(true)
	}
	return l
}

var std = New(os.Stderr, "", LstdFlags)

// Default returns the standard logger used by the package-level output functions.
func Default() *Logger { return std }


//对应结构体中的flag
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
	Lmsgprefix                    // move the "prefix" from the beginning of the line to before the message
									//默认前缀放行首,log.Lmsgprefix 这个标记把前缀prefix放到消息message之前
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

默认输出

输出 格式输出 换行输出 备注
log.Print() log.Printf() log.Println() 类似fmt.Print*
log.Fatal() log.Fatalf() log.Fatalln() 相当于log.Print* + os.Exit(1)
log.Panic() log.Panicf() log.Panicln 相当于log.Print* + panic()

自定义logger

	l1 := log.New(os.Stdout, "\t", log.LstdFlags|log.Lmsgprefix) //自定义logger
	l1.Print("test")

	注: // 默认前缀放行首,log.Lmsgprefix 这个标记把前缀prefix放到消息message之前
		//os.Stdin  标准输入
		//os.Stdout 标准输出
		//os.Stderr 标准错误输出

文件输出

	f, err := os.OpenFile(
		"d:/test.txt",
		os.O_CREATE|os.O_RDONLY|os.O_APPEND, // 只写 | 文件不存在创建 | 追加
		os.ModePerm,// os.FileMode()     chmod值,如0511 
	)
	if err != nil {
		log.Panicln(err)
	}
	defer f.Close()
	l2 := log.New(f, "\t", log.LstdFlags|log.Lmsgprefix)
	l2.Println("test")

你可能感兴趣的:(GO,golang,开发语言,后端)