11

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

RickyA
  • 15,465
  • 5
  • 71
  • 95
ZHOU Ling
  • 564
  • 1
  • 7
  • 13

4 Answers4

21

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
RickyA
  • 15,465
  • 5
  • 71
  • 95
  • I was wondering what these getter and setter methods were for. Note that with this method (lacking a documentation) you can also print the value `glog.Info("Log level: ", flag.Lookup("v").Value)`. Thank you very much. I don't think it's a hack. It is the intended use. – chmike Nov 20 '16 at 11:21
4

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

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.

Uvelichitel
  • 8,220
  • 1
  • 19
  • 36
0

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")
Roman Shishkin
  • 2,097
  • 20
  • 21