如何将 klog 同时记录到标准输出和文件中?

huangapple go评论81阅读模式
英文:

How klog logs to stdout as well as files files

问题

我正在为一个使用klog库进行日志记录的项目工作,并且我希望能够将日志写入终端,同时也能够写入文件以便在重新启动或停机期间查看。

我通过以下代码进行了测试,但它只能将日志写入文件,而不能同时输出到终端:

package main

import (
	"flag"
	"k8s.io/klog/v2"
)

func init() {
	var fs flag.FlagSet
	klog.InitFlags(&fs)
	fs.Set("logtostderr", "false")
	fs.Set("log_file_max_size", "1000")
	fs.Set("log_file", "/home/test/workspace/test/test.log")
}

func main() {
	defer klog.Flush()
	klog.Info("test")
}

我该如何实现这个功能?非常感谢您的帮助。

英文:

I'm working on a project that uses the klog library for logging, and I want to be able to write the logs to a **terminal** while being able to write to a **file** for viewing on reboot or downtime.

I tested through the following code, but it can only write to the file and not output at the terminal at the same time

package main

import (
	"flag"
	"k8s.io/klog/v2"
)

func init() {
func init() {
	var fs flag.FlagSet
	klog.InitFlags(&fs)
	fs.Set("logtostderr", "false")
	fs.Set("log_file_max_size", "1000")
	fs.Set("log_file", "/home/test/workspace/test/test.log")
}
}

func main() {
	defer klog.Flush()
	klog.Info("test")
}

How can I get it? I really appreciate any help with this.

答案1

得分: 1

如果你阅读Klog文档,它提到支持一个标志-alsologtostderr

-alsologtostderr=false
日志会同时写入标准错误和文件。

看起来这个标志可以满足你的需求。

英文:

If you read the Klog documentation says that it supports a flag, -alsologtostderr:

> -alsologtostderr=false<br/>
> Logs are written to standard error as well as to files.

Seems like that would do you.

huangapple
  • 本文由 发表于 2022年8月30日 11:23:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/73536793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定