英文:
How do I set the log directory of glog from code
问题
有人知道如何在Golang源代码中设置/修改日志目录吗?
我想在源代码中设置日志目录,而不是在命令行中使用-log_dir=
。
英文:
Does anyone know how to set/modify the log dir in the golang source code?
I want to set the log dir in the soure code, instead of -log_dir=
in the cmdline
答案1
得分: 20
这是我见过的一个常见的技巧:在代码中设置标志位。也非常适用于从代码中设置日志级别。
package main
import (
"flag"
"github.com/golang/glog"
)
func main() {
flag.Parse()
glog.Info("hi_a")
flag.Lookup("logtostderr").Value.Set("true")
glog.Info("hi_b")
flag.Lookup("log_dir").Value.Set("/path/to/log/dir")
glog.V(4).Info("v4a")
flag.Lookup("v").Value.Set("10")
glog.V(4).Info("v4b")
// etc.
}
输出结果:
hi_b
v4b
英文:
This is a hack I have seen lying around: set the flags in code.
Also very good for setting log levels from code.
package main
import (
"flag"
"github.com/golang/glog"
)
func main() {
flag.Parse()
glog.Info("hi_a")
flag.Lookup("logtostderr").Value.Set("true")
glog.Info("hi_b")
flag.Lookup("log_dir").Value.Set("/path/to/log/dir")
glog.V(4).Info("v4a")
flag.Lookup("v").Value.Set("10")
glog.V(4).Info("v4b")
//etc.
}
>>> hi_b
>>> v4b
答案2
得分: 4
glog包是Google内部使用的日志包的转储。Google使用命令行标志配置日志记录,这也是该包所支持的方式。
如果你想要从代码中设置目录,你可以寻找另一个日志包,或者对该包进行分支。
英文:
The glog package is a dump of the log package used inside Google. Google configures logging using command line flags and that's what the package supports.
You should look to another log package or fork the package if you want to set the directory from code.
答案3
得分: 1
变量logDir
确实存在于glog包中https://github.com/golang/glog/blob/master/glog_file.go#L41
它只是没有被导出。因此,您可以在您的glog实例的源代码中进行更改。这有点破解的感觉,但并不难。
英文:
Variable logDir
really exist in glog package https://github.com/golang/glog/blob/master/glog_file.go#L41
It just not exported. So you can change it in source of your instance of glog. It's little hacky, but not hard.
答案4
得分: 0
首先,Glog 依赖于 Flag 包。如果你不导入它,日志消息中会出现烦人的警告。
如果你只需要在初始化时设置参数一次,那非常简单。
flag.Set("logtostderr", "true")
flag.Parse()
glog.Infof("starting main program")
英文:
First of all Glog rely on the package Flag. If you will not import it, you will have annoying warning in log message.
If you only need to set parameters one time in initialisation it is very easy.
flag.Set("logtostderr", "true")
flag.Parse()
glog.Infof("starting main program")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论