/
example.go
71 lines (56 loc) · 1.83 KB
/
example.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright © 2023 KubeCub & Xinwei Xiong(cubxxw). All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
package main
import (
"context"
"flag"
"github.com/kubecub/log"
)
var (
h bool
level int
format string
)
func main() {
flag.BoolVar(&h, "h", false, "Print this help.")
flag.IntVar(&level, "l", 0, "Log level.")
flag.StringVar(&format, "f", "console", "log output format.")
flag.Parse()
if h {
flag.Usage()
return
}
// logger配置
opts := &log.Options{
Level: "debug",
Format: "console",
EnableColor: true, // if you need output to local path, with EnableColor must be false.
DisableCaller: true,
OutputPaths: []string{"test.log", "stdout"},
ErrorOutputPaths: []string{"error.log"},
}
// 初始化全局logger
log.Init(opts)
defer log.Flush()
// Debug、Info(with field)、Warnf、Errorw使用
log.Debug("This is a debug message")
log.Info("This is a info message", log.Int32("int_key", 10))
log.Warnf("This is a formatted %s message", "warn")
log.Errorw("Message printed with Errorw", "X-Request-ID", "fbf54504-64da-4088-9b86-67824a7fb508")
// WithValues使用
lv := log.WithValues("X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
lv.Infow("Info message printed with [WithValues] logger")
lv.Infow("Debug message printed with [WithValues] logger")
// Context使用
ctx := lv.WithContext(context.Background())
lc := log.FromContext(ctx)
lc.Info("Message printed with [WithContext] logger")
ln := lv.WithName("test")
ln.Info("Message printed with [WithName] logger")
// V level使用
log.V(log.InfoLevel).Info("This is a V level message")
log.V(log.ErrorLevel).
Infow("This is a V level message with fields", "X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
}