cmd: make --logfile global parameter

This commit is contained in:
Christian Schwarz 2017-05-20 18:08:52 +02:00
parent 35dcfc234e
commit 3b1cac1ea2

View File

@ -23,6 +23,7 @@ type Logger interface {
var conf Config var conf Config
var runner *jobrun.JobRunner var runner *jobrun.JobRunner
var logFlags int = log.LUTC | log.Ldate | log.Ltime var logFlags int = log.LUTC | log.Ldate | log.Ltime
var logOut io.Writer
var defaultLog Logger var defaultLog Logger
func main() { func main() {
@ -43,11 +44,27 @@ func main() {
app.EnableBashCompletion = true app.EnableBashCompletion = true
app.Flags = []cli.Flag{ app.Flags = []cli.Flag{
cli.StringFlag{Name: "config"}, cli.StringFlag{Name: "config"},
cli.StringFlag{Name: "logfile"},
} }
app.Before = func(c *cli.Context) (err error) { app.Before = func(c *cli.Context) (err error) {
defaultLog = log.New(os.Stderr, "", logFlags) if c.GlobalIsSet("logfile") {
var logFile *os.File
logFile, err = os.OpenFile(c.String("logfile"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return
}
if err = unix.Dup2(int(logFile.Fd()), int(os.Stderr.Fd())); err != nil {
logFile.WriteString(fmt.Sprintf("error duping logfile to stderr: %s\n", err))
return
}
logOut = logFile
} else {
logOut = os.Stderr
}
defaultLog = log.New(logOut, "", logFlags)
if !c.GlobalIsSet("config") { if !c.GlobalIsSet("config") {
return cli.NewExitError("config flag not set", 2) return cli.NewExitError("config flag not set", 2)
} }
@ -66,7 +83,6 @@ func main() {
Usage: "start in stdin server mode (from authorized keys)", Usage: "start in stdin server mode (from authorized keys)",
Flags: []cli.Flag{ Flags: []cli.Flag{
cli.StringFlag{Name: "identity"}, cli.StringFlag{Name: "identity"},
cli.StringFlag{Name: "logfile"},
}, },
Action: cmdStdinServer, Action: cmdStdinServer,
}, },
@ -89,23 +105,6 @@ func cmdStdinServer(c *cli.Context) (err error) {
} }
identity := c.String("identity") identity := c.String("identity")
var logOut io.Writer
if c.IsSet("logfile") {
var logFile *os.File
logFile, err = os.OpenFile(c.String("logfile"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return
}
if err = unix.Dup2(int(logFile.Fd()), int(os.Stderr.Fd())); err != nil {
logFile.WriteString(fmt.Sprintf("error duping logfile to stderr: %s\n", err))
return
}
logOut = logFile
} else {
logOut = os.Stderr
}
var sshByteStream io.ReadWriteCloser var sshByteStream io.ReadWriteCloser
if sshByteStream, err = sshbytestream.Incoming(); err != nil { if sshByteStream, err = sshbytestream.Incoming(); err != nil {
return return