config_logging.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package embed
  15. import (
  16. "crypto/tls"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "reflect"
  22. "sync"
  23. "go.etcd.io/etcd/pkg/logutil"
  24. "github.com/coreos/pkg/capnslog"
  25. "go.uber.org/zap"
  26. "go.uber.org/zap/zapcore"
  27. "google.golang.org/grpc"
  28. "google.golang.org/grpc/grpclog"
  29. )
  30. // GetLogger returns the logger.
  31. func (cfg Config) GetLogger() *zap.Logger {
  32. cfg.loggerMu.RLock()
  33. l := cfg.logger
  34. cfg.loggerMu.RUnlock()
  35. return l
  36. }
  37. // for testing
  38. var grpcLogOnce = new(sync.Once)
  39. // setupLogging initializes etcd logging.
  40. // Must be called after flag parsing or finishing configuring embed.Config.
  41. func (cfg *Config) setupLogging() error {
  42. // handle "DeprecatedLogOutput" in v3.4
  43. // TODO: remove "DeprecatedLogOutput" in v3.5
  44. len1 := len(cfg.DeprecatedLogOutput)
  45. len2 := len(cfg.LogOutputs)
  46. if len1 != len2 {
  47. switch {
  48. case len1 > len2: // deprecate "log-output" flag is used
  49. fmt.Fprintln(os.Stderr, "'--log-output' flag has been deprecated! Please use '--log-outputs'!")
  50. cfg.LogOutputs = cfg.DeprecatedLogOutput
  51. case len1 < len2: // "--log-outputs" flag has been set with multiple writers
  52. cfg.DeprecatedLogOutput = []string{}
  53. }
  54. } else {
  55. if len1 > 1 {
  56. return errors.New("both '--log-output' and '--log-outputs' are set; only set '--log-outputs'")
  57. }
  58. if len1 < 1 {
  59. return errors.New("either '--log-output' or '--log-outputs' flag must be set")
  60. }
  61. if reflect.DeepEqual(cfg.DeprecatedLogOutput, cfg.LogOutputs) && cfg.DeprecatedLogOutput[0] != DefaultLogOutput {
  62. return fmt.Errorf("'--log-output=%q' and '--log-outputs=%q' are incompatible; only set --log-outputs", cfg.DeprecatedLogOutput, cfg.LogOutputs)
  63. }
  64. if !reflect.DeepEqual(cfg.DeprecatedLogOutput, []string{DefaultLogOutput}) {
  65. fmt.Fprintf(os.Stderr, "[WARNING] Deprecated '--log-output' flag is set to %q\n", cfg.DeprecatedLogOutput)
  66. fmt.Fprintln(os.Stderr, "Please use '--log-outputs' flag")
  67. }
  68. }
  69. // TODO: remove after deprecating log related flags in v3.5
  70. if cfg.Debug {
  71. fmt.Fprintf(os.Stderr, "[WARNING] Deprecated '--debug' flag is set to %v (use '--log-level=debug' instead\n", cfg.Debug)
  72. }
  73. if cfg.Debug && cfg.LogLevel != "debug" {
  74. fmt.Fprintf(os.Stderr, "[WARNING] Deprecated '--debug' flag is set to %v with inconsistent '--log-level=%s' flag\n", cfg.Debug, cfg.LogLevel)
  75. }
  76. if cfg.Logger == "capnslog" {
  77. fmt.Fprintf(os.Stderr, "[WARNING] Deprecated '--logger=%s' flag is set; use '--logger=zap' flag instead\n", cfg.Logger)
  78. }
  79. if cfg.LogPkgLevels != "" {
  80. fmt.Fprintf(os.Stderr, "[WARNING] Deprecated '--log-package-levels=%s' flag is set; use '--logger=zap' flag instead\n", cfg.LogPkgLevels)
  81. }
  82. switch cfg.Logger {
  83. case "capnslog": // TODO: deprecate this in v3.5
  84. cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  85. cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  86. if cfg.Debug {
  87. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  88. grpc.EnableTracing = true
  89. // enable info, warning, error
  90. grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr))
  91. } else {
  92. capnslog.SetGlobalLogLevel(logutil.ConvertToCapnslogLogLevel(cfg.LogLevel))
  93. // only discard info
  94. grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, os.Stderr, os.Stderr))
  95. }
  96. // TODO: deprecate with "capnslog"
  97. if cfg.LogPkgLevels != "" {
  98. repoLog := capnslog.MustRepoLogger("go.etcd.io/etcd")
  99. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  100. if err != nil {
  101. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  102. return nil
  103. }
  104. repoLog.SetLogLevel(settings)
  105. }
  106. if len(cfg.LogOutputs) != 1 {
  107. return fmt.Errorf("--logger=capnslog supports only 1 value in '--log-outputs', got %q", cfg.LogOutputs)
  108. }
  109. // capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
  110. // where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
  111. // specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
  112. output := cfg.LogOutputs[0]
  113. switch output {
  114. case StdErrLogOutput:
  115. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
  116. case StdOutLogOutput:
  117. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
  118. case DefaultLogOutput:
  119. default:
  120. return fmt.Errorf("unknown log-output %q (only supports %q, %q, %q)", output, DefaultLogOutput, StdErrLogOutput, StdOutLogOutput)
  121. }
  122. case "zap":
  123. if len(cfg.LogOutputs) == 0 {
  124. cfg.LogOutputs = []string{DefaultLogOutput}
  125. }
  126. if len(cfg.LogOutputs) > 1 {
  127. for _, v := range cfg.LogOutputs {
  128. if v == DefaultLogOutput {
  129. return fmt.Errorf("multi logoutput for %q is not supported yet", DefaultLogOutput)
  130. }
  131. }
  132. }
  133. outputPaths, errOutputPaths := make([]string, 0), make([]string, 0)
  134. isJournal := false
  135. for _, v := range cfg.LogOutputs {
  136. switch v {
  137. case DefaultLogOutput:
  138. outputPaths = append(outputPaths, StdErrLogOutput)
  139. errOutputPaths = append(errOutputPaths, StdErrLogOutput)
  140. case JournalLogOutput:
  141. isJournal = true
  142. case StdErrLogOutput:
  143. outputPaths = append(outputPaths, StdErrLogOutput)
  144. errOutputPaths = append(errOutputPaths, StdErrLogOutput)
  145. case StdOutLogOutput:
  146. outputPaths = append(outputPaths, StdOutLogOutput)
  147. errOutputPaths = append(errOutputPaths, StdOutLogOutput)
  148. default:
  149. outputPaths = append(outputPaths, v)
  150. errOutputPaths = append(errOutputPaths, v)
  151. }
  152. }
  153. if !isJournal {
  154. copied := logutil.DefaultZapLoggerConfig
  155. copied.OutputPaths = outputPaths
  156. copied.ErrorOutputPaths = errOutputPaths
  157. copied = logutil.MergeOutputPaths(copied)
  158. copied.Level = zap.NewAtomicLevelAt(logutil.ConvertToZapLevel(cfg.LogLevel))
  159. if cfg.Debug || cfg.LogLevel == "debug" {
  160. // enable tracing even when "--debug --log-level info"
  161. // in order to keep backward compatibility with <= v3.3
  162. // TODO: remove "Debug" check in v3.5
  163. grpc.EnableTracing = true
  164. }
  165. if cfg.ZapLoggerBuilder == nil {
  166. cfg.ZapLoggerBuilder = func(c *Config) error {
  167. var err error
  168. c.logger, err = copied.Build()
  169. if err != nil {
  170. return err
  171. }
  172. c.loggerMu.Lock()
  173. defer c.loggerMu.Unlock()
  174. c.loggerConfig = &copied
  175. c.loggerCore = nil
  176. c.loggerWriteSyncer = nil
  177. grpcLogOnce.Do(func() {
  178. // debug true, enable info, warning, error
  179. // debug false, only discard info
  180. var gl grpclog.LoggerV2
  181. gl, err = logutil.NewGRPCLoggerV2(copied)
  182. if err == nil {
  183. grpclog.SetLoggerV2(gl)
  184. }
  185. })
  186. return nil
  187. }
  188. }
  189. } else {
  190. if len(cfg.LogOutputs) > 1 {
  191. for _, v := range cfg.LogOutputs {
  192. if v != DefaultLogOutput {
  193. return fmt.Errorf("running with systemd/journal but other '--log-outputs' values (%q) are configured with 'default'; override 'default' value with something else", cfg.LogOutputs)
  194. }
  195. }
  196. }
  197. // use stderr as fallback
  198. syncer, lerr := getJournalWriteSyncer()
  199. if lerr != nil {
  200. return lerr
  201. }
  202. lvl := zap.NewAtomicLevelAt(logutil.ConvertToZapLevel(cfg.LogLevel))
  203. if cfg.Debug || cfg.LogLevel == "debug" {
  204. // enable tracing even when "--debug --log-level info"
  205. // in order to keep backward compatibility with <= v3.3
  206. // TODO: remove "Debug" check in v3.5
  207. grpc.EnableTracing = true
  208. }
  209. // WARN: do not change field names in encoder config
  210. // journald logging writer assumes field names of "level" and "caller"
  211. cr := zapcore.NewCore(
  212. zapcore.NewJSONEncoder(logutil.DefaultZapLoggerConfig.EncoderConfig),
  213. syncer,
  214. lvl,
  215. )
  216. if cfg.ZapLoggerBuilder == nil {
  217. cfg.ZapLoggerBuilder = func(c *Config) error {
  218. c.logger = zap.New(cr, zap.AddCaller(), zap.ErrorOutput(syncer))
  219. c.loggerMu.Lock()
  220. defer c.loggerMu.Unlock()
  221. c.loggerConfig = nil
  222. c.loggerCore = cr
  223. c.loggerWriteSyncer = syncer
  224. grpcLogOnce.Do(func() {
  225. grpclog.SetLoggerV2(logutil.NewGRPCLoggerV2FromZapCore(cr, syncer))
  226. })
  227. return nil
  228. }
  229. }
  230. }
  231. err := cfg.ZapLoggerBuilder(cfg)
  232. if err != nil {
  233. return err
  234. }
  235. logTLSHandshakeFailure := func(conn *tls.Conn, err error) {
  236. state := conn.ConnectionState()
  237. remoteAddr := conn.RemoteAddr().String()
  238. serverName := state.ServerName
  239. if len(state.PeerCertificates) > 0 {
  240. cert := state.PeerCertificates[0]
  241. ips := make([]string, len(cert.IPAddresses))
  242. for i := range cert.IPAddresses {
  243. ips[i] = cert.IPAddresses[i].String()
  244. }
  245. cfg.logger.Warn(
  246. "rejected connection",
  247. zap.String("remote-addr", remoteAddr),
  248. zap.String("server-name", serverName),
  249. zap.Strings("ip-addresses", ips),
  250. zap.Strings("dns-names", cert.DNSNames),
  251. zap.Error(err),
  252. )
  253. } else {
  254. cfg.logger.Warn(
  255. "rejected connection",
  256. zap.String("remote-addr", remoteAddr),
  257. zap.String("server-name", serverName),
  258. zap.Error(err),
  259. )
  260. }
  261. }
  262. cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  263. cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  264. default:
  265. return fmt.Errorf("unknown logger option %q", cfg.Logger)
  266. }
  267. return nil
  268. }
  269. // NewZapCoreLoggerBuilder generates a zap core logger builder.
  270. func NewZapCoreLoggerBuilder(lg *zap.Logger, cr zapcore.Core, syncer zapcore.WriteSyncer) func(*Config) error {
  271. return func(cfg *Config) error {
  272. cfg.loggerMu.Lock()
  273. defer cfg.loggerMu.Unlock()
  274. cfg.logger = lg
  275. cfg.loggerConfig = nil
  276. cfg.loggerCore = cr
  277. cfg.loggerWriteSyncer = syncer
  278. grpcLogOnce.Do(func() {
  279. grpclog.SetLoggerV2(logutil.NewGRPCLoggerV2FromZapCore(cr, syncer))
  280. })
  281. return nil
  282. }
  283. }