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 )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。