Iht*_*kaS 3 flags command-line go
考虑一下,我的应用程序使用第三方库。我希望我的应用程序仅接受应用程序中定义的标志,而不接受导入的包中定义的标志。
package main
import (
"flag"
"fmt"
log "github.com/golang/glog"
)
var myFlag int
func init() {
flag.IntVar(&myFlag, "my_flag", 0, "need only my flags")
confDir := "/Users/foo/test/logs" //assume this is read from configuration file
flag.Set("log_dir", confDir)
flag.Parse()
}
func main() {
flag.Parse()
log.Errorln("flag", myFlag)
log.V(0).Infoln("flag", myFlag)
fmt.Println("test", myFlag)
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码示例中,日志包有很多标志。编译后,当我执行以下命令时,将显示包括“my_flag”在内的所有标志和日志包中的标志。但是,我想使用从配置文件获取的值来设置代码中日志包标志的值。
-alsologtostderr
log to standard error as well as files
-log_backtrace_at value
when logging hits line file:N, emit a stack trace
-log_dir string
If non-empty, write log files in this directory
-logtostderr
log to standard error instead of files
-my_flag int
need only my flags
-stderrthreshold value
logs at or above this threshold go to stderr
-v value
log level for V logs
-vmodule value
comma-separated list of pattern=N settings for file-filtered logging
Run Code Online (Sandbox Code Playgroud)
如何限制我的应用程序可执行文件接受其他标志?
如果您想丢弃其他包的标志,那么您可以使用新的标志集而不是默认的标志集。
package main
import (
"flag"
"fmt"
"os"
)
var myFlag int
func main() {
f := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
f.IntVar(&myFlag, "my_flag", 0, "need only my flags")
confDir := "/Users/foo/test/logs" //assume this is read from configuration file
f.Set("log_dir", confDir)
f.Parse(os.Args[1:])
fmt.Println("test", myFlag)
}
Run Code Online (Sandbox Code Playgroud)