首頁  >  文章  >  後端開發  >  如何結合 cobra 和 klog

如何結合 cobra 和 klog

WBOY
WBOY轉載
2024-02-06 10:51:071096瀏覽

如何结合 cobra 和 klog

問題內容

我有一個專案需要使用cobraklog來產生可執行檔並列印日誌並保留。

首先我測試了一下,使用下面的klog可以將日誌同時輸出到terminal和file

package main
import (
    "flag"
    "k8s.io/klog"
)
func init() {
    var fs flag.flagset
    klog.initflags(&fs)
    fs.set("logtostderr", "false")
    fs.set("log_file_max_size", "100")
    fs.set("log_file", "/home/test/workspace/klogfile/test.log")
    fs.set("alsologtostderr", "true")
}
func main() {
    defer klog.flush()
    klog.info("info")
    klog.warning("warning")
    klog.error("error")
}

檔案/home/test/workspace/klogfile/test.log的內容如下

log file created at: 2023/04/06 16:46:07
running on machine: s52
binary: built with gc go1.16.12 for linux/amd64
log line format: [iwef]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
i0406 16:46:07.751183   13512 main.go:20] info
w0406 16:46:07.751594   13512 main.go:21] warning
e0406 16:46:07.751629   13512 main.go:22] error

然後我嘗試基於k8s style添加到cobra

#
package main
import (
    "flag"
    "github.com/spf13/cobra"
    "k8s.io/klog"
)
var (
    str = "hello world"
)
func newcommand() *cobra.command {
    cmd := &cobra.command{
        use:   "echo",
        short: "use klog with cobra",
        long:  "use klog together with cobra.",
        run: func(cmd *cobra.command, args []string) {
            run()
        },
    }
    klog.initflags(flag.commandline)
    cmd.flags().addgoflagset(flag.commandline)
    cmd.flags().sortflags = false
    cmd.flags().stringvar(&str, "str", str, "string to print")
    return cmd
}
func run() {
    defer klog.flush()
    klog.infof("running, str:%s", str)
}

func main() {
    if err := newcommand().execute(); err != nil {
        klog.fatalf("root cmd execute failed, err=%v", err)
    }
}

我可以透過--help列印出required日誌選項,但是當我重寫它們以實現上例中的儲存到檔案時,僅將輸出輸出到終端機而不是輸出到檔案

#
# go run main2.go --logtostderr false --log_file_max_size "100" --alsologtostderr true --log_file "/home/test/workspace/klogfile/test2.log"
I0406 16:52:57.479455   15217 cobra_klog.go:34] Running, str:hello world

請問我哪裡的缺少必要的程式碼,如果有請告訴我如何修改,謝謝!


正確答案


你的程式碼沒有任何問題。唯一的問題是您必須使用 -flag=false 表單來關閉布林標誌(請參閱 命令列標誌語法)。

嘗試此指令(以 --logtostderr=false 取代 --logtostderr false):

go run main2.go --logtostderr=false --log_file_max_size "100" --alsologtostderr true --log_file "/home/test/workspace/klogfile/test2.log"

順便說一句,我認為 --log_file_max_size "100" 可以簡化為 --log_file_max_size 100

更新

減少 klog 暴露的標誌:

package main
 
 import (
    "flag"
    "github.com/spf13/cobra"
    "k8s.io/klog"
 )
 
 var (
    str     = "hello world"
+   logFile string
 )
 
 func NewCommand() *cobra.Command {
+   var fs flag.FlagSet
+   klog.InitFlags(&fs)

    cmd := &cobra.Command{
        Use:   "echo",
        Short: "use klog with cobra",
        Long:  "Use klog together with cobra.",
        Run: func(cmd *cobra.Command, args []string) {
+           fs.Set("logtostderr", "false")
+           fs.Set("log_file", logFile)

            Run()
        },
    }
-   klog.InitFlags(flag.CommandLine)
-   cmd.Flags().AddGoFlagSet(flag.CommandLine)
    cmd.Flags().SortFlags = false
    cmd.Flags().StringVar(&str, "str", str, "string to print")
+   cmd.Flags().StringVar(&logFile, "log_file", "", "If non-empty, use this log file")
    return cmd
 }
 func Run() {
    defer klog.Flush()
    klog.Infof("Running, str:%s", str)
 }
 
 func main() {
    if err := NewCommand().Execute(); err != nil {
        klog.Fatalf("root cmd execute failed, err=%v", err)
    }
 }

以上是如何結合 cobra 和 klog的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除