【Golang】Go语言之log的使用

一、了解一些概念

Golang的log包短小精悍,可以非常轻松的实现日志打印转存功能。不用多说,log支持并发操作(即协程安全-相对于JAVA中的线程安全而言),其结构定义如下:

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 // 用于指定日志输出位置,理论上可以是任务地方,只要实现了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/23
	Ltime                         // the time: 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
	LstdFlags     = Ldate | Ltime // 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(out io.Writer, prefix string, flag int) *Logger {
	return &Logger{out: out, prefix: prefix, flag: flag}
} 

log包已默认提供了一个日志对象,并封装了包级别的常用函数,该对象将日志信息输出到标准输出设备中(开箱即用)。

var std = New(os.Stderr, "", 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.
func Println(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
}

二、如何将log 写入到指定的文件中

方法一

package main
import (
        "log"
        "os"
        "time"
)
func init() {
        file := "./" +"log"+ ".txt"
        logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
        if err != nil {
                panic(err)
        }
        log.SetOutput(logFile) // 将文件设置为log输出的文件
        log.SetPrefix("[log]")
        log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
        return
}

func main() {
        log.Println("Hello logs!") // log 还是可以作为输出的前缀
        return
}

方法二

package main

import (
        "log"
        "os"
        "time"
)
var loger *log.Logger

func init() {
        file := "./" + time.Now().Format("20180102") + ".txt"
        logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
        if err != nil {
                panic(err)
        }
        loger = log.New(logFile, "[qSkiptool]",log.LstdFlags | log.Lshortfile | log.LUTC) // 将文件设置为loger作为输出
        return
}

func main() {
        loger.Println("Hello logs") // 使用的时候,需要采用loger作为输出的前
        return
}

  




posted @ 2021-10-01 23:23  踏雪无痕SS  阅读(1211)  评论(0编辑  收藏  举报