summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/mattermost/logr
diff options
context:
space:
mode:
authorWim <wim@42.be>2023-08-05 20:43:19 +0200
committerGitHub <noreply@github.com>2023-08-05 20:43:19 +0200
commit56e7bd01ca09ad52b0c4f48f146a20a4f1b78696 (patch)
treeb1355645342667209263cbd355dc0b4254f1e8fe /vendor/github.com/mattermost/logr
parent9459495484d6e06a3d46de64fccd8d06f7ccc72c (diff)
downloadmatterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.tar.gz
matterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.tar.bz2
matterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.zip
Update dependencies and remove old matterclient lib (#2067)HEADmaster
Diffstat (limited to 'vendor/github.com/mattermost/logr')
-rw-r--r--vendor/github.com/mattermost/logr/.gitignore36
-rw-r--r--vendor/github.com/mattermost/logr/.travis.yml4
-rw-r--r--vendor/github.com/mattermost/logr/LICENSE21
-rw-r--r--vendor/github.com/mattermost/logr/README.md193
-rw-r--r--vendor/github.com/mattermost/logr/config.go11
-rw-r--r--vendor/github.com/mattermost/logr/const.go34
-rw-r--r--vendor/github.com/mattermost/logr/filter.go26
-rw-r--r--vendor/github.com/mattermost/logr/format/json.go273
-rw-r--r--vendor/github.com/mattermost/logr/format/plain.go75
-rw-r--r--vendor/github.com/mattermost/logr/formatter.go119
-rw-r--r--vendor/github.com/mattermost/logr/levelcache.go98
-rw-r--r--vendor/github.com/mattermost/logr/levelcustom.go45
-rw-r--r--vendor/github.com/mattermost/logr/levelstd.go37
-rw-r--r--vendor/github.com/mattermost/logr/logger.go218
-rw-r--r--vendor/github.com/mattermost/logr/logr.go664
-rw-r--r--vendor/github.com/mattermost/logr/logrec.go189
-rw-r--r--vendor/github.com/mattermost/logr/metrics.go117
-rw-r--r--vendor/github.com/mattermost/logr/target.go299
-rw-r--r--vendor/github.com/mattermost/logr/target/file.go87
-rw-r--r--vendor/github.com/mattermost/logr/target/syslog.go89
-rw-r--r--vendor/github.com/mattermost/logr/target/writer.go40
-rw-r--r--vendor/github.com/mattermost/logr/timeout.go34
22 files changed, 0 insertions, 2709 deletions
diff --git a/vendor/github.com/mattermost/logr/.gitignore b/vendor/github.com/mattermost/logr/.gitignore
deleted file mode 100644
index c2c0a9e2..00000000
--- a/vendor/github.com/mattermost/logr/.gitignore
+++ /dev/null
@@ -1,36 +0,0 @@
-# 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
deleted file mode 100644
index e6c7caf1..00000000
--- a/vendor/github.com/mattermost/logr/.travis.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-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
deleted file mode 100644
index 3bea6788..00000000
--- a/vendor/github.com/mattermost/logr/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-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
deleted file mode 100644
index a25d6de0..00000000
--- a/vendor/github.com/mattermost/logr/README.md
+++ /dev/null
@@ -1,193 +0,0 @@
-# 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
deleted file mode 100644
index 83d4b0c1..00000000
--- a/vendor/github.com/mattermost/logr/config.go
+++ /dev/null
@@ -1,11 +0,0 @@
-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
deleted file mode 100644
index 704d0507..00000000
--- a/vendor/github.com/mattermost/logr/const.go
+++ /dev/null
@@ -1,34 +0,0 @@
-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
deleted file mode 100644
index 6e654cd7..00000000
--- a/vendor/github.com/mattermost/logr/filter.go
+++ /dev/null
@@ -1,26 +0,0 @@
-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
deleted file mode 100644
index 8f56c6cb..00000000
--- a/vendor/github.com/mattermost/logr/format/json.go
+++ /dev/null
@@ -1,273 +0,0 @@
-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
deleted file mode 100644
index 3fa92b49..00000000
--- a/vendor/github.com/mattermost/logr/format/plain.go
+++ /dev/null
@@ -1,75 +0,0 @@
-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
deleted file mode 100644
index bb8df2d4..00000000
--- a/vendor/github.com/mattermost/logr/formatter.go
+++ /dev/null
@@ -1,119 +0,0 @@
-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/levelcache.go b/vendor/github.com/mattermost/logr/levelcache.go
deleted file mode 100644
index 2cefb61d..00000000
--- a/vendor/github.com/mattermost/logr/levelcache.go
+++ /dev/null
@@ -1,98 +0,0 @@
-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
deleted file mode 100644
index 384fe4e9..00000000
--- a/vendor/github.com/mattermost/logr/levelcustom.go
+++ /dev/null
@@ -1,45 +0,0 @@
-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
deleted file mode 100644
index f5e0fa46..00000000
--- a/vendor/github.com/mattermost/logr/levelstd.go
+++ /dev/null
@@ -1,37 +0,0 @@
-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
deleted file mode 100644
index c2386312..00000000
--- a/vendor/github.com/mattermost/logr/logger.go
+++ /dev/null
@@ -1,218 +0,0 @@
-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
deleted file mode 100644
index 631366a5..00000000
--- a/vendor/github.com/mattermost/logr/logr.go
+++ /dev/null
@@ -1,664 +0,0 @@
-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
deleted file mode 100644
index 9428aaec..00000000
--- a/vendor/github.com/mattermost/logr/logrec.go
+++ /dev/null
@@ -1,189 +0,0 @@
-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
deleted file mode 100644
index 24fe22b6..00000000
--- a/vendor/github.com/mattermost/logr/metrics.go
+++ /dev/null
@@ -1,117 +0,0 @@
-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
deleted file mode 100644
index f8e7bf75..00000000
--- a/vendor/github.com/mattermost/logr/target.go
+++ /dev/null
@@ -1,299 +0,0 @@
-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
deleted file mode 100644
index 0fd50768..00000000
--- a/vendor/github.com/mattermost/logr/target/file.go
+++ /dev/null
@@ -1,87 +0,0 @@
-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
deleted file mode 100644
index 1d2013b6..00000000
--- a/vendor/github.com/mattermost/logr/target/syslog.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// +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
deleted file mode 100644
index 2250da51..00000000
--- a/vendor/github.com/mattermost/logr/target/writer.go
+++ /dev/null
@@ -1,40 +0,0 @@
-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
deleted file mode 100644
index 37737bcf..00000000
--- a/vendor/github.com/mattermost/logr/timeout.go
+++ /dev/null
@@ -1,34 +0,0 @@
-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
-}