logr.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*
  2. Copyright 2019 The logr Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // This design derives from Dave Cheney's blog:
  14. // http://dave.cheney.net/2015/11/05/lets-talk-about-logging
  15. // Package logr defines a general-purpose logging API and abstract interfaces
  16. // to back that API. Packages in the Go ecosystem can depend on this package,
  17. // while callers can implement logging with whatever backend is appropriate.
  18. //
  19. // Usage
  20. //
  21. // Logging is done using a Logger instance. Logger is a concrete type with
  22. // methods, which defers the actual logging to a LogSink interface. The main
  23. // methods of Logger are Info() and Error(). Arguments to Info() and Error()
  24. // are key/value pairs rather than printf-style formatted strings, emphasizing
  25. // "structured logging".
  26. //
  27. // With Go's standard log package, we might write:
  28. // log.Printf("setting target value %s", targetValue)
  29. //
  30. // With logr's structured logging, we'd write:
  31. // logger.Info("setting target", "value", targetValue)
  32. //
  33. // Errors are much the same. Instead of:
  34. // log.Printf("failed to open the pod bay door for user %s: %v", user, err)
  35. //
  36. // We'd write:
  37. // logger.Error(err, "failed to open the pod bay door", "user", user)
  38. //
  39. // Info() and Error() are very similar, but they are separate methods so that
  40. // LogSink implementations can choose to do things like attach additional
  41. // information (such as stack traces) on calls to Error(). Error() messages are
  42. // always logged, regardless of the current verbosity. If there is no error
  43. // instance available, passing nil is valid.
  44. //
  45. // Verbosity
  46. //
  47. // Often we want to log information only when the application in "verbose
  48. // mode". To write log lines that are more verbose, Logger has a V() method.
  49. // The higher the V-level of a log line, the less critical it is considered.
  50. // Log-lines with V-levels that are not enabled (as per the LogSink) will not
  51. // be written. Level V(0) is the default, and logger.V(0).Info() has the same
  52. // meaning as logger.Info(). Negative V-levels have the same meaning as V(0).
  53. // Error messages do not have a verbosity level and are always logged.
  54. //
  55. // Where we might have written:
  56. // if flVerbose >= 2 {
  57. // log.Printf("an unusual thing happened")
  58. // }
  59. //
  60. // We can write:
  61. // logger.V(2).Info("an unusual thing happened")
  62. //
  63. // Logger Names
  64. //
  65. // Logger instances can have name strings so that all messages logged through
  66. // that instance have additional context. For example, you might want to add
  67. // a subsystem name:
  68. //
  69. // logger.WithName("compactor").Info("started", "time", time.Now())
  70. //
  71. // The WithName() method returns a new Logger, which can be passed to
  72. // constructors or other functions for further use. Repeated use of WithName()
  73. // will accumulate name "segments". These name segments will be joined in some
  74. // way by the LogSink implementation. It is strongly recommended that name
  75. // segments contain simple identifiers (letters, digits, and hyphen), and do
  76. // not contain characters that could muddle the log output or confuse the
  77. // joining operation (e.g. whitespace, commas, periods, slashes, brackets,
  78. // quotes, etc).
  79. //
  80. // Saved Values
  81. //
  82. // Logger instances can store any number of key/value pairs, which will be
  83. // logged alongside all messages logged through that instance. For example,
  84. // you might want to create a Logger instance per managed object:
  85. //
  86. // With the standard log package, we might write:
  87. // log.Printf("decided to set field foo to value %q for object %s/%s",
  88. // targetValue, object.Namespace, object.Name)
  89. //
  90. // With logr we'd write:
  91. // // Elsewhere: set up the logger to log the object name.
  92. // obj.logger = mainLogger.WithValues(
  93. // "name", obj.name, "namespace", obj.namespace)
  94. //
  95. // // later on...
  96. // obj.logger.Info("setting foo", "value", targetValue)
  97. //
  98. // Best Practices
  99. //
  100. // Logger has very few hard rules, with the goal that LogSink implementations
  101. // might have a lot of freedom to differentiate. There are, however, some
  102. // things to consider.
  103. //
  104. // The log message consists of a constant message attached to the log line.
  105. // This should generally be a simple description of what's occurring, and should
  106. // never be a format string. Variable information can then be attached using
  107. // named values.
  108. //
  109. // Keys are arbitrary strings, but should generally be constant values. Values
  110. // may be any Go value, but how the value is formatted is determined by the
  111. // LogSink implementation.
  112. //
  113. // Logger instances are meant to be passed around by value. Code that receives
  114. // such a value can call its methods without having to check whether the
  115. // instance is ready for use.
  116. //
  117. // Calling methods with the null logger (Logger{}) as instance will crash
  118. // because it has no LogSink. Therefore this null logger should never be passed
  119. // around. For cases where passing a logger is optional, a pointer to Logger
  120. // should be used.
  121. //
  122. // Key Naming Conventions
  123. //
  124. // Keys are not strictly required to conform to any specification or regex, but
  125. // it is recommended that they:
  126. // * be human-readable and meaningful (not auto-generated or simple ordinals)
  127. // * be constant (not dependent on input data)
  128. // * contain only printable characters
  129. // * not contain whitespace or punctuation
  130. // * use lower case for simple keys and lowerCamelCase for more complex ones
  131. //
  132. // These guidelines help ensure that log data is processed properly regardless
  133. // of the log implementation. For example, log implementations will try to
  134. // output JSON data or will store data for later database (e.g. SQL) queries.
  135. //
  136. // While users are generally free to use key names of their choice, it's
  137. // generally best to avoid using the following keys, as they're frequently used
  138. // by implementations:
  139. // * "caller": the calling information (file/line) of a particular log line
  140. // * "error": the underlying error value in the `Error` method
  141. // * "level": the log level
  142. // * "logger": the name of the associated logger
  143. // * "msg": the log message
  144. // * "stacktrace": the stack trace associated with a particular log line or
  145. // error (often from the `Error` message)
  146. // * "ts": the timestamp for a log line
  147. //
  148. // Implementations are encouraged to make use of these keys to represent the
  149. // above concepts, when necessary (for example, in a pure-JSON output form, it
  150. // would be necessary to represent at least message and timestamp as ordinary
  151. // named values).
  152. //
  153. // Break Glass
  154. //
  155. // Implementations may choose to give callers access to the underlying
  156. // logging implementation. The recommended pattern for this is:
  157. // // Underlier exposes access to the underlying logging implementation.
  158. // // Since callers only have a logr.Logger, they have to know which
  159. // // implementation is in use, so this interface is less of an abstraction
  160. // // and more of way to test type conversion.
  161. // type Underlier interface {
  162. // GetUnderlying() <underlying-type>
  163. // }
  164. //
  165. // Logger grants access to the sink to enable type assertions like this:
  166. // func DoSomethingWithImpl(log logr.Logger) {
  167. // if underlier, ok := log.GetSink()(impl.Underlier) {
  168. // implLogger := underlier.GetUnderlying()
  169. // ...
  170. // }
  171. // }
  172. //
  173. // Custom `With*` functions can be implemented by copying the complete
  174. // Logger struct and replacing the sink in the copy:
  175. // // WithFooBar changes the foobar parameter in the log sink and returns a
  176. // // new logger with that modified sink. It does nothing for loggers where
  177. // // the sink doesn't support that parameter.
  178. // func WithFoobar(log logr.Logger, foobar int) logr.Logger {
  179. // if foobarLogSink, ok := log.GetSink()(FoobarSink); ok {
  180. // log = log.WithSink(foobarLogSink.WithFooBar(foobar))
  181. // }
  182. // return log
  183. // }
  184. //
  185. // Don't use New to construct a new Logger with a LogSink retrieved from an
  186. // existing Logger. Source code attribution might not work correctly and
  187. // unexported fields in Logger get lost.
  188. //
  189. // Beware that the same LogSink instance may be shared by different logger
  190. // instances. Calling functions that modify the LogSink will affect all of
  191. // those.
  192. package logr
  193. import (
  194. "context"
  195. )
  196. // New returns a new Logger instance. This is primarily used by libraries
  197. // implementing LogSink, rather than end users.
  198. func New(sink LogSink) Logger {
  199. logger := Logger{}
  200. logger.setSink(sink)
  201. sink.Init(runtimeInfo)
  202. return logger
  203. }
  204. // setSink stores the sink and updates any related fields. It mutates the
  205. // logger and thus is only safe to use for loggers that are not currently being
  206. // used concurrently.
  207. func (l *Logger) setSink(sink LogSink) {
  208. l.sink = sink
  209. }
  210. // GetSink returns the stored sink.
  211. func (l Logger) GetSink() LogSink {
  212. return l.sink
  213. }
  214. // WithSink returns a copy of the logger with the new sink.
  215. func (l Logger) WithSink(sink LogSink) Logger {
  216. l.setSink(sink)
  217. return l
  218. }
  219. // Logger is an interface to an abstract logging implementation. This is a
  220. // concrete type for performance reasons, but all the real work is passed on to
  221. // a LogSink. Implementations of LogSink should provide their own constructors
  222. // that return Logger, not LogSink.
  223. //
  224. // The underlying sink can be accessed through GetSink and be modified through
  225. // WithSink. This enables the implementation of custom extensions (see "Break
  226. // Glass" in the package documentation). Normally the sink should be used only
  227. // indirectly.
  228. type Logger struct {
  229. sink LogSink
  230. level int
  231. }
  232. // Enabled tests whether this Logger is enabled. For example, commandline
  233. // flags might be used to set the logging verbosity and disable some info logs.
  234. func (l Logger) Enabled() bool {
  235. return l.sink.Enabled(l.level)
  236. }
  237. // Info logs a non-error message with the given key/value pairs as context.
  238. //
  239. // The msg argument should be used to add some constant description to the log
  240. // line. The key/value pairs can then be used to add additional variable
  241. // information. The key/value pairs must alternate string keys and arbitrary
  242. // values.
  243. func (l Logger) Info(msg string, keysAndValues ...interface{}) {
  244. if l.Enabled() {
  245. if withHelper, ok := l.sink.(CallStackHelperLogSink); ok {
  246. withHelper.GetCallStackHelper()()
  247. }
  248. l.sink.Info(l.level, msg, keysAndValues...)
  249. }
  250. }
  251. // Error logs an error, with the given message and key/value pairs as context.
  252. // It functions similarly to Info, but may have unique behavior, and should be
  253. // preferred for logging errors (see the package documentations for more
  254. // information). The log message will always be emitted, regardless of
  255. // verbosity level.
  256. //
  257. // The msg argument should be used to add context to any underlying error,
  258. // while the err argument should be used to attach the actual error that
  259. // triggered this log line, if present. The err parameter is optional
  260. // and nil may be passed instead of an error instance.
  261. func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) {
  262. if withHelper, ok := l.sink.(CallStackHelperLogSink); ok {
  263. withHelper.GetCallStackHelper()()
  264. }
  265. l.sink.Error(err, msg, keysAndValues...)
  266. }
  267. // V returns a new Logger instance for a specific verbosity level, relative to
  268. // this Logger. In other words, V-levels are additive. A higher verbosity
  269. // level means a log message is less important. Negative V-levels are treated
  270. // as 0.
  271. func (l Logger) V(level int) Logger {
  272. if level < 0 {
  273. level = 0
  274. }
  275. l.level += level
  276. return l
  277. }
  278. // WithValues returns a new Logger instance with additional key/value pairs.
  279. // See Info for documentation on how key/value pairs work.
  280. func (l Logger) WithValues(keysAndValues ...interface{}) Logger {
  281. l.setSink(l.sink.WithValues(keysAndValues...))
  282. return l
  283. }
  284. // WithName returns a new Logger instance with the specified name element added
  285. // to the Logger's name. Successive calls with WithName append additional
  286. // suffixes to the Logger's name. It's strongly recommended that name segments
  287. // contain only letters, digits, and hyphens (see the package documentation for
  288. // more information).
  289. func (l Logger) WithName(name string) Logger {
  290. l.setSink(l.sink.WithName(name))
  291. return l
  292. }
  293. // WithCallDepth returns a Logger instance that offsets the call stack by the
  294. // specified number of frames when logging call site information, if possible.
  295. // This is useful for users who have helper functions between the "real" call
  296. // site and the actual calls to Logger methods. If depth is 0 the attribution
  297. // should be to the direct caller of this function. If depth is 1 the
  298. // attribution should skip 1 call frame, and so on. Successive calls to this
  299. // are additive.
  300. //
  301. // If the underlying log implementation supports a WithCallDepth(int) method,
  302. // it will be called and the result returned. If the implementation does not
  303. // support CallDepthLogSink, the original Logger will be returned.
  304. //
  305. // To skip one level, WithCallStackHelper() should be used instead of
  306. // WithCallDepth(1) because it works with implementions that support the
  307. // CallDepthLogSink and/or CallStackHelperLogSink interfaces.
  308. func (l Logger) WithCallDepth(depth int) Logger {
  309. if withCallDepth, ok := l.sink.(CallDepthLogSink); ok {
  310. l.setSink(withCallDepth.WithCallDepth(depth))
  311. }
  312. return l
  313. }
  314. // WithCallStackHelper returns a new Logger instance that skips the direct
  315. // caller when logging call site information, if possible. This is useful for
  316. // users who have helper functions between the "real" call site and the actual
  317. // calls to Logger methods and want to support loggers which depend on marking
  318. // each individual helper function, like loggers based on testing.T.
  319. //
  320. // In addition to using that new logger instance, callers also must call the
  321. // returned function.
  322. //
  323. // If the underlying log implementation supports a WithCallDepth(int) method,
  324. // WithCallDepth(1) will be called to produce a new logger. If it supports a
  325. // WithCallStackHelper() method, that will be also called. If the
  326. // implementation does not support either of these, the original Logger will be
  327. // returned.
  328. func (l Logger) WithCallStackHelper() (func(), Logger) {
  329. var helper func()
  330. if withCallDepth, ok := l.sink.(CallDepthLogSink); ok {
  331. l.setSink(withCallDepth.WithCallDepth(1))
  332. }
  333. if withHelper, ok := l.sink.(CallStackHelperLogSink); ok {
  334. helper = withHelper.GetCallStackHelper()
  335. } else {
  336. helper = func() {}
  337. }
  338. return helper, l
  339. }
  340. // contextKey is how we find Loggers in a context.Context.
  341. type contextKey struct{}
  342. // FromContext returns a Logger from ctx or an error if no Logger is found.
  343. func FromContext(ctx context.Context) (Logger, error) {
  344. if v, ok := ctx.Value(contextKey{}).(Logger); ok {
  345. return v, nil
  346. }
  347. return Logger{}, notFoundError{}
  348. }
  349. // notFoundError exists to carry an IsNotFound method.
  350. type notFoundError struct{}
  351. func (notFoundError) Error() string {
  352. return "no logr.Logger was present"
  353. }
  354. func (notFoundError) IsNotFound() bool {
  355. return true
  356. }
  357. // FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this
  358. // returns a Logger that discards all log messages.
  359. func FromContextOrDiscard(ctx context.Context) Logger {
  360. if v, ok := ctx.Value(contextKey{}).(Logger); ok {
  361. return v
  362. }
  363. return Discard()
  364. }
  365. // NewContext returns a new Context, derived from ctx, which carries the
  366. // provided Logger.
  367. func NewContext(ctx context.Context, logger Logger) context.Context {
  368. return context.WithValue(ctx, contextKey{}, logger)
  369. }
  370. // RuntimeInfo holds information that the logr "core" library knows which
  371. // LogSinks might want to know.
  372. type RuntimeInfo struct {
  373. // CallDepth is the number of call frames the logr library adds between the
  374. // end-user and the LogSink. LogSink implementations which choose to print
  375. // the original logging site (e.g. file & line) should climb this many
  376. // additional frames to find it.
  377. CallDepth int
  378. }
  379. // runtimeInfo is a static global. It must not be changed at run time.
  380. var runtimeInfo = RuntimeInfo{
  381. CallDepth: 1,
  382. }
  383. // LogSink represents a logging implementation. End-users will generally not
  384. // interact with this type.
  385. type LogSink interface {
  386. // Init receives optional information about the logr library for LogSink
  387. // implementations that need it.
  388. Init(info RuntimeInfo)
  389. // Enabled tests whether this LogSink is enabled at the specified V-level.
  390. // For example, commandline flags might be used to set the logging
  391. // verbosity and disable some info logs.
  392. Enabled(level int) bool
  393. // Info logs a non-error message with the given key/value pairs as context.
  394. // The level argument is provided for optional logging. This method will
  395. // only be called when Enabled(level) is true. See Logger.Info for more
  396. // details.
  397. Info(level int, msg string, keysAndValues ...interface{})
  398. // Error logs an error, with the given message and key/value pairs as
  399. // context. See Logger.Error for more details.
  400. Error(err error, msg string, keysAndValues ...interface{})
  401. // WithValues returns a new LogSink with additional key/value pairs. See
  402. // Logger.WithValues for more details.
  403. WithValues(keysAndValues ...interface{}) LogSink
  404. // WithName returns a new LogSink with the specified name appended. See
  405. // Logger.WithName for more details.
  406. WithName(name string) LogSink
  407. }
  408. // CallDepthLogSink represents a Logger that knows how to climb the call stack
  409. // to identify the original call site and can offset the depth by a specified
  410. // number of frames. This is useful for users who have helper functions
  411. // between the "real" call site and the actual calls to Logger methods.
  412. // Implementations that log information about the call site (such as file,
  413. // function, or line) would otherwise log information about the intermediate
  414. // helper functions.
  415. //
  416. // This is an optional interface and implementations are not required to
  417. // support it.
  418. type CallDepthLogSink interface {
  419. // WithCallDepth returns a LogSink that will offset the call
  420. // stack by the specified number of frames when logging call
  421. // site information.
  422. //
  423. // If depth is 0, the LogSink should skip exactly the number
  424. // of call frames defined in RuntimeInfo.CallDepth when Info
  425. // or Error are called, i.e. the attribution should be to the
  426. // direct caller of Logger.Info or Logger.Error.
  427. //
  428. // If depth is 1 the attribution should skip 1 call frame, and so on.
  429. // Successive calls to this are additive.
  430. WithCallDepth(depth int) LogSink
  431. }
  432. // CallStackHelperLogSink represents a Logger that knows how to climb
  433. // the call stack to identify the original call site and can skip
  434. // intermediate helper functions if they mark themselves as
  435. // helper. Go's testing package uses that approach.
  436. //
  437. // This is useful for users who have helper functions between the
  438. // "real" call site and the actual calls to Logger methods.
  439. // Implementations that log information about the call site (such as
  440. // file, function, or line) would otherwise log information about the
  441. // intermediate helper functions.
  442. //
  443. // This is an optional interface and implementations are not required
  444. // to support it. Implementations that choose to support this must not
  445. // simply implement it as WithCallDepth(1), because
  446. // Logger.WithCallStackHelper will call both methods if they are
  447. // present. This should only be implemented for LogSinks that actually
  448. // need it, as with testing.T.
  449. type CallStackHelperLogSink interface {
  450. // GetCallStackHelper returns a function that must be called
  451. // to mark the direct caller as helper function when logging
  452. // call site information.
  453. GetCallStackHelper() func()
  454. }
  455. // Marshaler is an optional interface that logged values may choose to
  456. // implement. Loggers with structured output, such as JSON, should
  457. // log the object return by the MarshalLog method instead of the
  458. // original value.
  459. type Marshaler interface {
  460. // MarshalLog can be used to:
  461. // - ensure that structs are not logged as strings when the original
  462. // value has a String method: return a different type without a
  463. // String method
  464. // - select which fields of a complex type should get logged:
  465. // return a simpler struct with fewer fields
  466. // - log unexported fields: return a different struct
  467. // with exported fields
  468. //
  469. // It may return any value of any type.
  470. MarshalLog() interface{}
  471. }