Golang学习笔记--log包
发布时间:2020-12-16 18:42:39 所属栏目:大数据 来源:网络整理
导读:个人站:http://www.cloudnoter.com/?p=137 一、快速使用 Golang的log包短小精悍,可以非常轻松的实现日志打印转存功能。不用多说,log支持并发操作(即协程安全-相对于JAVA中的线程安全而言),其结构定义如下: type Logger struct { mu sync . Mutex // e
个人站:http://www.cloudnoter.com/?p=137 一、快速使用 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 ioWriter // destination for output // 用于指定日志输出位置,理论上可以是任务地方,只要实现了io.Writer接口就行 buf []byte// for accumulating text to write // 日志内容 } log包定义了一些日志格式标志: // These flags define which text to prefix to each log entry generated by the Logger. const( // Bits or'ed together to control what's printed. There is no control over the// order they appear (the order listed here) or the format they present (as// described in the comments). A colon appears after these items:// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message Ldate = 1<< iota // the date: 2009/01/23Ltime // the time: 01:23:23Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.Llongfile // full file name and line number: /a/b/c/d.go:23Lshortfile // final file name element and line number: d.go:23. overrides LlongfileLstdFlags |// initial values for the standard logger) 上述这些标志可以在创建Logger对象时指定(通过下面的New函数创建),也可以通过Logger.setFlat()方法动态指定。 Logger对象通过函数New创建 // 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( ioWriter, prefix string flag int)*return&Logger{out: prefix flag} log包已默认提供了一个日志对象,并封装了包级别的常用函数,该对象将日志信息输出到标准输出设备中(开箱即用)。 var std osStderr ""LstdFlags// 日志中只使用的flag为LstdFlags,即只输出日期 如果只是想输出到终端而不保存到文件等其它地方时,可以直接通过log.Xxxx()方式直接调用,因为这些包级别的函数只是对std对象相关方法的简单封装,如println函数定义如下: // Println calls Output to print to the standard logger.// Arguments are handled in the manner of fmt.Println.Printlnv ...interface{}) stdOutput(2 fmtSprintlnv...)) 二、Logger对象方法使用说明 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |