From 4eb89c46ca5b34b8cb4c5301d801e7d9f03c0627 Mon Sep 17 00:00:00 2001 From: Gyu-Ho Lee Date: Wed, 15 Jun 2016 13:48:49 -0700 Subject: [PATCH] etcdmain: add log-output flag So we can choose where to write logs. Fix https://github.com/coreos/etcd/issues/5449. --- etcdmain/config.go | 2 ++ etcdmain/etcd.go | 37 +++++++++++++++++++++++++++++++++++++ etcdmain/help.go | 2 ++ 3 files changed, 41 insertions(+) diff --git a/etcdmain/config.go b/etcdmain/config.go index 61c50ddff05e..f4bad8c014fa 100644 --- a/etcdmain/config.go +++ b/etcdmain/config.go @@ -135,6 +135,7 @@ type config struct { // Debug logging Debug bool `json:"debug"` LogPkgLevels string `json:"log-package-levels"` + LogOutput string `json:"log-output"` // ForceNewCluster is unsafe ForceNewCluster bool `json:"force-new-cluster"` @@ -249,6 +250,7 @@ func NewConfig() *config { // logging fs.BoolVar(&cfg.Debug, "debug", false, "Enable debug-level logging for etcd.") fs.StringVar(&cfg.LogPkgLevels, "log-package-levels", "", "Specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG').") + fs.StringVar(&cfg.LogOutput, "log-output", "stderr", "Specify log output path (stderr,stdout,journald,YOUR_NAME.log).") // unsafe fs.BoolVar(&cfg.ForceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster.") diff --git a/etcdmain/etcd.go b/etcdmain/etcd.go index fd09b81bbb60..cca27ad7df25 100644 --- a/etcdmain/etcd.go +++ b/etcdmain/etcd.go @@ -24,6 +24,7 @@ import ( _ "net/http/pprof" "os" "path" + "path/filepath" "reflect" "runtime" "strings" @@ -616,6 +617,42 @@ func setupLogging(cfg *config) { } repoLog.SetLogLevel(settings) } + switch cfg.LogOutput { + case "", "stderr": + break + + case "stdout": + capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug)) + + case "journald": + f, err := capnslog.NewJournaldFormatter() + if err != nil { + plog.Warningf("couldn't log to journald (%v)", err) + return + } + capnslog.SetFormatter(f) + + default: + if filepath.Ext(cfg.LogOutput) == ".log" { + f, err := openToAppend(cfg.LogOutput) + if err != nil { + plog.Warningf("couldn't log to file %q (%v)", cfg.LogOutput, err) + return + } + capnslog.SetFormatter(capnslog.NewPrettyFormatter(f, cfg.Debug)) + } + } +} + +func openToAppend(fpath string) (*os.File, error) { + f, err := os.OpenFile(fpath, os.O_RDWR|os.O_APPEND, fileutil.PrivateFileMode) + if err != nil { + f, err = os.Create(fpath) + if err != nil { + return f, err + } + } + return f, nil } func checkSupportArch() { diff --git a/etcdmain/help.go b/etcdmain/help.go index 826ce5e0059a..a86c61940500 100644 --- a/etcdmain/help.go +++ b/etcdmain/help.go @@ -131,6 +131,8 @@ logging flags enable debug-level logging for etcd. --log-package-levels '' specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG'). + --log-output 'stderr' + specify log output path (stderr,stdout,journald,YOUR_NAME.log). unsafe flags: