golang package log
Posted endurance9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang package log相关的知识,希望对你有一定的参考价值。
package main
import (
"log"
"os"
)
var logger *log.Logger
func main() {
file, err := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE, 666)
if err != nil {
log.Fatalln("fail to create test.log file!")
}
defer file.Close()
logger = log.New(file, "", log.LstdFlags|log.Lshortfile) // 日志文件格式:log包含时间及文件行数
log.Println("输出日志到命令行终端")
logger.Println("将日志写入文件")
logger.SetFlags(log.LstdFlags | log.Lshortfile) // 设置日志格式
log.Panicln("在命令行终端输出panic,并中断程序执行")
logger.Panicln("在日志文件中写入panic,并中断程序执行")
log.Fatal("在命令行终端输出日志并执行os.exit(1)")
logger.Fatal("在日志文件中写入日志并执行os.exit(1)")
}
Logger结构体所有字段都是私有的,提供了一个工厂函数获取结构体实例
// New creates a new Logger. The out variable sets the // destination to which log data will be written. // The prefix appears at the beginning of each generated log line. // The flag argument defines the logging properties. func New(out io.Writer, prefix string, flag int) *Logger { return &Logger{out: out, prefix: prefix, flag: flag} }
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 LstdFlags = Ldate | Ltime // initial values for the standard logger )
以上是关于golang package log的主要内容,如果未能解决你的问题,请参考以下文章