-2

I would like to log all the flags(cmdline args) passed to a program at startup. How do I do this? Currently the program uses flag package to read the flags into the program .

2
  • If it's for logging, why not just log the raw arguments?
    – JimB
    Commented Mar 3, 2020 at 22:40
  • Hi @JimB. How do I do that? I want dump of the args passed to the program. Commented Mar 3, 2020 at 22:43

2 Answers 2

5

If you're using the flag package, there is the concept of a "flag" which is a defined command line argument i.e.

name := flag.String("name", "default", "some name")

And also the concept of an "arg" which is an undefined command line argument (i.e. not a flag).

You can get the list of args with flag.Args() which returns string[].

There doesn't seem to be a way to get the list of flags. There are Visit functions. You could use VisitAll that takes a function to execute on each flag:

flag.VisitAll(func(f *flag.Flag) {
    fmt.Printf("%s: %s\n", f.Name, f.Value)
})
1

You can use os.Args, which is a slice of strings, from the os package.

E.g:

package main

import (
        "log"
        "os"
)

func main() {
        log.Println(os.Args)
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.