分享

使用golang log库包实现日志文件输出 | 峰云就她了

 紫火神兵 2017-07-26

.

1
2
3
4
5
6
7
8
9
10
//定义logger, 传入参数 文件,前缀字符串,flag标记
func New(out io.Writer, prefix string, flag int) *Logger
//设置flag格式
func SetFlags(flag int)
//配置log的输出格式
func SetPrefix(prefix string)


下面是golang log包参数中flag的用法。 flag有根据时间的,也有根据code行号的。 

1
2
3
4
5
6
Ldate         = 1 << iota     // the date: 2009/01/23 形如 2009/01/23 的日期
Ltime                         // the time: 01:23:23   形如 01:23:23   的时间
Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  形如01:23:23.123123   的时间
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 // 日期和时间


废话不多说,直接通过一个完整的实例说明golang log实例。 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
package main
import (
    "log"
    "os"
)
func main(){
    // 定义一个文件
    fileName := "ll.log"
    logFile,err  := os.Create(fileName)
    defer logFile.Close()
    if err != nil {
        log.Fatalln("open file error !")
    }
    // 创建一个日志对象
    debugLog := log.New(logFile,"[Debug]",log.LstdFlags)
    debugLog.Println("A debug message here")
    //配置一个日志格式的前缀
    debugLog.SetPrefix("[Info]")
    debugLog.Println("A Info Message here ")
    //配置log的Flag参数
    debugLog.SetFlags(debugLog.Flags() | log.LstdFlags)
    debugLog.Println("A different prefix")
}

在github中找到了一个老外封装的go-logging库包,还真是特别好用。 go-logging可自定义日志输出的格式和颜色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#http://
package main
import (
    "os"
    "fmt"
    "github.com/op/go-logging"
)
var log = logging.MustGetLogger("example")
var format = logging.MustStringFormatter(
    `%{color}%{time:15:04:05.000} %{shortfunc} > %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
type Password string
func (p Password) Redacted() interface{} {
    return logging.Redact(string(p))
}
func main() {
    logFile, err := os.OpenFile("log.txt", os.O_WRONLY,0666)
    if err != nil{
        fmt.Println(err)
    }
    backend1 := logging.NewLogBackend(logFile, "", 0)
    backend2 := logging.NewLogBackend(os.Stderr, "", 0)
    backend2Formatter := logging.NewBackendFormatter(backend2, format)
    backend1Leveled := logging.AddModuleLevel(backend1)
    backend1Leveled.SetLevel(logging.INFO, "")
    logging.SetBackend(backend1Leveled, backend2Formatter)
    log.Debugf("debug %s", Password("secret"))
    log.Info("info")
    log.Notice("notice")
    log.Warning("warning")
    log.Error("")
    log.Critical("太严重了")
}

上面的go-logging代码运行后的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
[ruifengyun@devops ~ ]$ go run l.go
18:26:36.456 main ? DEBU 001 debug ******
18:26:36.456 main ? INFO 002 info
18:26:36.456 main ? NOTI 003 notice
18:26:36.456 main ? WARN 004 warning
18:26:36.456 main ? ERRO 005
18:26:36.456 main ? CRIT 006 太严重了
[ruifengyun@devops ~ ]$ cat log.txt
info
notice
warning
太严重了

看看下面的日志有颜色效果吧…. 有点意思…


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多