diff options
Diffstat (limited to 'vendor/github.com/mattermost/logr')
24 files changed, 2894 insertions, 0 deletions
diff --git a/vendor/github.com/mattermost/logr/.gitignore b/vendor/github.com/mattermost/logr/.gitignore new file mode 100644 index 00000000..c2c0a9e2 --- /dev/null +++ b/vendor/github.com/mattermost/logr/.gitignore @@ -0,0 +1,36 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib +debug +dynip + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Output of profiler +*.prof + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +# IntelliJ config +.idea + +# log files +*.log + +# transient directories +vendor +output +build +app +logs + +# test apps +test/cmd/testapp1/testapp1 +test/cmd/simple/simple diff --git a/vendor/github.com/mattermost/logr/.travis.yml b/vendor/github.com/mattermost/logr/.travis.yml new file mode 100644 index 00000000..e6c7caf1 --- /dev/null +++ b/vendor/github.com/mattermost/logr/.travis.yml @@ -0,0 +1,4 @@ +language: go +sudo: false +go: + - 1.x
\ No newline at end of file diff --git a/vendor/github.com/mattermost/logr/LICENSE b/vendor/github.com/mattermost/logr/LICENSE new file mode 100644 index 00000000..3bea6788 --- /dev/null +++ b/vendor/github.com/mattermost/logr/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 wiggin77 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/mattermost/logr/README.md b/vendor/github.com/mattermost/logr/README.md new file mode 100644 index 00000000..a25d6de0 --- /dev/null +++ b/vendor/github.com/mattermost/logr/README.md @@ -0,0 +1,193 @@ +# logr + +[![GoDoc](https://godoc.org/github.com/mattermost/logr?status.svg)](http://godoc.org/github.com/mattermost/logr) +[![Report Card](https://goreportcard.com/badge/github.com/mattermost/logr)](https://goreportcard.com/report/github.com/mattermost/logr) + +Logr is a fully asynchronous, contextual logger for Go. + +It is very much inspired by [Logrus](https://github.com/sirupsen/logrus) but addresses two issues: + +1. Logr is fully asynchronous, meaning that all formatting and writing is done in the background. Latency sensitive applications benefit from not waiting for logging to complete. + +2. Logr provides custom filters which provide more flexibility than Trace, Debug, Info... levels. If you need to temporarily increase verbosity of logging while tracking down a problem you can avoid the fire-hose that typically comes from Debug or Trace by using custom filters. + +## Concepts + +<!-- markdownlint-disable MD033 --> +| entity | description | +| ------ | ----------- | +| Logr | Engine instance typically instantiated once; used to configure logging.<br>```lgr := &Logr{}```| +| Logger | Provides contextual logging via fields; lightweight, can be created once and accessed globally or create on demand.<br>```logger := lgr.NewLogger()```<br>```logger2 := logger.WithField("user", "Sam")```| +| Target | A destination for log items such as console, file, database or just about anything that can be written to. Each target has its own filter/level and formatter, and any number of targets can be added to a Logr. Targets for syslog and any io.Writer are built-in and it is easy to create your own. You can also use any [Logrus hooks](https://github.com/sirupsen/logrus/wiki/Hooks) via a simple [adapter](https://github.com/wiggin77/logrus4logr).| +| Filter | Determines which logging calls get written versus filtered out. Also determines which logging calls generate a stack trace.<br>```filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Fatal}```| +| Formatter | Formats the output. Logr includes built-in formatters for JSON and plain text with delimiters. It is easy to create your own formatters or you can also use any [Logrus formatters](https://github.com/sirupsen/logrus#formatters) via a simple [adapter](https://github.com/wiggin77/logrus4logr).<br>```formatter := &format.Plain{Delim: " \| "}```| + +## Usage + +```go +// Create Logr instance. +lgr := &logr.Logr{} + +// Create a filter and formatter. Both can be shared by multiple +// targets. +filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Error} +formatter := &format.Plain{Delim: " | "} + +// WriterTarget outputs to any io.Writer +t := target.NewWriterTarget(filter, formatter, os.StdOut, 1000) +lgr.AddTarget(t) + +// One or more Loggers can be created, shared, used concurrently, +// or created on demand. +logger := lgr.NewLogger().WithField("user", "Sarah") + +// Now we can log to the target(s). +logger.Debug("login attempt") +logger.Error("login failed") + +// Ensure targets are drained before application exit. +lgr.Shutdown() +``` + +## Fields + +Fields allow for contextual logging, meaning information can be added to log statements without changing the statements themselves. Information can be shared across multiple logging statements thus allowing log analysis tools to group them. + +Fields are added via Loggers: + +```go +lgr := &Logr{} +// ... add targets ... +logger := lgr.NewLogger().WithFields(logr.Fields{ + "user": user, + "role": role}) +logger.Info("login attempt") +// ... later ... +logger.Info("login successful") +``` + +`Logger.WithFields` can be used to create additional Loggers that add more fields. + +Logr fields are inspired by and work the same as [Logrus fields](https://github.com/sirupsen/logrus#fields). + +## Filters + +Logr supports the traditional seven log levels via `logr.StdFilter`: Panic, Fatal, Error, Warning, Info, Debug, and Trace. + +```go +// When added to a target, this filter will only allow +// log statements with level severity Warn or higher. +// It will also generate stack traces for Error or higher. +filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Error} +``` + +Logr also supports custom filters (logr.CustomFilter) which allow fine grained inclusion of log items without turning on the fire-hose. + +```go + // create custom levels; use IDs > 10. + LoginLevel := logr.Level{ID: 100, Name: "login ", Stacktrace: false} + LogoutLevel := logr.Level{ID: 101, Name: "logout", Stacktrace: false} + + lgr := &logr.Logr{} + + // create a custom filter with custom levels. + filter := &logr.CustomFilter{} + filter.Add(LoginLevel, LogoutLevel) + + formatter := &format.Plain{Delim: " | "} + tgr := target.NewWriterTarget(filter, formatter, os.StdOut, 1000) + lgr.AddTarget(tgr) + logger := lgr.NewLogger().WithFields(logr.Fields{"user": "Bob", "role": "admin"}) + + logger.Log(LoginLevel, "this item will get logged") + logger.Debug("won't be logged since Debug wasn't added to custom filter") +``` + +Both filter types allow you to determine which levels require a stack trace to be output. Note that generating stack traces cannot happen fully asynchronously and thus add latency to the calling goroutine. + +## Targets + +There are built-in targets for outputting to syslog, file, or any `io.Writer`. More will be added. + +You can use any [Logrus hooks](https://github.com/sirupsen/logrus/wiki/Hooks) via a simple [adapter](https://github.com/wiggin77/logrus4logr). + +You can create your own target by implementing the [Target](./target.go) interface. + +An easier method is to use the [logr.Basic](./target.go) type target and build your functionality on that. Basic handles all the queuing and other plumbing so you only need to implement two methods. Example target that outputs to `io.Writer`: + +```go +type Writer struct { + logr.Basic + out io.Writer +} + +func NewWriterTarget(filter logr.Filter, formatter logr.Formatter, out io.Writer, maxQueue int) *Writer { + w := &Writer{out: out} + w.Basic.Start(w, w, filter, formatter, maxQueue) + return w +} + +// Write will always be called by a single goroutine, so no locking needed. +// Just convert a log record to a []byte using the formatter and output the +// bytes to your sink. +func (w *Writer) Write(rec *logr.LogRec) error { + _, stacktrace := w.IsLevelEnabled(rec.Level()) + + // take a buffer from the pool to avoid allocations or just allocate a new one. + buf := rec.Logger().Logr().BorrowBuffer() + defer rec.Logger().Logr().ReleaseBuffer(buf) + + buf, err := w.Formatter().Format(rec, stacktrace, buf) + if err != nil { + return err + } + _, err = w.out.Write(buf.Bytes()) + return err +} +``` + +## Formatters + +Logr has two built-in formatters, one for JSON and the other plain, delimited text. + +You can use any [Logrus formatters](https://github.com/sirupsen/logrus#formatters) via a simple [adapter](https://github.com/wiggin77/logrus4logr). + +You can create your own formatter by implementing the [Formatter](./formatter.go) interface: + +```go +Format(rec *LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) +``` + +## Handlers + +When creating the Logr instance, you can add several handlers that get called when exceptional events occur: + +### ```Logr.OnLoggerError(err error)``` + +Called any time an internal logging error occurs. For example, this can happen when a target cannot connect to its data sink. + +It may be tempting to log this error, however there is a danger that logging this will simply generate another error and so on. If you must log it, use a target and custom level specifically for this event and ensure it cannot generate more errors. + +### ```Logr.OnQueueFull func(rec *LogRec, maxQueueSize int) bool``` + +Called on an attempt to add a log record to a full Logr queue. This generally means the Logr maximum queue size is too small, or at least one target is very slow. Logr maximum queue size can be changed before adding any targets via: + +```go +lgr := logr.Logr{MaxQueueSize: 10000} +``` + +Returning true will drop the log record. False will block until the log record can be added, which creates a natural throttle at the expense of latency for the calling goroutine. The default is to block. + +### ```Logr.OnTargetQueueFull func(target Target, rec *LogRec, maxQueueSize int) bool``` + +Called on an attempt to add a log record to a full target queue. This generally means your target's max queue size is too small, or the target is very slow to output. + +As with the Logr queue, returning true will drop the log record. False will block until the log record can be added, which creates a natural throttle at the expense of latency for the calling goroutine. The default is to block. + +### ```Logr.OnExit func(code int) and Logr.OnPanic func(err interface{})``` + +OnExit and OnPanic are called when the Logger.FatalXXX and Logger.PanicXXX functions are called respectively. + +In both cases the default behavior is to shut down gracefully, draining all targets, and calling `os.Exit` or `panic` respectively. + +When adding your own handlers, be sure to call `Logr.Shutdown` before exiting the application to avoid losing log records. diff --git a/vendor/github.com/mattermost/logr/config.go b/vendor/github.com/mattermost/logr/config.go new file mode 100644 index 00000000..83d4b0c1 --- /dev/null +++ b/vendor/github.com/mattermost/logr/config.go @@ -0,0 +1,11 @@ +package logr + +import ( + "fmt" + + "github.com/wiggin77/cfg" +) + +func ConfigLogger(config *cfg.Config) error { + return fmt.Errorf("Not implemented yet") +} diff --git a/vendor/github.com/mattermost/logr/const.go b/vendor/github.com/mattermost/logr/const.go new file mode 100644 index 00000000..704d0507 --- /dev/null +++ b/vendor/github.com/mattermost/logr/const.go @@ -0,0 +1,34 @@ +package logr + +import "time" + +// Defaults. +const ( + // DefaultMaxQueueSize is the default maximum queue size for Logr instances. + DefaultMaxQueueSize = 1000 + + // DefaultMaxStackFrames is the default maximum max number of stack frames collected + // when generating stack traces for logging. + DefaultMaxStackFrames = 30 + + // MaxLevelID is the maximum value of a level ID. Some level cache implementations will + // allocate a cache of this size. Cannot exceed uint. + MaxLevelID = 256 + + // DefaultEnqueueTimeout is the default amount of time a log record can take to be queued. + // This only applies to blocking enqueue which happen after `logr.OnQueueFull` is called + // and returns false. + DefaultEnqueueTimeout = time.Second * 30 + + // DefaultShutdownTimeout is the default amount of time `logr.Shutdown` can execute before + // timing out. + DefaultShutdownTimeout = time.Second * 30 + + // DefaultFlushTimeout is the default amount of time `logr.Flush` can execute before + // timing out. + DefaultFlushTimeout = time.Second * 30 + + // DefaultMaxPooledBuffer is the maximum size a pooled buffer can be. + // Buffers that grow beyond this size are garbage collected. + DefaultMaxPooledBuffer = 1024 * 1024 +) diff --git a/vendor/github.com/mattermost/logr/filter.go b/vendor/github.com/mattermost/logr/filter.go new file mode 100644 index 00000000..6e654cd7 --- /dev/null +++ b/vendor/github.com/mattermost/logr/filter.go @@ -0,0 +1,26 @@ +package logr + +// LevelID is the unique id of each level. +type LevelID uint + +// Level provides a mechanism to enable/disable specific log lines. +type Level struct { + ID LevelID + Name string + Stacktrace bool +} + +// String returns the name of this level. +func (level Level) String() string { + return level.Name +} + +// Filter allows targets to determine which Level(s) are active +// for logging and which Level(s) require a stack trace to be output. +// A default implementation using "panic, fatal..." is provided, and +// a more flexible alternative implementation is also provided that +// allows any number of custom levels. +type Filter interface { + IsEnabled(Level) bool + IsStacktraceEnabled(Level) bool +} diff --git a/vendor/github.com/mattermost/logr/format/json.go b/vendor/github.com/mattermost/logr/format/json.go new file mode 100644 index 00000000..8f56c6cb --- /dev/null +++ b/vendor/github.com/mattermost/logr/format/json.go @@ -0,0 +1,273 @@ +package format + +import ( + "bytes" + "fmt" + "runtime" + "sort" + "sync" + "time" + + "github.com/francoispqt/gojay" + "github.com/mattermost/logr" +) + +// ContextField is a name/value pair within the context fields. +type ContextField struct { + Key string + Val interface{} +} + +// JSON formats log records as JSON. +type JSON struct { + // DisableTimestamp disables output of timestamp field. + DisableTimestamp bool + // DisableLevel disables output of level field. + DisableLevel bool + // DisableMsg disables output of msg field. + DisableMsg bool + // DisableContext disables output of all context fields. + DisableContext bool + // DisableStacktrace disables output of stack trace. + DisableStacktrace bool + + // TimestampFormat is an optional format for timestamps. If empty + // then DefTimestampFormat is used. + TimestampFormat string + + // Deprecated: this has no effect. + Indent string + + // EscapeHTML determines if certain characters (e.g. `<`, `>`, `&`) + // are escaped. + EscapeHTML bool + + // KeyTimestamp overrides the timestamp field key name. + KeyTimestamp string + + // KeyLevel overrides the level field key name. + KeyLevel string + + // KeyMsg overrides the msg field key name. + KeyMsg string + + // KeyContextFields when not empty will group all context fields + // under this key. + KeyContextFields string + + // KeyStacktrace overrides the stacktrace field key name. + KeyStacktrace string + + // ContextSorter allows custom sorting for the context fields. + ContextSorter func(fields logr.Fields) []ContextField + + once sync.Once +} + +// Format converts a log record to bytes in JSON format. +func (j *JSON) Format(rec *logr.LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) { + j.once.Do(j.applyDefaultKeyNames) + + if buf == nil { + buf = &bytes.Buffer{} + } + enc := gojay.BorrowEncoder(buf) + defer func() { + enc.Release() + }() + + sorter := j.ContextSorter + if sorter == nil { + sorter = j.defaultContextSorter + } + + jlr := JSONLogRec{ + LogRec: rec, + JSON: j, + stacktrace: stacktrace, + sorter: sorter, + } + + err := enc.EncodeObject(jlr) + if err != nil { + return nil, err + } + buf.WriteByte('\n') + return buf, nil +} + +func (j *JSON) applyDefaultKeyNames() { + if j.KeyTimestamp == "" { + j.KeyTimestamp = "timestamp" + } + if j.KeyLevel == "" { + j.KeyLevel = "level" + } + if j.KeyMsg == "" { + j.KeyMsg = "msg" + } + if j.KeyStacktrace == "" { + j.KeyStacktrace = "stacktrace" + } +} + +// defaultContextSorter sorts the context fields alphabetically by key. +func (j *JSON) defaultContextSorter(fields logr.Fields) []ContextField { + keys := make([]string, 0, len(fields)) + for k := range fields { + keys = append(keys, k) + } + sort.Strings(keys) + + cf := make([]ContextField, 0, len(keys)) + for _, k := range keys { + cf = append(cf, ContextField{Key: k, Val: fields[k]}) + } + return cf +} + +// JSONLogRec decorates a LogRec adding JSON encoding. +type JSONLogRec struct { + *logr.LogRec + *JSON + stacktrace bool + sorter func(fields logr.Fields) []ContextField +} + +// MarshalJSONObject encodes the LogRec as JSON. +func (rec JSONLogRec) MarshalJSONObject(enc *gojay.Encoder) { + if !rec.DisableTimestamp { + timestampFmt := rec.TimestampFormat + if timestampFmt == "" { + timestampFmt = logr.DefTimestampFormat + } + time := rec.Time() + enc.AddTimeKey(rec.KeyTimestamp, &time, timestampFmt) + } + if !rec.DisableLevel { + enc.AddStringKey(rec.KeyLevel, rec.Level().Name) + } + if !rec.DisableMsg { + enc.AddStringKey(rec.KeyMsg, rec.Msg()) + } + if !rec.DisableContext { + ctxFields := rec.sorter(rec.Fields()) + if rec.KeyContextFields != "" { + enc.AddObjectKey(rec.KeyContextFields, jsonFields(ctxFields)) + } else { + if len(ctxFields) > 0 { + for _, cf := range ctxFields { + key := rec.prefixCollision(cf.Key) + encodeField(enc, key, cf.Val) + } + } + } + } + if rec.stacktrace && !rec.DisableStacktrace { + frames := rec.StackFrames() + if len(frames) > 0 { + enc.AddArrayKey(rec.KeyStacktrace, stackFrames(frames)) + } + } + +} + +// IsNil returns true if the LogRec pointer is nil. +func (rec JSONLogRec) IsNil() bool { + return rec.LogRec == nil +} + +func (rec JSONLogRec) prefixCollision(key string) string { + switch key { + case rec.KeyTimestamp, rec.KeyLevel, rec.KeyMsg, rec.KeyStacktrace: + return rec.prefixCollision("_" + key) + } + return key +} + +type stackFrames []runtime.Frame + +// MarshalJSONArray encodes stackFrames slice as JSON. +func (s stackFrames) MarshalJSONArray(enc *gojay.Encoder) { + for _, frame := range s { + enc.AddObject(stackFrame(frame)) + } +} + +// IsNil returns true if stackFrames is empty slice. +func (s stackFrames) IsNil() bool { + return len(s) == 0 +} + +type stackFrame runtime.Frame + +// MarshalJSONArray encodes stackFrame as JSON. +func (f stackFrame) MarshalJSONObject(enc *gojay.Encoder) { + enc.AddStringKey("Function", f.Function) + enc.AddStringKey("File", f.File) + enc.AddIntKey("Line", f.Line) +} + +func (f stackFrame) IsNil() bool { + return false +} + +type jsonFields []ContextField + +// MarshalJSONObject encodes Fields map to JSON. +func (f jsonFields) MarshalJSONObject(enc *gojay.Encoder) { + for _, ctxField := range f { + encodeField(enc, ctxField.Key, ctxField.Val) + } +} + +// IsNil returns true if map is nil. +func (f jsonFields) IsNil() bool { + return f == nil +} + +func encodeField(enc *gojay.Encoder, key string, val interface{}) { + switch vt := val.(type) { + case gojay.MarshalerJSONObject: + enc.AddObjectKey(key, vt) + case gojay.MarshalerJSONArray: + enc.AddArrayKey(key, vt) + case string: + enc.AddStringKey(key, vt) + case error: + enc.AddStringKey(key, vt.Error()) + case bool: + enc.AddBoolKey(key, vt) + case int: + enc.AddIntKey(key, vt) + case int64: + enc.AddInt64Key(key, vt) + case int32: + enc.AddIntKey(key, int(vt)) + case int16: + enc.AddIntKey(key, int(vt)) + case int8: + enc.AddIntKey(key, int(vt)) + case uint64: + enc.AddIntKey(key, int(vt)) + case uint32: + enc.AddIntKey(key, int(vt)) + case uint16: + enc.AddIntKey(key, int(vt)) + case uint8: + enc.AddIntKey(key, int(vt)) + case float64: + enc.AddFloatKey(key, vt) + case float32: + enc.AddFloat32Key(key, vt) + case *gojay.EmbeddedJSON: + enc.AddEmbeddedJSONKey(key, vt) + case time.Time: + enc.AddTimeKey(key, &vt, logr.DefTimestampFormat) + case *time.Time: + enc.AddTimeKey(key, vt, logr.DefTimestampFormat) + default: + s := fmt.Sprintf("%v", vt) + enc.AddStringKey(key, s) + } +} diff --git a/vendor/github.com/mattermost/logr/format/plain.go b/vendor/github.com/mattermost/logr/format/plain.go new file mode 100644 index 00000000..3fa92b49 --- /dev/null +++ b/vendor/github.com/mattermost/logr/format/plain.go @@ -0,0 +1,75 @@ +package format + +import ( + "bytes" + "fmt" + + "github.com/mattermost/logr" +) + +// Plain is the simplest formatter, outputting only text with +// no colors. +type Plain struct { + // DisableTimestamp disables output of timestamp field. + DisableTimestamp bool + // DisableLevel disables output of level field. + DisableLevel bool + // DisableMsg disables output of msg field. + DisableMsg bool + // DisableContext disables output of all context fields. + DisableContext bool + // DisableStacktrace disables output of stack trace. + DisableStacktrace bool + + // Delim is an optional delimiter output between each log field. + // Defaults to a single space. + Delim string + + // TimestampFormat is an optional format for timestamps. If empty + // then DefTimestampFormat is used. + TimestampFormat string +} + +// Format converts a log record to bytes. +func (p *Plain) Format(rec *logr.LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) { + delim := p.Delim + if delim == "" { + delim = " " + } + if buf == nil { + buf = &bytes.Buffer{} + } + + timestampFmt := p.TimestampFormat + if timestampFmt == "" { + timestampFmt = logr.DefTimestampFormat + } + + if !p.DisableTimestamp { + var arr [128]byte + tbuf := rec.Time().AppendFormat(arr[:0], timestampFmt) + buf.Write(tbuf) + buf.WriteString(delim) + } + if !p.DisableLevel { + fmt.Fprintf(buf, "%v%s", rec.Level().Name, delim) + } + if !p.DisableMsg { + fmt.Fprint(buf, rec.Msg(), delim) + } + if !p.DisableContext { + ctx := rec.Fields() + if len(ctx) > 0 { + logr.WriteFields(buf, ctx, " ") + } + } + if stacktrace && !p.DisableStacktrace { + frames := rec.StackFrames() + if len(frames) > 0 { + buf.WriteString("\n") + logr.WriteStacktrace(buf, rec.StackFrames()) + } + } + buf.WriteString("\n") + return buf, nil +} diff --git a/vendor/github.com/mattermost/logr/formatter.go b/vendor/github.com/mattermost/logr/formatter.go new file mode 100644 index 00000000..bb8df2d4 --- /dev/null +++ b/vendor/github.com/mattermost/logr/formatter.go @@ -0,0 +1,119 @@ +package logr + +import ( + "bytes" + "fmt" + "io" + "runtime" + "sort" +) + +// Formatter turns a LogRec into a formatted string. +type Formatter interface { + // Format converts a log record to bytes. If buf is not nil then it will be + // be filled with the formatted results, otherwise a new buffer will be allocated. + Format(rec *LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) +} + +const ( + // DefTimestampFormat is the default time stamp format used by + // Plain formatter and others. + DefTimestampFormat = "2006-01-02 15:04:05.000 Z07:00" +) + +// DefaultFormatter is the default formatter, outputting only text with +// no colors and a space delimiter. Use `format.Plain` instead. +type DefaultFormatter struct { +} + +// Format converts a log record to bytes. +func (p *DefaultFormatter) Format(rec *LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) { + if buf == nil { + buf = &bytes.Buffer{} + } + delim := " " + timestampFmt := DefTimestampFormat + + fmt.Fprintf(buf, "%s%s", rec.Time().Format(timestampFmt), delim) + fmt.Fprintf(buf, "%v%s", rec.Level(), delim) + fmt.Fprint(buf, rec.Msg(), delim) + + ctx := rec.Fields() + if len(ctx) > 0 { + WriteFields(buf, ctx, " ") + } + + if stacktrace { + frames := rec.StackFrames() + if len(frames) > 0 { + buf.WriteString("\n") + WriteStacktrace(buf, rec.StackFrames()) + } + } + buf.WriteString("\n") + + return buf, nil +} + +// WriteFields writes zero or more name value pairs to the io.Writer. +// The pairs are sorted by key name and output in key=value format +// with optional separator between fields. +func WriteFields(w io.Writer, flds Fields, separator string) { + keys := make([]string, 0, len(flds)) + for k := range flds { + keys = append(keys, k) + } + sort.Strings(keys) + sep := "" + for _, key := range keys { + writeField(w, key, flds[key], sep) + sep = separator + } +} + +func writeField(w io.Writer, key string, val interface{}, sep string) { + var template string + switch v := val.(type) { + case error: + val := v.Error() + if shouldQuote(val) { + template = "%s%s=%q" + } else { + template = "%s%s=%s" + } + case string: + if shouldQuote(v) { + template = "%s%s=%q" + } else { + template = "%s%s=%s" + } + default: + template = "%s%s=%v" + } + fmt.Fprintf(w, template, sep, key, val) +} + +// shouldQuote returns true if val contains any characters that might be unsafe +// when injecting log output into an aggregator, viewer or report. +func shouldQuote(val string) bool { + for _, c := range val { + if !((c >= '0' && c <= '9') || + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z')) { + return true + } + } + return false +} + +// WriteStacktrace formats and outputs a stack trace to an io.Writer. +func WriteStacktrace(w io.Writer, frames []runtime.Frame) { + for _, frame := range frames { + if frame.Function != "" { + fmt.Fprintf(w, " %s\n", frame.Function) + } + if frame.File != "" { + fmt.Fprintf(w, " %s:%d\n", frame.File, frame.Line) + } + } +} diff --git a/vendor/github.com/mattermost/logr/go.mod b/vendor/github.com/mattermost/logr/go.mod new file mode 100644 index 00000000..e8e8acfb --- /dev/null +++ b/vendor/github.com/mattermost/logr/go.mod @@ -0,0 +1,11 @@ +module github.com/mattermost/logr + +go 1.12 + +require ( + github.com/francoispqt/gojay v1.2.13 + github.com/stretchr/testify v1.2.2 + github.com/wiggin77/cfg v1.0.2 + github.com/wiggin77/merror v1.0.2 + gopkg.in/natefinch/lumberjack.v2 v2.0.0 +) diff --git a/vendor/github.com/mattermost/logr/go.sum b/vendor/github.com/mattermost/logr/go.sum new file mode 100644 index 00000000..ea688513 --- /dev/null +++ b/vendor/github.com/mattermost/logr/go.sum @@ -0,0 +1,174 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= +dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= +dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= +dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= +dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= +git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= +github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk= +github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= +github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= +github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= +github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= +github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= +github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= +github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= +github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= +github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= +github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= +github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= +github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= +github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= +github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= +github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= +github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= +github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= +github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= +github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= +github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= +github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= +github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= +github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= +github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= +github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= +github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= +github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= +github.com/wiggin77/cfg v1.0.2 h1:NBUX+iJRr+RTncTqTNvajHwzduqbhCQjEqxLHr6Fk7A= +github.com/wiggin77/cfg v1.0.2/go.mod h1:b3gotba2e5bXTqTW48DwIFoLc+4lWKP7WPi/CdvZ4aE= +github.com/wiggin77/merror v1.0.2 h1:V0nH9eFp64ASyaXC+pB5WpvBoCg7NUwvaCSKdzlcHqw= +github.com/wiggin77/merror v1.0.2/go.mod h1:uQTcIU0Z6jRK4OwqganPYerzQxSFJ4GSHM3aurxxQpg= +go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= +go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= +golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= +golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= +google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= +sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/vendor/github.com/mattermost/logr/levelcache.go b/vendor/github.com/mattermost/logr/levelcache.go new file mode 100644 index 00000000..2cefb61d --- /dev/null +++ b/vendor/github.com/mattermost/logr/levelcache.go @@ -0,0 +1,98 @@ +package logr + +import ( + "fmt" + "sync" +) + +// LevelStatus represents whether a level is enabled and +// requires a stack trace. +type LevelStatus struct { + Enabled bool + Stacktrace bool + empty bool +} + +type levelCache interface { + setup() + get(id LevelID) (LevelStatus, bool) + put(id LevelID, status LevelStatus) error + clear() +} + +// syncMapLevelCache uses sync.Map which may better handle large concurrency +// scenarios. +type syncMapLevelCache struct { + m sync.Map +} + +func (c *syncMapLevelCache) setup() { + c.clear() +} + +func (c *syncMapLevelCache) get(id LevelID) (LevelStatus, bool) { + if id > MaxLevelID { + return LevelStatus{}, false + } + s, _ := c.m.Load(id) + status := s.(LevelStatus) + return status, !status.empty +} + +func (c *syncMapLevelCache) put(id LevelID, status LevelStatus) error { + if id > MaxLevelID { + return fmt.Errorf("level id cannot exceed MaxLevelID (%d)", MaxLevelID) + } + c.m.Store(id, status) + return nil +} + +func (c *syncMapLevelCache) clear() { + var i LevelID + for i = 0; i < MaxLevelID; i++ { + c.m.Store(i, LevelStatus{empty: true}) + } +} + +// arrayLevelCache using array and a mutex. +type arrayLevelCache struct { + arr [MaxLevelID + 1]LevelStatus + mux sync.RWMutex +} + +func (c *arrayLevelCache) setup() { + c.clear() +} + +//var dummy = LevelStatus{} + +func (c *arrayLevelCache) get(id LevelID) (LevelStatus, bool) { + if id > MaxLevelID { + return LevelStatus{}, false + } + c.mux.RLock() + status := c.arr[id] + ok := !status.empty + c.mux.RUnlock() + return status, ok +} + +func (c *arrayLevelCache) put(id LevelID, status LevelStatus) error { + if id > MaxLevelID { + return fmt.Errorf("level id cannot exceed MaxLevelID (%d)", MaxLevelID) + } + c.mux.Lock() + defer c.mux.Unlock() + + c.arr[id] = status + return nil +} + +func (c *arrayLevelCache) clear() { + c.mux.Lock() + defer c.mux.Unlock() + + for i := range c.arr { + c.arr[i] = LevelStatus{empty: true} + } +} diff --git a/vendor/github.com/mattermost/logr/levelcustom.go b/vendor/github.com/mattermost/logr/levelcustom.go new file mode 100644 index 00000000..384fe4e9 --- /dev/null +++ b/vendor/github.com/mattermost/logr/levelcustom.go @@ -0,0 +1,45 @@ +package logr + +import ( + "sync" +) + +// CustomFilter allows targets to enable logging via a list of levels. +type CustomFilter struct { + mux sync.RWMutex + levels map[LevelID]Level +} + +// IsEnabled returns true if the specified Level exists in this list. +func (st *CustomFilter) IsEnabled(level Level) bool { + st.mux.RLock() + defer st.mux.RUnlock() + _, ok := st.levels[level.ID] + return ok +} + +// IsStacktraceEnabled returns true if the specified Level requires a stack trace. +func (st *CustomFilter) IsStacktraceEnabled(level Level) bool { + st.mux.RLock() + defer st.mux.RUnlock() + lvl, ok := st.levels[level.ID] + if ok { + return lvl.Stacktrace + } + return false +} + +// Add adds one or more levels to the list. Adding a level enables logging for +// that level on any targets using this CustomFilter. +func (st *CustomFilter) Add(levels ...Level) { + st.mux.Lock() + defer st.mux.Unlock() + + if st.levels == nil { + st.levels = make(map[LevelID]Level) + } + + for _, s := range levels { + st.levels[s.ID] = s + } +} diff --git a/vendor/github.com/mattermost/logr/levelstd.go b/vendor/github.com/mattermost/logr/levelstd.go new file mode 100644 index 00000000..f5e0fa46 --- /dev/null +++ b/vendor/github.com/mattermost/logr/levelstd.go @@ -0,0 +1,37 @@ +package logr + +// StdFilter allows targets to filter via classic log levels where any level +// beyond a certain verbosity/severity is enabled. +type StdFilter struct { + Lvl Level + Stacktrace Level +} + +// IsEnabled returns true if the specified Level is at or above this verbosity. Also +// determines if a stack trace is required. +func (lt StdFilter) IsEnabled(level Level) bool { + return level.ID <= lt.Lvl.ID +} + +// IsStacktraceEnabled returns true if the specified Level requires a stack trace. +func (lt StdFilter) IsStacktraceEnabled(level Level) bool { + return level.ID <= lt.Stacktrace.ID +} + +var ( + // Panic is the highest level of severity. Logs the message and then panics. + Panic = Level{ID: 0, Name: "panic"} + // Fatal designates a catastrophic error. Logs the message and then calls + // `logr.Exit(1)`. + Fatal = Level{ID: 1, Name: "fatal"} + // Error designates a serious but possibly recoverable error. + Error = Level{ID: 2, Name: "error"} + // Warn designates non-critical error. + Warn = Level{ID: 3, Name: "warn"} + // Info designates information regarding application events. + Info = Level{ID: 4, Name: "info"} + // Debug designates verbose information typically used for debugging. + Debug = Level{ID: 5, Name: "debug"} + // Trace designates the highest verbosity of log output. + Trace = Level{ID: 6, Name: "trace"} +) diff --git a/vendor/github.com/mattermost/logr/logger.go b/vendor/github.com/mattermost/logr/logger.go new file mode 100644 index 00000000..c2386312 --- /dev/null +++ b/vendor/github.com/mattermost/logr/logger.go @@ -0,0 +1,218 @@ +package logr + +import ( + "fmt" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Logger provides context for logging via fields. +type Logger struct { + logr *Logr + fields Fields +} + +// Logr returns the `Logr` instance that created this `Logger`. +func (logger Logger) Logr() *Logr { + return logger.logr +} + +// WithField creates a new `Logger` with any existing fields +// plus the new one. +func (logger Logger) WithField(key string, value interface{}) Logger { + return logger.WithFields(Fields{key: value}) +} + +// WithFields creates a new `Logger` with any existing fields +// plus the new ones. +func (logger Logger) WithFields(fields Fields) Logger { + l := Logger{logr: logger.logr} + // if parent has no fields then avoid creating a new map. + oldLen := len(logger.fields) + if oldLen == 0 { + l.fields = fields + return l + } + + l.fields = make(Fields, len(fields)+oldLen) + for k, v := range logger.fields { + l.fields[k] = v + } + for k, v := range fields { + l.fields[k] = v + } + return l +} + +// Log checks that the level matches one or more targets, and +// if so, generates a log record that is added to the Logr queue. +// Arguments are handled in the manner of fmt.Print. +func (logger Logger) Log(lvl Level, args ...interface{}) { + status := logger.logr.IsLevelEnabled(lvl) + if status.Enabled { + rec := NewLogRec(lvl, logger, "", args, status.Stacktrace) + logger.logr.enqueue(rec) + } +} + +// Trace is a convenience method equivalent to `Log(TraceLevel, args...)`. +func (logger Logger) Trace(args ...interface{}) { + logger.Log(Trace, args...) +} + +// Debug is a convenience method equivalent to `Log(DebugLevel, args...)`. +func (logger Logger) Debug(args ...interface{}) { + logger.Log(Debug, args...) +} + +// Print ensures compatibility with std lib logger. +func (logger Logger) Print(args ...interface{}) { + logger.Info(args...) +} + +// Info is a convenience method equivalent to `Log(InfoLevel, args...)`. +func (logger Logger) Info(args ...interface{}) { + logger.Log(Info, args...) +} + +// Warn is a convenience method equivalent to `Log(WarnLevel, args...)`. +func (logger Logger) Warn(args ...interface{}) { + logger.Log(Warn, args...) +} + +// Error is a convenience method equivalent to `Log(ErrorLevel, args...)`. +func (logger Logger) Error(args ...interface{}) { + logger.Log(Error, args...) +} + +// Fatal is a convenience method equivalent to `Log(FatalLevel, args...)` +// followed by a call to os.Exit(1). +func (logger Logger) Fatal(args ...interface{}) { + logger.Log(Fatal, args...) + logger.logr.exit(1) +} + +// Panic is a convenience method equivalent to `Log(PanicLevel, args...)` +// followed by a call to panic(). +func (logger Logger) Panic(args ...interface{}) { + logger.Log(Panic, args...) + panic(fmt.Sprint(args...)) +} + +// +// Printf style +// + +// Logf checks that the level matches one or more targets, and +// if so, generates a log record that is added to the main +// queue (channel). Arguments are handled in the manner of fmt.Printf. +func (logger Logger) Logf(lvl Level, format string, args ...interface{}) { + status := logger.logr.IsLevelEnabled(lvl) + if status.Enabled { + rec := NewLogRec(lvl, logger, format, args, status.Stacktrace) + logger.logr.enqueue(rec) + } +} + +// Tracef is a convenience method equivalent to `Logf(TraceLevel, args...)`. +func (logger Logger) Tracef(format string, args ...interface{}) { + logger.Logf(Trace, format, args...) +} + +// Debugf is a convenience method equivalent to `Logf(DebugLevel, args...)`. +func (logger Logger) Debugf(format string, args ...interface{}) { + logger.Logf(Debug, format, args...) +} + +// Infof is a convenience method equivalent to `Logf(InfoLevel, args...)`. +func (logger Logger) Infof(format string, args ...interface{}) { + logger.Logf(Info, format, args...) +} + +// Printf ensures compatibility with std lib logger. +func (logger Logger) Printf(format string, args ...interface{}) { + logger.Infof(format, args...) +} + +// Warnf is a convenience method equivalent to `Logf(WarnLevel, args...)`. +func (logger Logger) Warnf(format string, args ...interface{}) { + logger.Logf(Warn, format, args...) +} + +// Errorf is a convenience method equivalent to `Logf(ErrorLevel, args...)`. +func (logger Logger) Errorf(format string, args ...interface{}) { + logger.Logf(Error, format, args...) +} + +// Fatalf is a convenience method equivalent to `Logf(FatalLevel, args...)` +// followed by a call to os.Exit(1). +func (logger Logger) Fatalf(format string, args ...interface{}) { + logger.Logf(Fatal, format, args...) + logger.logr.exit(1) +} + +// Panicf is a convenience method equivalent to `Logf(PanicLevel, args...)` +// followed by a call to panic(). +func (logger Logger) Panicf(format string, args ...interface{}) { + logger.Logf(Panic, format, args...) +} + +// +// Println style +// + +// Logln checks that the level matches one or more targets, and +// if so, generates a log record that is added to the main +// queue (channel). Arguments are handled in the manner of fmt.Println. +func (logger Logger) Logln(lvl Level, args ...interface{}) { + status := logger.logr.IsLevelEnabled(lvl) + if status.Enabled { + rec := NewLogRec(lvl, logger, "", args, status.Stacktrace) + rec.newline = true + logger.logr.enqueue(rec) + } +} + +// Traceln is a convenience method equivalent to `Logln(TraceLevel, args...)`. +func (logger Logger) Traceln(args ...interface{}) { + logger.Logln(Trace, args...) +} + +// Debugln is a convenience method equivalent to `Logln(DebugLevel, args...)`. +func (logger Logger) Debugln(args ...interface{}) { + logger.Logln(Debug, args...) +} + +// Infoln is a convenience method equivalent to `Logln(InfoLevel, args...)`. +func (logger Logger) Infoln(args ...interface{}) { + logger.Logln(Info, args...) +} + +// Println ensures compatibility with std lib logger. +func (logger Logger) Println(args ...interface{}) { + logger.Infoln(args...) +} + +// Warnln is a convenience method equivalent to `Logln(WarnLevel, args...)`. +func (logger Logger) Warnln(args ...interface{}) { + logger.Logln(Warn, args...) +} + +// Errorln is a convenience method equivalent to `Logln(ErrorLevel, args...)`. +func (logger Logger) Errorln(args ...interface{}) { + logger.Logln(Error, args...) +} + +// Fatalln is a convenience method equivalent to `Logln(FatalLevel, args...)` +// followed by a call to os.Exit(1). +func (logger Logger) Fatalln(args ...interface{}) { + logger.Logln(Fatal, args...) + logger.logr.exit(1) +} + +// Panicln is a convenience method equivalent to `Logln(PanicLevel, args...)` +// followed by a call to panic(). +func (logger Logger) Panicln(args ...interface{}) { + logger.Logln(Panic, args...) +} diff --git a/vendor/github.com/mattermost/logr/logr.go b/vendor/github.com/mattermost/logr/logr.go new file mode 100644 index 00000000..631366a5 --- /dev/null +++ b/vendor/github.com/mattermost/logr/logr.go @@ -0,0 +1,664 @@ +package logr + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "sync" + "time" + + "github.com/wiggin77/cfg" + "github.com/wiggin77/merror" +) + +// Logr maintains a list of log targets and accepts incoming +// log records. +type Logr struct { + tmux sync.RWMutex // target mutex + targets []Target + + mux sync.RWMutex + maxQueueSizeActual int + in chan *LogRec + done chan struct{} + once sync.Once + shutdown bool + lvlCache levelCache + + metricsInitOnce sync.Once + metricsCloseOnce sync.Once + metricsDone chan struct{} + metrics MetricsCollector + queueSizeGauge Gauge + loggedCounter Counter + errorCounter Counter + + bufferPool sync.Pool + + // MaxQueueSize is the maximum number of log records that can be queued. + // If exceeded, `OnQueueFull` is called which determines if the log + // record will be dropped or block until add is successful. + // If this is modified, it must be done before `Configure` or + // `AddTarget`. Defaults to DefaultMaxQueueSize. + MaxQueueSize int + + // OnLoggerError, when not nil, is called any time an internal + // logging error occurs. For example, this can happen when a + // target cannot connect to its data sink. + OnLoggerError func(error) + + // OnQueueFull, when not nil, is called on an attempt to add + // a log record to a full Logr queue. + // `MaxQueueSize` can be used to modify the maximum queue size. + // This function should return quickly, with a bool indicating whether + // the log record should be dropped (true) or block until the log record + // is successfully added (false). If nil then blocking (false) is assumed. + OnQueueFull func(rec *LogRec, maxQueueSize int) bool + + // OnTargetQueueFull, when not nil, is called on an attempt to add + // a log record to a full target queue provided the target supports reporting + // this condition. + // This function should return quickly, with a bool indicating whether + // the log record should be dropped (true) or block until the log record + // is successfully added (false). If nil then blocking (false) is assumed. + OnTargetQueueFull func(target Target, rec *LogRec, maxQueueSize int) bool + + // OnExit, when not nil, is called when a FatalXXX style log API is called. + // When nil, then the default behavior is to cleanly shut down this Logr and + // call `os.Exit(code)`. + OnExit func(code int) + + // OnPanic, when not nil, is called when a PanicXXX style log API is called. + // When nil, then the default behavior is to cleanly shut down this Logr and + // call `panic(err)`. + OnPanic func(err interface{}) + + // EnqueueTimeout is the amount of time a log record can take to be queued. + // This only applies to blocking enqueue which happen after `logr.OnQueueFull` + // is called and returns false. + EnqueueTimeout time.Duration + + // ShutdownTimeout is the amount of time `logr.Shutdown` can execute before + // timing out. + ShutdownTimeout time.Duration + + // FlushTimeout is the amount of time `logr.Flush` can execute before + // timing out. + FlushTimeout time.Duration + + // UseSyncMapLevelCache can be set to true before the first target is added + // when high concurrency (e.g. >32 cores) is expected. This may improve + // performance with large numbers of cores - benchmark for your use case. + UseSyncMapLevelCache bool + + // MaxPooledFormatBuffer determines the maximum size of a buffer that can be + // pooled. To reduce allocations, the buffers needed during formatting (etc) + // are pooled. A very large log item will grow a buffer that could stay in + // memory indefinitely. This settings lets you control how big a pooled buffer + // can be - anything larger will be garbage collected after use. + // Defaults to 1MB. + MaxPooledBuffer int + + // DisableBufferPool when true disables the buffer pool. See MaxPooledBuffer. + DisableBufferPool bool + + // MetricsUpdateFreqMillis determines how often polled metrics are updated + // when metrics are enabled. + MetricsUpdateFreqMillis int64 +} + +// Configure adds/removes targets via the supplied `Config`. +func (logr *Logr) Configure(config *cfg.Config) error { + // TODO + return fmt.Errorf("not implemented yet") +} + +func (logr *Logr) ensureInit() { + logr.once.Do(func() { + defer func() { + go logr.start() + }() + + logr.mux.Lock() + defer logr.mux.Unlock() + + logr.maxQueueSizeActual = logr.MaxQueueSize + if logr.maxQueueSizeActual == 0 { + logr.maxQueueSizeActual = DefaultMaxQueueSize + } + + if logr.maxQueueSizeActual < 0 { + logr.maxQueueSizeActual = 0 + } + + logr.in = make(chan *LogRec, logr.maxQueueSizeActual) + logr.done = make(chan struct{}) + + if logr.UseSyncMapLevelCache { + logr.lvlCache = &syncMapLevelCache{} + } else { + logr.lvlCache = &arrayLevelCache{} + } + + if logr.MaxPooledBuffer == 0 { + logr.MaxPooledBuffer = DefaultMaxPooledBuffer + } + logr.bufferPool = sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, + } + + logr.lvlCache.setup() + }) +} + +// AddTarget adds one or more targets to the logger which will receive +// log records for outputting. +func (logr *Logr) AddTarget(targets ...Target) error { + if logr.IsShutdown() { + return fmt.Errorf("AddTarget called after Logr shut down") + } + + logr.ensureInit() + metrics := logr.getMetricsCollector() + defer logr.ResetLevelCache() // call this after tmux is released + + logr.tmux.Lock() + defer logr.tmux.Unlock() + + errs := merror.New() + for _, t := range targets { + if t == nil { + continue + } + + logr.targets = append(logr.targets, t) + if metrics != nil { + if tm, ok := t.(TargetWithMetrics); ok { + if err := tm.EnableMetrics(metrics, logr.MetricsUpdateFreqMillis); err != nil { + errs.Append(err) + } + } + } + } + return errs.ErrorOrNil() +} + +// NewLogger creates a Logger using defaults. A `Logger` is light-weight +// enough to create on-demand, but typically one or more Loggers are +// created and re-used. +func (logr *Logr) NewLogger() Logger { + logger := Logger{logr: logr} + return logger +} + +var levelStatusDisabled = LevelStatus{} + +// IsLevelEnabled returns true if at least one target has the specified +// level enabled. The result is cached so that subsequent checks are fast. +func (logr *Logr) IsLevelEnabled(lvl Level) LevelStatus { + status, ok := logr.isLevelEnabledFromCache(lvl) + if ok { + return status + } + + // Check each target. + logr.tmux.RLock() + for _, t := range logr.targets { + e, s := t.IsLevelEnabled(lvl) + if e { + status.Enabled = true + if s { + status.Stacktrace = true + break // if both enabled then no sense checking more targets + } + } + } + logr.tmux.RUnlock() + + // Cache and return the result. + if err := logr.updateLevelCache(lvl.ID, status); err != nil { + logr.ReportError(err) + return LevelStatus{} + } + return status +} + +func (logr *Logr) isLevelEnabledFromCache(lvl Level) (LevelStatus, bool) { + logr.mux.RLock() + defer logr.mux.RUnlock() + + // Don't accept new log records after shutdown. + if logr.shutdown { + return levelStatusDisabled, true + } + + // Check cache. lvlCache may still be nil if no targets added. + if logr.lvlCache == nil { + return levelStatusDisabled, true + } + status, ok := logr.lvlCache.get(lvl.ID) + if ok { + return status, true + } + return LevelStatus{}, false +} + +func (logr *Logr) updateLevelCache(id LevelID, status LevelStatus) error { + logr.mux.RLock() + defer logr.mux.RUnlock() + if logr.lvlCache != nil { + return logr.lvlCache.put(id, status) + } + return nil +} + +// HasTargets returns true only if at least one target exists within the Logr. +func (logr *Logr) HasTargets() bool { + logr.tmux.RLock() + defer logr.tmux.RUnlock() + return len(logr.targets) > 0 +} + +// TargetInfo provides name and type for a Target. +type TargetInfo struct { + Name string + Type string +} + +// TargetInfos enumerates all the targets added to this Logr. +// The resulting slice represents a snapshot at time of calling. +func (logr *Logr) TargetInfos() []TargetInfo { + logr.tmux.RLock() + defer logr.tmux.RUnlock() + + infos := make([]TargetInfo, 0) + + for _, t := range logr.targets { + inf := TargetInfo{ + Name: fmt.Sprintf("%v", t), + Type: fmt.Sprintf("%T", t), + } + infos = append(infos, inf) + } + return infos +} + +// RemoveTargets safely removes one or more targets based on the filtering method. +// f should return true to delete the target, false to keep it. +// When removing a target, best effort is made to write any queued log records before +// closing, with cxt determining how much time can be spent in total. +// Note, keep the timeout short since this method blocks certain logging operations. +func (logr *Logr) RemoveTargets(cxt context.Context, f func(ti TargetInfo) bool) error { + var removed bool + defer func() { + if removed { + // call this after tmux is released since + // it will lock mux and we don't want to + // introduce possible deadlock. + logr.ResetLevelCache() + } + }() + + errs := merror.New() + + logr.tmux.Lock() + defer logr.tmux.Unlock() + + cp := make([]Target, 0) + + for _, t := range logr.targets { + inf := TargetInfo{ + Name: fmt.Sprintf("%v", t), + Type: fmt.Sprintf("%T", t), + } + if f(inf) { + if err := t.Shutdown(cxt); err != nil { + errs.Append(err) + } + removed = true + } else { + cp = append(cp, t) + } + } + logr.targets = cp + return errs.ErrorOrNil() +} + +// ResetLevelCache resets the cached results of `IsLevelEnabled`. This is +// called any time a Target is added or a target's level is changed. +func (logr *Logr) ResetLevelCache() { + // Write lock so that new cache entries cannot be stored while we + // clear the cache. + logr.mux.Lock() + defer logr.mux.Unlock() + logr.resetLevelCache() +} + +// resetLevelCache empties the level cache without locking. +// mux.Lock must be held before calling this function. +func (logr *Logr) resetLevelCache() { + // lvlCache may still be nil if no targets added. + if logr.lvlCache != nil { + logr.lvlCache.clear() + } +} + +// enqueue adds a log record to the logr queue. If the queue is full then +// this function either blocks or the log record is dropped, depending on +// the result of calling `OnQueueFull`. +func (logr *Logr) enqueue(rec *LogRec) { + if logr.in == nil { + logr.ReportError(fmt.Errorf("AddTarget or Configure must be called before enqueue")) + } + + select { + case logr.in <- rec: + default: + if logr.OnQueueFull != nil && logr.OnQueueFull(rec, logr.maxQueueSizeActual) { + return // drop the record + } + select { + case <-time.After(logr.enqueueTimeout()): + logr.ReportError(fmt.Errorf("enqueue timed out for log rec [%v]", rec)) + case logr.in <- rec: // block until success or timeout + } + } +} + +// exit is called by one of the FatalXXX style APIS. If `logr.OnExit` is not nil +// then that method is called, otherwise the default behavior is to shut down this +// Logr cleanly then call `os.Exit(code)`. +func (logr *Logr) exit(code int) { + if logr.OnExit != nil { + logr.OnExit(code) + return + } + + if err := logr.Shutdown(); err != nil { + logr.ReportError(err) + } + os.Exit(code) +} + +// panic is called by one of the PanicXXX style APIS. If `logr.OnPanic` is not nil +// then that method is called, otherwise the default behavior is to shut down this +// Logr cleanly then call `panic(err)`. +func (logr *Logr) panic(err interface{}) { + if logr.OnPanic != nil { + logr.OnPanic(err) + return + } + + if err := logr.Shutdown(); err != nil { + logr.ReportError(err) + } + panic(err) +} + +// Flush blocks while flushing the logr queue and all target queues, by +// writing existing log records to valid targets. +// Any attempts to add new log records will block until flush is complete. +// `logr.FlushTimeout` determines how long flush can execute before +// timing out. Use `IsTimeoutError` to determine if the returned error is +// due to a timeout. +func (logr *Logr) Flush() error { + ctx, cancel := context.WithTimeout(context.Background(), logr.flushTimeout()) + defer cancel() + return logr.FlushWithTimeout(ctx) +} + +// Flush blocks while flushing the logr queue and all target queues, by +// writing existing log records to valid targets. +// Any attempts to add new log records will block until flush is complete. +// Use `IsTimeoutError` to determine if the returned error is +// due to a timeout. +func (logr *Logr) FlushWithTimeout(ctx context.Context) error { + if !logr.HasTargets() { + return nil + } + + if logr.IsShutdown() { + return errors.New("Flush called on shut down Logr") + } + + rec := newFlushLogRec(logr.NewLogger()) + logr.enqueue(rec) + + select { + case <-ctx.Done(): + return newTimeoutError("logr queue shutdown timeout") + case <-rec.flush: + } + return nil +} + +// IsShutdown returns true if this Logr instance has been shut down. +// No further log records can be enqueued and no targets added after +// shutdown. +func (logr *Logr) IsShutdown() bool { + logr.mux.Lock() + defer logr.mux.Unlock() + return logr.shutdown +} + +// Shutdown cleanly stops the logging engine after making best efforts +// to flush all targets. Call this function right before application +// exit - logr cannot be restarted once shut down. +// `logr.ShutdownTimeout` determines how long shutdown can execute before +// timing out. Use `IsTimeoutError` to determine if the returned error is +// due to a timeout. +func (logr *Logr) Shutdown() error { + ctx, cancel := context.WithTimeout(context.Background(), logr.shutdownTimeout()) + defer cancel() + return logr.ShutdownWithTimeout(ctx) +} + +// Shutdown cleanly stops the logging engine after making best efforts +// to flush all targets. Call this function right before application +// exit - logr cannot be restarted once shut down. +// Use `IsTimeoutError` to determine if the returned error is due to a +// timeout. +func (logr *Logr) ShutdownWithTimeout(ctx context.Context) error { + logr.mux.Lock() + if logr.shutdown { + logr.mux.Unlock() + return errors.New("Shutdown called again after shut down") + } + logr.shutdown = true + logr.resetLevelCache() + logr.mux.Unlock() + + logr.metricsCloseOnce.Do(func() { + if logr.metricsDone != nil { + close(logr.metricsDone) + } + }) + + errs := merror.New() + + // close the incoming channel and wait for read loop to exit. + if logr.in != nil { + close(logr.in) + select { + case <-ctx.Done(): + errs.Append(newTimeoutError("logr queue shutdown timeout")) + case <-logr.done: + } + } + + // logr.in channel should now be drained to targets and no more log records + // can be added. + logr.tmux.RLock() + defer logr.tmux.RUnlock() + for _, t := range logr.targets { + err := t.Shutdown(ctx) + if err != nil { + errs.Append(err) + } + } + return errs.ErrorOrNil() +} + +// ReportError is used to notify the host application of any internal logging errors. +// If `OnLoggerError` is not nil, it is called with the error, otherwise the error is +// output to `os.Stderr`. +func (logr *Logr) ReportError(err interface{}) { + logr.incErrorCounter() + + if logr.OnLoggerError == nil { + fmt.Fprintln(os.Stderr, err) + return + } + logr.OnLoggerError(fmt.Errorf("%v", err)) +} + +// BorrowBuffer borrows a buffer from the pool. Release the buffer to reduce garbage collection. +func (logr *Logr) BorrowBuffer() *bytes.Buffer { + if logr.DisableBufferPool { + return &bytes.Buffer{} + } + return logr.bufferPool.Get().(*bytes.Buffer) +} + +// ReleaseBuffer returns a buffer to the pool to reduce garbage collection. The buffer is only +// retained if less than MaxPooledBuffer. +func (logr *Logr) ReleaseBuffer(buf *bytes.Buffer) { + if !logr.DisableBufferPool && buf.Cap() < logr.MaxPooledBuffer { + buf.Reset() + logr.bufferPool.Put(buf) + } +} + +// enqueueTimeout returns amount of time a log record can take to be queued. +// This only applies to blocking enqueue which happen after `logr.OnQueueFull` is called +// and returns false. +func (logr *Logr) enqueueTimeout() time.Duration { + if logr.EnqueueTimeout == 0 { + return DefaultEnqueueTimeout + } + return logr.EnqueueTimeout +} + +// shutdownTimeout returns the timeout duration for `logr.Shutdown`. +func (logr *Logr) shutdownTimeout() time.Duration { + if logr.ShutdownTimeout == 0 { + return DefaultShutdownTimeout + } + return logr.ShutdownTimeout +} + +// flushTimeout returns the timeout duration for `logr.Flush`. +func (logr *Logr) flushTimeout() time.Duration { + if logr.FlushTimeout == 0 { + return DefaultFlushTimeout + } + return logr.FlushTimeout +} + +// start selects on incoming log records until done channel signals. +// Incoming log records are fanned out to all log targets. +func (logr *Logr) start() { + defer func() { + if r := recover(); r != nil { + logr.ReportError(r) + go logr.start() + } + }() + + for rec := range logr.in { + if rec.flush != nil { + logr.flush(rec.flush) + } else { + rec.prep() + logr.fanout(rec) + } + } + close(logr.done) +} + +// startMetricsUpdater updates the metrics for any polled values every `MetricsUpdateFreqSecs` seconds until +// logr is closed. +func (logr *Logr) startMetricsUpdater() { + for { + updateFreq := logr.getMetricsUpdateFreqMillis() + if updateFreq == 0 { + updateFreq = DefMetricsUpdateFreqMillis + } + if updateFreq < 250 { + updateFreq = 250 // don't peg the CPU + } + + select { + case <-logr.metricsDone: + return + case <-time.After(time.Duration(updateFreq) * time.Millisecond): + logr.setQueueSizeGauge(float64(len(logr.in))) + } + } +} + +func (logr *Logr) getMetricsUpdateFreqMillis() int64 { + logr.mux.RLock() + defer logr.mux.RUnlock() + return logr.MetricsUpdateFreqMillis +} + +// fanout pushes a LogRec to all targets. +func (logr *Logr) fanout(rec *LogRec) { + var target Target + defer func() { + if r := recover(); r != nil { + logr.ReportError(fmt.Errorf("fanout failed for target %s, %v", target, r)) + } + }() + + var logged bool + defer func() { + if logged { + logr.incLoggedCounter() // call this after tmux is released + } + }() + + logr.tmux.RLock() + defer logr.tmux.RUnlock() + for _, target = range logr.targets { + if enabled, _ := target.IsLevelEnabled(rec.Level()); enabled { + target.Log(rec) + logged = true + } + } +} + +// flush drains the queue and notifies when done. +func (logr *Logr) flush(done chan<- struct{}) { + // first drain the logr queue. +loop: + for { + var rec *LogRec + select { + case rec = <-logr.in: + if rec.flush == nil { + rec.prep() + logr.fanout(rec) + } + default: + break loop + } + } + + logger := logr.NewLogger() + + // drain all the targets; block until finished. + logr.tmux.RLock() + defer logr.tmux.RUnlock() + for _, target := range logr.targets { + rec := newFlushLogRec(logger) + target.Log(rec) + <-rec.flush + } + done <- struct{}{} +} diff --git a/vendor/github.com/mattermost/logr/logrec.go b/vendor/github.com/mattermost/logr/logrec.go new file mode 100644 index 00000000..9428aaec --- /dev/null +++ b/vendor/github.com/mattermost/logr/logrec.go @@ -0,0 +1,189 @@ +package logr + +import ( + "fmt" + "runtime" + "strings" + "sync" + "time" +) + +var ( + logrPkg string +) + +func init() { + // Calc current package name + pcs := make([]uintptr, 2) + _ = runtime.Callers(0, pcs) + tmp := runtime.FuncForPC(pcs[1]).Name() + logrPkg = getPackageName(tmp) +} + +// LogRec collects raw, unformatted data to be logged. +// TODO: pool these? how to reliably know when targets are done with them? Copy for each target? +type LogRec struct { + mux sync.RWMutex + time time.Time + + level Level + logger Logger + + template string + newline bool + args []interface{} + + stackPC []uintptr + stackCount int + + // flushes Logr and target queues when not nil. + flush chan struct{} + + // remaining fields calculated by `prep` + msg string + frames []runtime.Frame +} + +// NewLogRec creates a new LogRec with the current time and optional stack trace. +func NewLogRec(lvl Level, logger Logger, template string, args []interface{}, incStacktrace bool) *LogRec { + rec := &LogRec{time: time.Now(), logger: logger, level: lvl, template: template, args: args} + if incStacktrace { + rec.stackPC = make([]uintptr, DefaultMaxStackFrames) + rec.stackCount = runtime.Callers(2, rec.stackPC) + } + return rec +} + +// newFlushLogRec creates a LogRec that flushes the Logr queue and +// any target queues that support flushing. +func newFlushLogRec(logger Logger) *LogRec { + return &LogRec{logger: logger, flush: make(chan struct{})} +} + +// prep resolves all args and field values to strings, and +// resolves stack trace to frames. +func (rec *LogRec) prep() { + rec.mux.Lock() + defer rec.mux.Unlock() + + // resolve args + if rec.template == "" { + if rec.newline { + rec.msg = fmt.Sprintln(rec.args...) + } else { + rec.msg = fmt.Sprint(rec.args...) + } + } else { + rec.msg = fmt.Sprintf(rec.template, rec.args...) + } + + // resolve stack trace + if rec.stackCount > 0 { + frames := runtime.CallersFrames(rec.stackPC[:rec.stackCount]) + for { + f, more := frames.Next() + rec.frames = append(rec.frames, f) + if !more { + break + } + } + + // remove leading logr package entries. + var start int + for i, frame := range rec.frames { + pkg := getPackageName(frame.Function) + if pkg != "" && pkg != logrPkg { + start = i + break + } + } + rec.frames = rec.frames[start:] + } +} + +// WithTime returns a shallow copy of the log record while replacing +// the time. This can be used by targets and formatters to adjust +// the time, or take ownership of the log record. +func (rec *LogRec) WithTime(time time.Time) *LogRec { + rec.mux.RLock() + defer rec.mux.RUnlock() + + return &LogRec{ + time: time, + level: rec.level, + logger: rec.logger, + template: rec.template, + newline: rec.newline, + args: rec.args, + msg: rec.msg, + stackPC: rec.stackPC, + stackCount: rec.stackCount, + frames: rec.frames, + } +} + +// Logger returns the `Logger` that created this `LogRec`. +func (rec *LogRec) Logger() Logger { + return rec.logger +} + +// Time returns this log record's time stamp. +func (rec *LogRec) Time() time.Time { + // no locking needed as this field is not mutated. + return rec.time +} + +// Level returns this log record's Level. +func (rec *LogRec) Level() Level { + // no locking needed as this field is not mutated. + return rec.level +} + +// Fields returns this log record's Fields. +func (rec *LogRec) Fields() Fields { + // no locking needed as this field is not mutated. + return rec.logger.fields +} + +// Msg returns this log record's message text. +func (rec *LogRec) Msg() string { + rec.mux.RLock() + defer rec.mux.RUnlock() + return rec.msg +} + +// StackFrames returns this log record's stack frames or +// nil if no stack trace was required. +func (rec *LogRec) StackFrames() []runtime.Frame { + rec.mux.RLock() + defer rec.mux.RUnlock() + return rec.frames +} + +// String returns a string representation of this log record. +func (rec *LogRec) String() string { + if rec.flush != nil { + return "[flusher]" + } + + f := &DefaultFormatter{} + buf := rec.logger.logr.BorrowBuffer() + defer rec.logger.logr.ReleaseBuffer(buf) + buf, _ = f.Format(rec, true, buf) + return strings.TrimSpace(buf.String()) +} + +// getPackageName reduces a fully qualified function name to the package name +// By sirupsen: https://github.com/sirupsen/logrus/blob/master/entry.go +func getPackageName(f string) string { + for { + lastPeriod := strings.LastIndex(f, ".") + lastSlash := strings.LastIndex(f, "/") + if lastPeriod > lastSlash { + f = f[:lastPeriod] + } else { + break + } + } + return f +} diff --git a/vendor/github.com/mattermost/logr/metrics.go b/vendor/github.com/mattermost/logr/metrics.go new file mode 100644 index 00000000..24fe22b6 --- /dev/null +++ b/vendor/github.com/mattermost/logr/metrics.go @@ -0,0 +1,117 @@ +package logr + +import ( + "errors" + + "github.com/wiggin77/merror" +) + +const ( + DefMetricsUpdateFreqMillis = 15000 // 15 seconds +) + +// Counter is a simple metrics sink that can only increment a value. +// Implementations are external to Logr and provided via `MetricsCollector`. +type Counter interface { + // Inc increments the counter by 1. Use Add to increment it by arbitrary non-negative values. + Inc() + // Add adds the given value to the counter. It panics if the value is < 0. + Add(float64) +} + +// Gauge is a simple metrics sink that can receive values and increase or decrease. +// Implementations are external to Logr and provided via `MetricsCollector`. +type Gauge interface { + // Set sets the Gauge to an arbitrary value. + Set(float64) + // Add adds the given value to the Gauge. (The value can be negative, resulting in a decrease of the Gauge.) + Add(float64) + // Sub subtracts the given value from the Gauge. (The value can be negative, resulting in an increase of the Gauge.) + Sub(float64) +} + +// MetricsCollector provides a way for users of this Logr package to have metrics pushed +// in an efficient way to any backend, e.g. Prometheus. +// For each target added to Logr, the supplied MetricsCollector will provide a Gauge +// and Counters that will be called frequently as logging occurs. +type MetricsCollector interface { + // QueueSizeGauge returns a Gauge that will be updated by the named target. + QueueSizeGauge(target string) (Gauge, error) + // LoggedCounter returns a Counter that will be incremented by the named target. + LoggedCounter(target string) (Counter, error) + // ErrorCounter returns a Counter that will be incremented by the named target. + ErrorCounter(target string) (Counter, error) + // DroppedCounter returns a Counter that will be incremented by the named target. + DroppedCounter(target string) (Counter, error) + // BlockedCounter returns a Counter that will be incremented by the named target. + BlockedCounter(target string) (Counter, error) +} + +// TargetWithMetrics is a target that provides metrics. +type TargetWithMetrics interface { + EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error +} + +func (logr *Logr) getMetricsCollector() MetricsCollector { + logr.mux.RLock() + defer logr.mux.RUnlock() + return logr.metrics +} + +// SetMetricsCollector enables metrics collection by supplying a MetricsCollector. +// The MetricsCollector provides counters and gauges that are updated by log targets. +func (logr *Logr) SetMetricsCollector(collector MetricsCollector) error { + if collector == nil { + return errors.New("collector cannot be nil") + } + + logr.mux.Lock() + logr.metrics = collector + logr.queueSizeGauge, _ = collector.QueueSizeGauge("_logr") + logr.loggedCounter, _ = collector.LoggedCounter("_logr") + logr.errorCounter, _ = collector.ErrorCounter("_logr") + logr.mux.Unlock() + + logr.metricsInitOnce.Do(func() { + logr.metricsDone = make(chan struct{}) + go logr.startMetricsUpdater() + }) + + merr := merror.New() + + logr.tmux.RLock() + defer logr.tmux.RUnlock() + for _, target := range logr.targets { + if tm, ok := target.(TargetWithMetrics); ok { + if err := tm.EnableMetrics(collector, logr.MetricsUpdateFreqMillis); err != nil { + merr.Append(err) + } + } + + } + return merr.ErrorOrNil() +} + +func (logr *Logr) setQueueSizeGauge(val float64) { + logr.mux.RLock() + defer logr.mux.RUnlock() + if logr.queueSizeGauge != nil { + logr.queueSizeGauge.Set(val) + } +} + +func (logr *Logr) incLoggedCounter() { + logr.mux.RLock() + defer logr.mux.RUnlock() + if logr.loggedCounter != nil { + logr.loggedCounter.Inc() + } +} + +func (logr *Logr) incErrorCounter() { + logr.mux.RLock() + defer logr.mux.RUnlock() + if logr.errorCounter != nil { + logr.errorCounter.Inc() + } +} diff --git a/vendor/github.com/mattermost/logr/target.go b/vendor/github.com/mattermost/logr/target.go new file mode 100644 index 00000000..f8e7bf75 --- /dev/null +++ b/vendor/github.com/mattermost/logr/target.go @@ -0,0 +1,299 @@ +package logr + +import ( + "context" + "fmt" + "os" + "sync" + "time" +) + +// Target represents a destination for log records such as file, +// database, TCP socket, etc. +type Target interface { + // SetName provides an optional name for the target. + SetName(name string) + + // IsLevelEnabled returns true if this target should emit + // logs for the specified level. Also determines if + // a stack trace is required. + IsLevelEnabled(Level) (enabled bool, stacktrace bool) + + // Formatter returns the Formatter associated with this Target. + Formatter() Formatter + + // Log outputs the log record to this target's destination. + Log(rec *LogRec) + + // Shutdown makes best effort to flush target queue and + // frees/closes all resources. + Shutdown(ctx context.Context) error +} + +// RecordWriter can convert a LogRecord to bytes and output to some data sink. +type RecordWriter interface { + Write(rec *LogRec) error +} + +// Basic provides the basic functionality of a Target that can be used +// to more easily compose your own Targets. To use, just embed Basic +// in your target type, implement `RecordWriter`, and call `(*Basic).Start`. +type Basic struct { + target Target + + filter Filter + formatter Formatter + + in chan *LogRec + done chan struct{} + w RecordWriter + + mux sync.RWMutex + name string + + metrics bool + queueSizeGauge Gauge + loggedCounter Counter + errorCounter Counter + droppedCounter Counter + blockedCounter Counter + + metricsUpdateFreqMillis int64 +} + +// Start initializes this target helper and starts accepting log records for processing. +func (b *Basic) Start(target Target, rw RecordWriter, filter Filter, formatter Formatter, maxQueued int) { + if filter == nil { + filter = &StdFilter{Lvl: Fatal} + } + if formatter == nil { + formatter = &DefaultFormatter{} + } + + b.target = target + b.filter = filter + b.formatter = formatter + b.in = make(chan *LogRec, maxQueued) + b.done = make(chan struct{}, 1) + b.w = rw + go b.start() + + if b.hasMetrics() { + go b.startMetricsUpdater() + } +} + +func (b *Basic) SetName(name string) { + b.mux.Lock() + defer b.mux.Unlock() + b.name = name +} + +// IsLevelEnabled returns true if this target should emit +// logs for the specified level. Also determines if +// a stack trace is required. +func (b *Basic) IsLevelEnabled(lvl Level) (enabled bool, stacktrace bool) { + return b.filter.IsEnabled(lvl), b.filter.IsStacktraceEnabled(lvl) +} + +// Formatter returns the Formatter associated with this Target. +func (b *Basic) Formatter() Formatter { + return b.formatter +} + +// Shutdown stops processing log records after making best +// effort to flush queue. +func (b *Basic) Shutdown(ctx context.Context) error { + // close the incoming channel and wait for read loop to exit. + close(b.in) + select { + case <-ctx.Done(): + case <-b.done: + } + + // b.in channel should now be drained. + return nil +} + +// Log outputs the log record to this targets destination. +func (b *Basic) Log(rec *LogRec) { + lgr := rec.Logger().Logr() + select { + case b.in <- rec: + default: + handler := lgr.OnTargetQueueFull + if handler != nil && handler(b.target, rec, cap(b.in)) { + b.incDroppedCounter() + return // drop the record + } + b.incBlockedCounter() + + select { + case <-time.After(lgr.enqueueTimeout()): + lgr.ReportError(fmt.Errorf("target enqueue timeout for log rec [%v]", rec)) + case b.in <- rec: // block until success or timeout + } + } +} + +// Metrics enables metrics collection using the provided MetricsCollector. +func (b *Basic) EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error { + name := fmt.Sprintf("%v", b) + + b.mux.Lock() + defer b.mux.Unlock() + + b.metrics = true + b.metricsUpdateFreqMillis = updateFreqMillis + + var err error + + if b.queueSizeGauge, err = collector.QueueSizeGauge(name); err != nil { + return err + } + if b.loggedCounter, err = collector.LoggedCounter(name); err != nil { + return err + } + if b.errorCounter, err = collector.ErrorCounter(name); err != nil { + return err + } + if b.droppedCounter, err = collector.DroppedCounter(name); err != nil { + return err + } + if b.blockedCounter, err = collector.BlockedCounter(name); err != nil { + return err + } + return nil +} + +func (b *Basic) hasMetrics() bool { + b.mux.RLock() + defer b.mux.RUnlock() + return b.metrics +} + +func (b *Basic) setQueueSizeGauge(val float64) { + b.mux.RLock() + defer b.mux.RUnlock() + if b.queueSizeGauge != nil { + b.queueSizeGauge.Set(val) + } +} + +func (b *Basic) incLoggedCounter() { + b.mux.RLock() + defer b.mux.RUnlock() + if b.loggedCounter != nil { + b.loggedCounter.Inc() + } +} + +func (b *Basic) incErrorCounter() { + b.mux.RLock() + defer b.mux.RUnlock() + if b.errorCounter != nil { + b.errorCounter.Inc() + } +} + +func (b *Basic) incDroppedCounter() { + b.mux.RLock() + defer b.mux.RUnlock() + if b.droppedCounter != nil { + b.droppedCounter.Inc() + } +} + +func (b *Basic) incBlockedCounter() { + b.mux.RLock() + defer b.mux.RUnlock() + if b.blockedCounter != nil { + b.blockedCounter.Inc() + } +} + +// String returns a name for this target. Use `SetName` to specify a name. +func (b *Basic) String() string { + b.mux.RLock() + defer b.mux.RUnlock() + + if b.name != "" { + return b.name + } + return fmt.Sprintf("%T", b.target) +} + +// Start accepts log records via In channel and writes to the +// supplied writer, until Done channel signaled. +func (b *Basic) start() { + defer func() { + if r := recover(); r != nil { + fmt.Fprintln(os.Stderr, "Basic.start -- ", r) + go b.start() + } + }() + + for rec := range b.in { + if rec.flush != nil { + b.flush(rec.flush) + } else { + err := b.w.Write(rec) + if err != nil { + b.incErrorCounter() + rec.Logger().Logr().ReportError(err) + } else { + b.incLoggedCounter() + } + } + } + close(b.done) +} + +// startMetricsUpdater updates the metrics for any polled values every `MetricsUpdateFreqSecs` seconds until +// target is closed. +func (b *Basic) startMetricsUpdater() { + for { + updateFreq := b.getMetricsUpdateFreqMillis() + if updateFreq == 0 { + updateFreq = DefMetricsUpdateFreqMillis + } + if updateFreq < 250 { + updateFreq = 250 // don't peg the CPU + } + + select { + case <-b.done: + return + case <-time.After(time.Duration(updateFreq) * time.Millisecond): + b.setQueueSizeGauge(float64(len(b.in))) + } + } +} + +func (b *Basic) getMetricsUpdateFreqMillis() int64 { + b.mux.RLock() + defer b.mux.RUnlock() + return b.metricsUpdateFreqMillis +} + +// flush drains the queue and notifies when done. +func (b *Basic) flush(done chan<- struct{}) { + for { + var rec *LogRec + var err error + select { + case rec = <-b.in: + // ignore any redundant flush records. + if rec.flush == nil { + err = b.w.Write(rec) + if err != nil { + b.incErrorCounter() + rec.Logger().Logr().ReportError(err) + } + } + default: + done <- struct{}{} + return + } + } +} diff --git a/vendor/github.com/mattermost/logr/target/file.go b/vendor/github.com/mattermost/logr/target/file.go new file mode 100644 index 00000000..0fd50768 --- /dev/null +++ b/vendor/github.com/mattermost/logr/target/file.go @@ -0,0 +1,87 @@ +package target + +import ( + "context" + "io" + + "github.com/mattermost/logr" + "github.com/wiggin77/merror" + "gopkg.in/natefinch/lumberjack.v2" +) + +type FileOptions struct { + // Filename is the file to write logs to. Backup log files will be retained + // in the same directory. It uses <processname>-lumberjack.log in + // os.TempDir() if empty. + Filename string + + // MaxSize is the maximum size in megabytes of the log file before it gets + // rotated. It defaults to 100 megabytes. + MaxSize int + + // MaxAge is the maximum number of days to retain old log files based on the + // timestamp encoded in their filename. Note that a day is defined as 24 + // hours and may not exactly correspond to calendar days due to daylight + // savings, leap seconds, etc. The default is not to remove old log files + // based on age. + MaxAge int + + // MaxBackups is the maximum number of old log files to retain. The default + // is to retain all old log files (though MaxAge may still cause them to get + // deleted.) + MaxBackups int + + // Compress determines if the rotated log files should be compressed + // using gzip. The default is not to perform compression. + Compress bool +} + +// File outputs log records to a file which can be log rotated based on size or age. +// Uses `https://github.com/natefinch/lumberjack` for rotation. +type File struct { + logr.Basic + out io.WriteCloser +} + +// NewFileTarget creates a target capable of outputting log records to a rotated file. +func NewFileTarget(filter logr.Filter, formatter logr.Formatter, opts FileOptions, maxQueue int) *File { + lumber := &lumberjack.Logger{ + Filename: opts.Filename, + MaxSize: opts.MaxSize, + MaxBackups: opts.MaxBackups, + MaxAge: opts.MaxAge, + Compress: opts.Compress, + } + f := &File{out: lumber} + f.Basic.Start(f, f, filter, formatter, maxQueue) + return f +} + +// Write converts the log record to bytes, via the Formatter, +// and outputs to a file. +func (f *File) Write(rec *logr.LogRec) error { + _, stacktrace := f.IsLevelEnabled(rec.Level()) + + buf := rec.Logger().Logr().BorrowBuffer() + defer rec.Logger().Logr().ReleaseBuffer(buf) + + buf, err := f.Formatter().Format(rec, stacktrace, buf) + if err != nil { + return err + } + _, err = f.out.Write(buf.Bytes()) + return err +} + +// Shutdown flushes any remaining log records and closes the file. +func (f *File) Shutdown(ctx context.Context) error { + errs := merror.New() + + err := f.Basic.Shutdown(ctx) + errs.Append(err) + + err = f.out.Close() + errs.Append(err) + + return errs.ErrorOrNil() +} diff --git a/vendor/github.com/mattermost/logr/target/syslog.go b/vendor/github.com/mattermost/logr/target/syslog.go new file mode 100644 index 00000000..1d2013b6 --- /dev/null +++ b/vendor/github.com/mattermost/logr/target/syslog.go @@ -0,0 +1,89 @@ +// +build !windows,!nacl,!plan9 + +package target + +import ( + "context" + "fmt" + "log/syslog" + + "github.com/mattermost/logr" + "github.com/wiggin77/merror" +) + +// Syslog outputs log records to local or remote syslog. +type Syslog struct { + logr.Basic + w *syslog.Writer +} + +// SyslogParams provides parameters for dialing a syslog daemon. +type SyslogParams struct { + Network string + Raddr string + Priority syslog.Priority + Tag string +} + +// NewSyslogTarget creates a target capable of outputting log records to remote or local syslog. +func NewSyslogTarget(filter logr.Filter, formatter logr.Formatter, params *SyslogParams, maxQueue int) (*Syslog, error) { + writer, err := syslog.Dial(params.Network, params.Raddr, params.Priority, params.Tag) + if err != nil { + return nil, err + } + + s := &Syslog{w: writer} + s.Basic.Start(s, s, filter, formatter, maxQueue) + + return s, nil +} + +// Shutdown stops processing log records after making best +// effort to flush queue. +func (s *Syslog) Shutdown(ctx context.Context) error { + errs := merror.New() + + err := s.Basic.Shutdown(ctx) + errs.Append(err) + + err = s.w.Close() + errs.Append(err) + + return errs.ErrorOrNil() +} + +// Write converts the log record to bytes, via the Formatter, +// and outputs to syslog. +func (s *Syslog) Write(rec *logr.LogRec) error { + _, stacktrace := s.IsLevelEnabled(rec.Level()) + + buf := rec.Logger().Logr().BorrowBuffer() + defer rec.Logger().Logr().ReleaseBuffer(buf) + + buf, err := s.Formatter().Format(rec, stacktrace, buf) + if err != nil { + return err + } + txt := buf.String() + + switch rec.Level() { + case logr.Panic, logr.Fatal: + err = s.w.Crit(txt) + case logr.Error: + err = s.w.Err(txt) + case logr.Warn: + err = s.w.Warning(txt) + case logr.Debug, logr.Trace: + err = s.w.Debug(txt) + default: + // logr.Info plus all custom levels. + err = s.w.Info(txt) + } + + if err != nil { + reporter := rec.Logger().Logr().ReportError + reporter(fmt.Errorf("syslog write fail: %w", err)) + // syslog writer will try to reconnect. + } + return err +} diff --git a/vendor/github.com/mattermost/logr/target/writer.go b/vendor/github.com/mattermost/logr/target/writer.go new file mode 100644 index 00000000..2250da51 --- /dev/null +++ b/vendor/github.com/mattermost/logr/target/writer.go @@ -0,0 +1,40 @@ +package target + +import ( + "io" + "io/ioutil" + + "github.com/mattermost/logr" +) + +// Writer outputs log records to any `io.Writer`. +type Writer struct { + logr.Basic + out io.Writer +} + +// NewWriterTarget creates a target capable of outputting log records to an io.Writer. +func NewWriterTarget(filter logr.Filter, formatter logr.Formatter, out io.Writer, maxQueue int) *Writer { + if out == nil { + out = ioutil.Discard + } + w := &Writer{out: out} + w.Basic.Start(w, w, filter, formatter, maxQueue) + return w +} + +// Write converts the log record to bytes, via the Formatter, +// and outputs to the io.Writer. +func (w *Writer) Write(rec *logr.LogRec) error { + _, stacktrace := w.IsLevelEnabled(rec.Level()) + + buf := rec.Logger().Logr().BorrowBuffer() + defer rec.Logger().Logr().ReleaseBuffer(buf) + + buf, err := w.Formatter().Format(rec, stacktrace, buf) + if err != nil { + return err + } + _, err = w.out.Write(buf.Bytes()) + return err +} diff --git a/vendor/github.com/mattermost/logr/timeout.go b/vendor/github.com/mattermost/logr/timeout.go new file mode 100644 index 00000000..37737bcf --- /dev/null +++ b/vendor/github.com/mattermost/logr/timeout.go @@ -0,0 +1,34 @@ +package logr + +import "github.com/wiggin77/merror" + +// timeoutError is returned from functions that can timeout. +type timeoutError struct { + text string +} + +// newTimeoutError returns a TimeoutError. +func newTimeoutError(text string) timeoutError { + return timeoutError{text: text} +} + +// IsTimeoutError returns true if err is a TimeoutError. +func IsTimeoutError(err error) bool { + if _, ok := err.(timeoutError); ok { + return true + } + // if a multi-error, return true if any of the errors + // are TimeoutError + if merr, ok := err.(*merror.MError); ok { + for _, e := range merr.Errors() { + if IsTimeoutError(e) { + return true + } + } + } + return false +} + +func (err timeoutError) Error() string { + return err.text +} |