diff options
Diffstat (limited to 'vendor/github.com/dsoprea/go-logging')
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/.travis.yml | 12 | ||||
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/LICENSE | 9 | ||||
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/README.md | 223 | ||||
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/config.go | 246 | ||||
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/console_adapter.go | 36 | ||||
-rw-r--r-- | vendor/github.com/dsoprea/go-logging/log.go | 537 |
6 files changed, 0 insertions, 1063 deletions
diff --git a/vendor/github.com/dsoprea/go-logging/.travis.yml b/vendor/github.com/dsoprea/go-logging/.travis.yml deleted file mode 100644 index e37da4ba8..000000000 --- a/vendor/github.com/dsoprea/go-logging/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - tip -install: - - go get -t ./... - - go get github.com/mattn/goveralls -script: -# v1 - - go test -v . -# v2 - - cd v2 - - goveralls -v -service=travis-ci diff --git a/vendor/github.com/dsoprea/go-logging/LICENSE b/vendor/github.com/dsoprea/go-logging/LICENSE deleted file mode 100644 index 163291ed6..000000000 --- a/vendor/github.com/dsoprea/go-logging/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -MIT LICENSE - -Copyright 2020 Dustin Oprea - -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/dsoprea/go-logging/README.md b/vendor/github.com/dsoprea/go-logging/README.md deleted file mode 100644 index 820cd9dc0..000000000 --- a/vendor/github.com/dsoprea/go-logging/README.md +++ /dev/null @@ -1,223 +0,0 @@ -[](https://travis-ci.org/dsoprea/go-logging) -[](https://coveralls.io/github/dsoprea/go-logging?branch=master) -[](https://goreportcard.com/report/github.com/dsoprea/go-logging/v2) -[](https://godoc.org/github.com/dsoprea/go-logging/v2) - -## Introduction - -This project bridges several gaps that are present in the standard logging support in Go: - -- Equips errors with stacktraces and provides a facility for printing them -- Inherently supports the ability for each Go file to print its messages with a prefix representing that file/package -- Adds some functions to specifically log messages of different levels (e.g. debug, error) -- Adds a `PanicIf()` function that can be used to conditionally manage errors depending on whether an error variable is `nil` or actually has an error -- Adds support for pluggable logging adapters (so the output can be sent somewhere other than the console) -- Adds configuration (such as the logging level or adapter) that can be driven from the environment -- Supports filtering to show/hide the logging of certain places of the application -- The loggers can be definded at the package level, so you can determine which Go file any log message came from. - -When used with the Panic-Defer-Recover pattern in Go, even panics rising from the Go runtime will be caught and wrapped with a stacktrace. This compartmentalizes which function they could have originated from, which is, otherwise, potentially non-trivial to figure out. - -## AppEngine - -Go under AppEngine is very stripped down, such as there being no logging type (e.g. `Logger` in native Go) and there is no support for prefixing. As each logging call from this project takes a `Context`, this works cooperatively to bridge the additional gaps in AppEngine's logging support. - -With standard console logging outside of this context, that parameter will take a`nil`. - - -## Getting Started - -The simplest, possible example: - -```go -package thispackage - -import ( - "context" - "errors" - - "github.com/dsoprea/go-logging/v2" -) - -var ( - thisfileLog = log.NewLogger("thispackage.thisfile") -) - -func a_cry_for_help(ctx context.Context) { - err := errors.New("a big error") - thisfileLog.Errorf(ctx, err, "How big is my problem: %s", "pretty big") -} - -func init() { - cla := log.NewConsoleLogAdapter() - log.AddAdapter("console", cla) -} -``` - -Notice two things: - -1. We register the "console" adapter at the bottom. The first adapter registered will be used by default. -2. We pass-in a prefix (what we refer to as a "noun") to `log.NewLogger()`. This is a simple, descriptive name that represents the subject of the file. By convention, we construct this by dot-separating the current package and the name of the file. We recommend that you define a different log for every file at the package level, but it is your choice whether you want to do this or share the same logger over the entire package, define one in each struct, etc.. - - -### Example Output - -Example output from a real application (not from the above): - -``` -2016/09/09 12:57:44 DEBUG: user: User revisiting: [test@example.com] -2016/09/09 12:57:44 DEBUG: context: Session already inited: [DCRBDGRY6RMWANCSJXVLD7GULDH4NZEB6SBAQ3KSFIGA2LP45IIQ] -2016/09/09 12:57:44 DEBUG: session_data: Session save not necessary: [DCRBDGRY6RMWANCSJXVLD7GULDH4NZEB6SBAQ3KSFIGA2LP45IIQ] -2016/09/09 12:57:44 DEBUG: context: Got session: [DCRBDGRY6RMWANCSJXVLD7GULDH4NZEB6SBAQ3KSFIGA2LP45IIQ] -2016/09/09 12:57:44 DEBUG: session_data: Found user in session. -2016/09/09 12:57:44 DEBUG: cache: Cache miss: [geo.geocode.reverse:dhxp15x] -``` - - -## Adapters - -This project provides one built-in logging adapter, "console", which prints to the screen. To register it: - -```go -cla := log.NewConsoleLogAdapter() -log.AddAdapter("console", cla) -``` - -### Custom Adapters - -If you would like to implement your own logger, just create a struct type that satisfies the LogAdapter interface. - -```go -type LogAdapter interface { - Debugf(lc *LogContext, message *string) error - Infof(lc *LogContext, message *string) error - Warningf(lc *LogContext, message *string) error - Errorf(lc *LogContext, message *string) error -} -``` - -The *LogContext* struct passed in provides additional information that you may need in order to do what you need to do: - -```go -type LogContext struct { - Logger *Logger - Ctx context.Context -} -``` - -`Logger` represents your Logger instance. - -Adapter example: - -```go -type DummyLogAdapter struct { - -} - -func (dla *DummyLogAdapter) Debugf(lc *LogContext, message *string) error { - -} - -func (dla *DummyLogAdapter) Infof(lc *LogContext, message *string) error { - -} - -func (dla *DummyLogAdapter) Warningf(lc *LogContext, message *string) error { - -} - -func (dla *DummyLogAdapter) Errorf(lc *LogContext, message *string) error { - -} -``` - -Then, register it: - -```go -func init() { - log.AddAdapter("dummy", new(DummyLogAdapter)) -} -``` - -If this is a task-specific implementation, just register it from the `init()` of the file that defines it. - -If this is the first adapter you've registered, it will be the default one used. Otherwise, you'll have to deliberately specify it when you are creating a logger: Instead of calling `log.NewLogger(noun string)`, call `log.NewLoggerWithAdapterName(noun string, adapterName string)`. - -We discuss how to configure the adapter from configuration in the "Configuration" section below. - - -### Adapter Notes - -- The `Logger` instance exports `Noun()` in the event you want to discriminate where your log entries go in your adapter. It also exports `Adapter()` for if you need to access the adapter instance from your application. -- If no adapter is registered (specifically, the default adapter-name remains empty), logging calls will be a no-op. This allows libraries to implement *go-logging* where the larger application doesn't. - - -## Filters - -We support the ability to exclusively log for a specific set of nouns (we'll exclude any not specified): - -```go -log.AddIncludeFilter("nountoshow1") -log.AddIncludeFilter("nountoshow2") -``` - -Depending on your needs, you might just want to exclude a couple and include the rest: - -```go -log.AddExcludeFilter("nountohide1") -log.AddExcludeFilter("nountohide2") -``` - -We'll first hit the include-filters. If it's in there, we'll forward the log item to the adapter. If not, and there is at least one include filter in the list, we won't do anything. If the list of include filters is empty but the noun appears in the exclude list, we won't do anything. - -It is a good convention to exclude the nouns of any library you are writing whose logging you do not want to generally be aware of unless you are debugging. You might call `AddExcludeFilter()` from the `init()` function at the bottom of those files unless there is some configuration variable, such as "(LibraryNameHere)DoShowLogging", that has been defined and set to TRUE. - - -## Configuration - -The following configuration items are available: - -- *Format*: The default format used to build the message that gets sent to the adapter. It is assumed that the adapter already prefixes the message with time and log-level (since the default AppEngine logger does). The default value is: `{{.Noun}}: [{{.Level}}] {{if eq .ExcludeBypass true}} [BYPASS]{{end}} {{.Message}}`. The available tokens are "Level", "Noun", "ExcludeBypass", and "Message". -- *DefaultAdapterName*: The default name of the adapter to use when NewLogger() is called (if this isn't defined then the name of the first registered adapter will be used). -- *LevelName*: The priority-level of messages permitted to be logged (all others will be discarded). By default, it is "info". Other levels are: "debug", "warning", "error", "critical" -- *IncludeNouns*: Comma-separated list of nouns to log for. All others will be ignored. -- *ExcludeNouns*: Comma-separated list on nouns to exclude from logging. -- *ExcludeBypassLevelName*: The log-level at which we will show logging for nouns that have been excluded. Allows you to hide excessive, unimportant logging for nouns but to still see their warnings, errors, etc... - - -### Configuration Providers - -You provide the configuration by setting a configuration-provider. Configuration providers must satisfy the `ConfigurationProvider` interface. The following are provided with the project: - -- `EnvironmentConfigurationProvider`: Read values from the environment. -- `StaticConfigurationProvider`: Set values directly on the struct. - -**The configuration provider must be applied before doing any logging (otherwise it will have no effect).** - -Environments such as AppEngine work best with `EnvironmentConfigurationProvider` as this is generally how configuration is exposed *by* AppEngine *to* the application. You can define this configuration directly in *that* configuration. - -By default, no configuration-provider is applied, the level is defaulted to INFO and the format is defaulted to "{{.Noun}}:{{if eq .ExcludeBypass true}} [BYPASS]{{end}} {{.Message}}". - -Again, if a configuration-provider does not provide a log-level or format, they will be defaulted (or left alone, if already set). If it does not provide an adapter-name, the adapter-name of the first registered adapter will be used. - -Usage instructions of both follow. - - -### Environment-Based Configuration - -```go -ecp := log.NewEnvironmentConfigurationProvider() -log.LoadConfiguration(ecp) -``` - -Each of the items listed at the top of the "Configuration" section can be specified in the environment using a prefix of "Log" (e.g. LogDefaultAdapterName). - - -### Static Configuration - -```go -scp := log.NewStaticConfigurationProvider() -scp.SetLevelName(log.LevelNameWarning) - -log.LoadConfiguration(scp) -``` diff --git a/vendor/github.com/dsoprea/go-logging/config.go b/vendor/github.com/dsoprea/go-logging/config.go deleted file mode 100644 index 20896e342..000000000 --- a/vendor/github.com/dsoprea/go-logging/config.go +++ /dev/null @@ -1,246 +0,0 @@ -package log - -import ( - "fmt" - "os" -) - -// Config keys. -const ( - ckFormat = "LogFormat" - ckDefaultAdapterName = "LogDefaultAdapterName" - ckLevelName = "LogLevelName" - ckIncludeNouns = "LogIncludeNouns" - ckExcludeNouns = "LogExcludeNouns" - ckExcludeBypassLevelName = "LogExcludeBypassLevelName" -) - -// Other constants -const ( - defaultFormat = "{{.Noun}}: [{{.Level}}] {{if eq .ExcludeBypass true}} [BYPASS]{{end}} {{.Message}}" - defaultLevelName = LevelNameInfo -) - -// Config -var ( - // Alternative format. - format = defaultFormat - - // Alternative adapter. - defaultAdapterName = "" - - // Alternative level at which to display log-items - levelName = defaultLevelName - - // Configuration-driven comma-separated list of nouns to include. - includeNouns = "" - - // Configuration-driven comma-separated list of nouns to exclude. - excludeNouns = "" - - // Level at which to disregard exclusion (if the severity of a message - // meets or exceed this, always display). - excludeBypassLevelName = "" -) - -// Other -var ( - configurationLoaded = false -) - -// Return the current default adapter name. -func GetDefaultAdapterName() string { - return defaultAdapterName -} - -// The adapter will automatically be the first one registered. This overrides -// that. -func SetDefaultAdapterName(name string) { - defaultAdapterName = name -} - -func LoadConfiguration(cp ConfigurationProvider) { - configuredDefaultAdapterName := cp.DefaultAdapterName() - - if configuredDefaultAdapterName != "" { - defaultAdapterName = configuredDefaultAdapterName - } - - includeNouns = cp.IncludeNouns() - excludeNouns = cp.ExcludeNouns() - excludeBypassLevelName = cp.ExcludeBypassLevelName() - - f := cp.Format() - if f != "" { - format = f - } - - ln := cp.LevelName() - if ln != "" { - levelName = ln - } - - configurationLoaded = true -} - -func getConfigState() map[string]interface{} { - return map[string]interface{}{ - "format": format, - "defaultAdapterName": defaultAdapterName, - "levelName": levelName, - "includeNouns": includeNouns, - "excludeNouns": excludeNouns, - "excludeBypassLevelName": excludeBypassLevelName, - } -} - -func setConfigState(config map[string]interface{}) { - format = config["format"].(string) - - defaultAdapterName = config["defaultAdapterName"].(string) - levelName = config["levelName"].(string) - includeNouns = config["includeNouns"].(string) - excludeNouns = config["excludeNouns"].(string) - excludeBypassLevelName = config["excludeBypassLevelName"].(string) -} - -func getConfigDump() string { - return fmt.Sprintf( - "Current configuration:\n"+ - " FORMAT=[%s]\n"+ - " DEFAULT-ADAPTER-NAME=[%s]\n"+ - " LEVEL-NAME=[%s]\n"+ - " INCLUDE-NOUNS=[%s]\n"+ - " EXCLUDE-NOUNS=[%s]\n"+ - " EXCLUDE-BYPASS-LEVEL-NAME=[%s]", - format, defaultAdapterName, levelName, includeNouns, excludeNouns, excludeBypassLevelName) -} - -func IsConfigurationLoaded() bool { - return configurationLoaded -} - -type ConfigurationProvider interface { - // Alternative format (defaults to . - Format() string - - // Alternative adapter (defaults to "appengine"). - DefaultAdapterName() string - - // Alternative level at which to display log-items (defaults to - // "info"). - LevelName() string - - // Configuration-driven comma-separated list of nouns to include. Defaults - // to empty. - IncludeNouns() string - - // Configuration-driven comma-separated list of nouns to exclude. Defaults - // to empty. - ExcludeNouns() string - - // Level at which to disregard exclusion (if the severity of a message - // meets or exceed this, always display). Defaults to empty. - ExcludeBypassLevelName() string -} - -// Environment configuration-provider. -type EnvironmentConfigurationProvider struct { -} - -func NewEnvironmentConfigurationProvider() *EnvironmentConfigurationProvider { - return new(EnvironmentConfigurationProvider) -} - -func (ecp *EnvironmentConfigurationProvider) Format() string { - return os.Getenv(ckFormat) -} - -func (ecp *EnvironmentConfigurationProvider) DefaultAdapterName() string { - return os.Getenv(ckDefaultAdapterName) -} - -func (ecp *EnvironmentConfigurationProvider) LevelName() string { - return os.Getenv(ckLevelName) -} - -func (ecp *EnvironmentConfigurationProvider) IncludeNouns() string { - return os.Getenv(ckIncludeNouns) -} - -func (ecp *EnvironmentConfigurationProvider) ExcludeNouns() string { - return os.Getenv(ckExcludeNouns) -} - -func (ecp *EnvironmentConfigurationProvider) ExcludeBypassLevelName() string { - return os.Getenv(ckExcludeBypassLevelName) -} - -// Static configuration-provider. -type StaticConfigurationProvider struct { - format string - defaultAdapterName string - levelName string - includeNouns string - excludeNouns string - excludeBypassLevelName string -} - -func NewStaticConfigurationProvider() *StaticConfigurationProvider { - return new(StaticConfigurationProvider) -} - -func (scp *StaticConfigurationProvider) SetFormat(format string) { - scp.format = format -} - -func (scp *StaticConfigurationProvider) SetDefaultAdapterName(adapterName string) { - scp.defaultAdapterName = adapterName -} - -func (scp *StaticConfigurationProvider) SetLevelName(levelName string) { - scp.levelName = levelName -} - -func (scp *StaticConfigurationProvider) SetIncludeNouns(includeNouns string) { - scp.includeNouns = includeNouns -} - -func (scp *StaticConfigurationProvider) SetExcludeNouns(excludeNouns string) { - scp.excludeNouns = excludeNouns -} - -func (scp *StaticConfigurationProvider) SetExcludeBypassLevelName(excludeBypassLevelName string) { - scp.excludeBypassLevelName = excludeBypassLevelName -} - -func (scp *StaticConfigurationProvider) Format() string { - return scp.format -} - -func (scp *StaticConfigurationProvider) DefaultAdapterName() string { - return scp.defaultAdapterName -} - -func (scp *StaticConfigurationProvider) LevelName() string { - return scp.levelName -} - -func (scp *StaticConfigurationProvider) IncludeNouns() string { - return scp.includeNouns -} - -func (scp *StaticConfigurationProvider) ExcludeNouns() string { - return scp.excludeNouns -} - -func (scp *StaticConfigurationProvider) ExcludeBypassLevelName() string { - return scp.excludeBypassLevelName -} - -func init() { - // Do the initial configuration-load from the environment. We gotta seed it - // with something for simplicity's sake. - ecp := NewEnvironmentConfigurationProvider() - LoadConfiguration(ecp) -} diff --git a/vendor/github.com/dsoprea/go-logging/console_adapter.go b/vendor/github.com/dsoprea/go-logging/console_adapter.go deleted file mode 100644 index c63a2911c..000000000 --- a/vendor/github.com/dsoprea/go-logging/console_adapter.go +++ /dev/null @@ -1,36 +0,0 @@ -package log - -import ( - golog "log" -) - -type ConsoleLogAdapter struct { -} - -func NewConsoleLogAdapter() LogAdapter { - return new(ConsoleLogAdapter) -} - -func (cla *ConsoleLogAdapter) Debugf(lc *LogContext, message *string) error { - golog.Println(*message) - - return nil -} - -func (cla *ConsoleLogAdapter) Infof(lc *LogContext, message *string) error { - golog.Println(*message) - - return nil -} - -func (cla *ConsoleLogAdapter) Warningf(lc *LogContext, message *string) error { - golog.Println(*message) - - return nil -} - -func (cla *ConsoleLogAdapter) Errorf(lc *LogContext, message *string) error { - golog.Println(*message) - - return nil -} diff --git a/vendor/github.com/dsoprea/go-logging/log.go b/vendor/github.com/dsoprea/go-logging/log.go deleted file mode 100644 index 84117a92e..000000000 --- a/vendor/github.com/dsoprea/go-logging/log.go +++ /dev/null @@ -1,537 +0,0 @@ -package log - -import ( - "bytes" - e "errors" - "fmt" - "strings" - "sync" - - "text/template" - - "github.com/go-errors/errors" - "golang.org/x/net/context" -) - -// TODO(dustin): Finish symbol documentation - -// Config severity integers. -const ( - LevelDebug = iota - LevelInfo = iota - LevelWarning = iota - LevelError = iota -) - -// Config severity names. -const ( - LevelNameDebug = "debug" - LevelNameInfo = "info" - LevelNameWarning = "warning" - LevelNameError = "error" -) - -// Seveirty name->integer map. -var ( - LevelNameMap = map[string]int{ - LevelNameDebug: LevelDebug, - LevelNameInfo: LevelInfo, - LevelNameWarning: LevelWarning, - LevelNameError: LevelError, - } - - LevelNameMapR = map[int]string{ - LevelDebug: LevelNameDebug, - LevelInfo: LevelNameInfo, - LevelWarning: LevelNameWarning, - LevelError: LevelNameError, - } -) - -// Errors -var ( - ErrAdapterAlreadyRegistered = e.New("adapter already registered") - ErrFormatEmpty = e.New("format is empty") - ErrExcludeLevelNameInvalid = e.New("exclude bypass-level is invalid") - ErrNoAdapterConfigured = e.New("no default adapter configured") - ErrAdapterIsNil = e.New("adapter is nil") - ErrConfigurationNotLoaded = e.New("can not configure because configuration is not loaded") -) - -// Other -var ( - includeFilters = make(map[string]bool) - useIncludeFilters = false - excludeFilters = make(map[string]bool) - useExcludeFilters = false - - adapters = make(map[string]LogAdapter) - - // TODO(dustin): !! Finish implementing this. - excludeBypassLevel = -1 -) - -// Add global include filter. -func AddIncludeFilter(noun string) { - includeFilters[noun] = true - useIncludeFilters = true -} - -// Remove global include filter. -func RemoveIncludeFilter(noun string) { - delete(includeFilters, noun) - if len(includeFilters) == 0 { - useIncludeFilters = false - } -} - -// Add global exclude filter. -func AddExcludeFilter(noun string) { - excludeFilters[noun] = true - useExcludeFilters = true -} - -// Remove global exclude filter. -func RemoveExcludeFilter(noun string) { - delete(excludeFilters, noun) - if len(excludeFilters) == 0 { - useExcludeFilters = false - } -} - -func AddAdapter(name string, la LogAdapter) { - if _, found := adapters[name]; found == true { - Panic(ErrAdapterAlreadyRegistered) - } - - if la == nil { - Panic(ErrAdapterIsNil) - } - - adapters[name] = la - - if GetDefaultAdapterName() == "" { - SetDefaultAdapterName(name) - } -} - -func ClearAdapters() { - adapters = make(map[string]LogAdapter) - SetDefaultAdapterName("") -} - -type LogAdapter interface { - Debugf(lc *LogContext, message *string) error - Infof(lc *LogContext, message *string) error - Warningf(lc *LogContext, message *string) error - Errorf(lc *LogContext, message *string) error -} - -// TODO(dustin): !! Also populate whether we've bypassed an exception so that -// we can add a template macro to prefix an exclamation of -// some sort. -type MessageContext struct { - Level *string - Noun *string - Message *string - ExcludeBypass bool -} - -type LogContext struct { - Logger *Logger - Ctx context.Context -} - -type Logger struct { - isConfigured bool - an string - la LogAdapter - t *template.Template - systemLevel int - noun string -} - -func NewLoggerWithAdapterName(noun string, adapterName string) (l *Logger) { - l = &Logger{ - noun: noun, - an: adapterName, - } - - return l -} - -func NewLogger(noun string) (l *Logger) { - l = NewLoggerWithAdapterName(noun, "") - - return l -} - -func (l *Logger) Noun() string { - return l.noun -} - -func (l *Logger) Adapter() LogAdapter { - return l.la -} - -var ( - configureMutex sync.Mutex -) - -func (l *Logger) doConfigure(force bool) { - configureMutex.Lock() - defer configureMutex.Unlock() - - if l.isConfigured == true && force == false { - return - } - - if IsConfigurationLoaded() == false { - Panic(ErrConfigurationNotLoaded) - } - - if l.an == "" { - l.an = GetDefaultAdapterName() - } - - // If this is empty, then no specific adapter was given or no system - // default was configured (which implies that no adapters were registered). - // All of our logging will be skipped. - if l.an != "" { - la, found := adapters[l.an] - if found == false { - Panic(fmt.Errorf("adapter is not valid: %s", l.an)) - } - - l.la = la - } - - // Set the level. - - systemLevel, found := LevelNameMap[levelName] - if found == false { - Panic(fmt.Errorf("log-level not valid: [%s]", levelName)) - } - - l.systemLevel = systemLevel - - // Set the form. - - if format == "" { - Panic(ErrFormatEmpty) - } - - if t, err := template.New("logItem").Parse(format); err != nil { - Panic(err) - } else { - l.t = t - } - - l.isConfigured = true -} - -func (l *Logger) flattenMessage(lc *MessageContext, format *string, args []interface{}) (string, error) { - m := fmt.Sprintf(*format, args...) - - lc.Message = &m - - var b bytes.Buffer - if err := l.t.Execute(&b, *lc); err != nil { - return "", err - } - - return b.String(), nil -} - -func (l *Logger) allowMessage(noun string, level int) bool { - if _, found := includeFilters[noun]; found == true { - return true - } - - // If we didn't hit an include filter and we *had* include filters, filter - // it out. - if useIncludeFilters == true { - return false - } - - if _, found := excludeFilters[noun]; found == true { - return false - } - - return true -} - -func (l *Logger) makeLogContext(ctx context.Context) *LogContext { - return &LogContext{ - Ctx: ctx, - Logger: l, - } -} - -type LogMethod func(lc *LogContext, message *string) error - -func (l *Logger) log(ctx context.Context, level int, lm LogMethod, format string, args []interface{}) error { - if l.systemLevel > level { - return nil - } - - // Preempt the normal filter checks if we can unconditionally allow at a - // certain level and we've hit that level. - // - // Notice that this is only relevant if the system-log level is letting - // *anything* show logs at the level we came in with. - canExcludeBypass := level >= excludeBypassLevel && excludeBypassLevel != -1 - didExcludeBypass := false - - n := l.Noun() - - if l.allowMessage(n, level) == false { - if canExcludeBypass == false { - return nil - } else { - didExcludeBypass = true - } - } - - levelName, found := LevelNameMapR[level] - if found == false { - Panic(fmt.Errorf("level not valid: (%d)", level)) - } - - levelName = strings.ToUpper(levelName) - - lc := &MessageContext{ - Level: &levelName, - Noun: &n, - ExcludeBypass: didExcludeBypass, - } - - if s, err := l.flattenMessage(lc, &format, args); err != nil { - return err - } else { - lc := l.makeLogContext(ctx) - if err := lm(lc, &s); err != nil { - panic(err) - } - - return e.New(s) - } -} - -func (l *Logger) Debugf(ctx context.Context, format string, args ...interface{}) { - l.doConfigure(false) - - if l.la != nil { - l.log(ctx, LevelDebug, l.la.Debugf, format, args) - } -} - -func (l *Logger) Infof(ctx context.Context, format string, args ...interface{}) { - l.doConfigure(false) - - if l.la != nil { - l.log(ctx, LevelInfo, l.la.Infof, format, args) - } -} - -func (l *Logger) Warningf(ctx context.Context, format string, args ...interface{}) { - l.doConfigure(false) - - if l.la != nil { - l.log(ctx, LevelWarning, l.la.Warningf, format, args) - } -} - -func (l *Logger) mergeStack(err interface{}, format string, args []interface{}) (string, []interface{}) { - if format != "" { - format += "\n%s" - } else { - format = "%s" - } - - var stackified *errors.Error - stackified, ok := err.(*errors.Error) - if ok == false { - stackified = errors.Wrap(err, 2) - } - - args = append(args, stackified.ErrorStack()) - - return format, args -} - -func (l *Logger) Errorf(ctx context.Context, errRaw interface{}, format string, args ...interface{}) { - l.doConfigure(false) - - var err interface{} - - if errRaw != nil { - _, ok := errRaw.(*errors.Error) - if ok == true { - err = errRaw - } else { - err = errors.Wrap(errRaw, 1) - } - } - - if l.la != nil { - if errRaw != nil { - format, args = l.mergeStack(err, format, args) - } - - l.log(ctx, LevelError, l.la.Errorf, format, args) - } -} - -func (l *Logger) ErrorIff(ctx context.Context, errRaw interface{}, format string, args ...interface{}) { - if errRaw == nil { - return - } - - var err interface{} - - _, ok := errRaw.(*errors.Error) - if ok == true { - err = errRaw - } else { - err = errors.Wrap(errRaw, 1) - } - - l.Errorf(ctx, err, format, args...) -} - -func (l *Logger) Panicf(ctx context.Context, errRaw interface{}, format string, args ...interface{}) { - l.doConfigure(false) - - var err interface{} - - _, ok := errRaw.(*errors.Error) - if ok == true { - err = errRaw - } else { - err = errors.Wrap(errRaw, 1) - } - - if l.la != nil { - format, args = l.mergeStack(err, format, args) - err = l.log(ctx, LevelError, l.la.Errorf, format, args) - } - - Panic(err.(error)) -} - -func (l *Logger) PanicIff(ctx context.Context, errRaw interface{}, format string, args ...interface{}) { - if errRaw == nil { - return - } - - var err interface{} - - _, ok := errRaw.(*errors.Error) - if ok == true { - err = errRaw - } else { - err = errors.Wrap(errRaw, 1) - } - - l.Panicf(ctx, err.(error), format, args...) -} - -func Wrap(err interface{}) *errors.Error { - es, ok := err.(*errors.Error) - if ok == true { - return es - } else { - return errors.Wrap(err, 1) - } -} - -func Errorf(message string, args ...interface{}) *errors.Error { - err := fmt.Errorf(message, args...) - return errors.Wrap(err, 1) -} - -func Panic(err interface{}) { - _, ok := err.(*errors.Error) - if ok == true { - panic(err) - } else { - panic(errors.Wrap(err, 1)) - } -} - -func Panicf(message string, args ...interface{}) { - err := Errorf(message, args...) - Panic(err) -} - -func PanicIf(err interface{}) { - if err == nil { - return - } - - _, ok := err.(*errors.Error) - if ok == true { - panic(err) - } else { - panic(errors.Wrap(err, 1)) - } -} - -// Is checks if the left ("actual") error equals the right ("against") error. -// The right must be an unwrapped error (the kind that you'd initialize as a -// global variable). The left can be a wrapped or unwrapped error. -func Is(actual, against error) bool { - // If it's an unwrapped error. - if _, ok := actual.(*errors.Error); ok == false { - return actual == against - } - - return errors.Is(actual, against) -} - -// Print is a utility function to prevent the caller from having to import the -// third-party library. -func PrintError(err error) { - wrapped := Wrap(err) - fmt.Printf("Stack:\n\n%s\n", wrapped.ErrorStack()) -} - -// PrintErrorf is a utility function to prevent the caller from having to -// import the third-party library. -func PrintErrorf(err error, format string, args ...interface{}) { - wrapped := Wrap(err) - - fmt.Printf(format, args...) - fmt.Printf("\n") - fmt.Printf("Stack:\n\n%s\n", wrapped.ErrorStack()) -} - -func init() { - if format == "" { - format = defaultFormat - } - - if levelName == "" { - levelName = defaultLevelName - } - - if includeNouns != "" { - for _, noun := range strings.Split(includeNouns, ",") { - AddIncludeFilter(noun) - } - } - - if excludeNouns != "" { - for _, noun := range strings.Split(excludeNouns, ",") { - AddExcludeFilter(noun) - } - } - - if excludeBypassLevelName != "" { - var found bool - if excludeBypassLevel, found = LevelNameMap[excludeBypassLevelName]; found == false { - panic(ErrExcludeLevelNameInvalid) - } - } -} |