all: replace log15 with slog (#28187)
This PR replaces Geth's logger package (a fork of [log15](https://github.com/inconshreveable/log15)) with an implementation using slog, a logging library included as part of the Go standard library as of Go1.21. Main changes are as follows: * removes any log handlers that were unused in the Geth codebase. * Json, logfmt, and terminal formatters are now slog handlers. * Verbosity level constants are changed to match slog constant values. Internal translation is done to make this opaque to the user and backwards compatible with existing `--verbosity` and `--vmodule` options. * `--log.backtraceat` and `--log.debug` are removed. The external-facing API is largely the same as the existing Geth logger. Logger method signatures remain unchanged. A small semantic difference is that a `Handler` can only be set once per `Logger` and not changed dynamically. This just means that a new logger must be instantiated every time the handler of the root logger is changed. ---- For users of the `go-ethereum/log` module. If you were using this module for your own project, you will need to change the initialization. If you previously did ```golang log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) ``` You now instead need to do ```golang log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelInfo, true))) ``` See more about reasoning here: https://github.com/ethereum/go-ethereum/issues/28558#issuecomment-1820606613
This commit is contained in:
@@ -1,11 +0,0 @@
|
||||
Contributors to log15:
|
||||
|
||||
- Aaron L
|
||||
- Alan Shreve
|
||||
- Chris Hines
|
||||
- Ciaran Downey
|
||||
- Dmitry Chestnykh
|
||||
- Evan Shaw
|
||||
- Péter Szilágyi
|
||||
- Trevor Gattis
|
||||
- Vincent Vanackere
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
Copyright 2014 Alan Shreve
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,77 +0,0 @@
|
||||

|
||||
|
||||
# log15 [](https://godoc.org/github.com/inconshreveable/log15) [](https://travis-ci.org/inconshreveable/log15)
|
||||
|
||||
Package log15 provides an opinionated, simple toolkit for best-practice logging in Go (golang) that is both human and machine readable. It is modeled after the Go standard library's [`io`](https://golang.org/pkg/io/) and [`net/http`](https://golang.org/pkg/net/http/) packages and is an alternative to the standard library's [`log`](https://golang.org/pkg/log/) package.
|
||||
|
||||
## Features
|
||||
- A simple, easy-to-understand API
|
||||
- Promotes structured logging by encouraging use of key/value pairs
|
||||
- Child loggers which inherit and add their own private context
|
||||
- Lazy evaluation of expensive operations
|
||||
- Simple Handler interface allowing for construction of flexible, custom logging configurations with a tiny API.
|
||||
- Color terminal support
|
||||
- Built-in support for logging to files, streams, syslog, and the network
|
||||
- Support for forking records to multiple handlers, buffering records for output, failing over from failed handler writes, + more
|
||||
|
||||
## Versioning
|
||||
The API of the master branch of log15 should always be considered unstable. If you want to rely on a stable API,
|
||||
you must vendor the library.
|
||||
|
||||
## Importing
|
||||
|
||||
```go
|
||||
import log "github.com/inconshreveable/log15"
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```go
|
||||
// all loggers can have key/value context
|
||||
srvlog := log.New("module", "app/server")
|
||||
|
||||
// all log messages can have key/value context
|
||||
srvlog.Warn("abnormal conn rate", "rate", curRate, "low", lowRate, "high", highRate)
|
||||
|
||||
// child loggers with inherited context
|
||||
connlog := srvlog.New("raddr", c.RemoteAddr())
|
||||
connlog.Info("connection open")
|
||||
|
||||
// lazy evaluation
|
||||
connlog.Debug("ping remote", "latency", log.Lazy{pingRemote})
|
||||
|
||||
// flexible configuration
|
||||
srvlog.SetHandler(log.MultiHandler(
|
||||
log.StreamHandler(os.Stderr, log.LogfmtFormat()),
|
||||
log.LvlFilterHandler(
|
||||
log.LvlError,
|
||||
log.Must.FileHandler("errors.json", log.JSONFormat()))))
|
||||
```
|
||||
|
||||
Will result in output that looks like this:
|
||||
|
||||
```
|
||||
WARN[06-17|21:58:10] abnormal conn rate module=app/server rate=0.500 low=0.100 high=0.800
|
||||
INFO[06-17|21:58:10] connection open module=app/server raddr=10.0.0.1
|
||||
```
|
||||
|
||||
## Breaking API Changes
|
||||
The following commits broke API stability. This reference is intended to help you understand the consequences of updating to a newer version
|
||||
of log15.
|
||||
|
||||
- 57a084d014d4150152b19e4e531399a7145d1540 - Added a `Get()` method to the `Logger` interface to retrieve the current handler
|
||||
- 93404652ee366648fa622b64d1e2b67d75a3094a - `Record` field `Call` changed to `stack.Call` with switch to `github.com/go-stack/stack`
|
||||
- a5e7613673c73281f58e15a87d2cf0cf111e8152 - Restored `syslog.Priority` argument to the `SyslogXxx` handler constructors
|
||||
|
||||
## FAQ
|
||||
|
||||
### The varargs style is brittle and error prone! Can I have type safety please?
|
||||
Yes. Use `log.Ctx`:
|
||||
|
||||
```go
|
||||
srvlog := log.New(log.Ctx{"module": "app/server"})
|
||||
srvlog.Warn("abnormal conn rate", log.Ctx{"rate": curRate, "low": lowRate, "high": highRate})
|
||||
```
|
||||
|
||||
## License
|
||||
Apache
|
||||
@@ -1,5 +0,0 @@
|
||||
This package is a fork of https://github.com/inconshreveable/log15, with some
|
||||
minor modifications required by the go-ethereum codebase:
|
||||
|
||||
* Support for log level `trace`
|
||||
* Modified behavior to exit on `critical` failure
|
||||
-327
@@ -1,327 +0,0 @@
|
||||
/*
|
||||
Package log15 provides an opinionated, simple toolkit for best-practice logging that is
|
||||
both human and machine readable. It is modeled after the standard library's io and net/http
|
||||
packages.
|
||||
|
||||
This package enforces you to only log key/value pairs. Keys must be strings. Values may be
|
||||
any type that you like. The default output format is logfmt, but you may also choose to use
|
||||
JSON instead if that suits you. Here's how you log:
|
||||
|
||||
log.Info("page accessed", "path", r.URL.Path, "user_id", user.id)
|
||||
|
||||
This will output a line that looks like:
|
||||
|
||||
lvl=info t=2014-05-02T16:07:23-0700 msg="page accessed" path=/org/71/profile user_id=9
|
||||
|
||||
# Getting Started
|
||||
|
||||
To get started, you'll want to import the library:
|
||||
|
||||
import log "github.com/inconshreveable/log15"
|
||||
|
||||
Now you're ready to start logging:
|
||||
|
||||
func main() {
|
||||
log.Info("Program starting", "args", os.Args())
|
||||
}
|
||||
|
||||
# Convention
|
||||
|
||||
Because recording a human-meaningful message is common and good practice, the first argument to every
|
||||
logging method is the value to the *implicit* key 'msg'.
|
||||
|
||||
Additionally, the level you choose for a message will be automatically added with the key 'lvl', and so
|
||||
will the current timestamp with key 't'.
|
||||
|
||||
You may supply any additional context as a set of key/value pairs to the logging function. log15 allows
|
||||
you to favor terseness, ordering, and speed over safety. This is a reasonable tradeoff for
|
||||
logging functions. You don't need to explicitly state keys/values, log15 understands that they alternate
|
||||
in the variadic argument list:
|
||||
|
||||
log.Warn("size out of bounds", "low", lowBound, "high", highBound, "val", val)
|
||||
|
||||
If you really do favor your type-safety, you may choose to pass a log.Ctx instead:
|
||||
|
||||
log.Warn("size out of bounds", log.Ctx{"low": lowBound, "high": highBound, "val": val})
|
||||
|
||||
# Context loggers
|
||||
|
||||
Frequently, you want to add context to a logger so that you can track actions associated with it. An http
|
||||
request is a good example. You can easily create new loggers that have context that is automatically included
|
||||
with each log line:
|
||||
|
||||
requestlogger := log.New("path", r.URL.Path)
|
||||
|
||||
// later
|
||||
requestlogger.Debug("db txn commit", "duration", txnTimer.Finish())
|
||||
|
||||
This will output a log line that includes the path context that is attached to the logger:
|
||||
|
||||
lvl=dbug t=2014-05-02T16:07:23-0700 path=/repo/12/add_hook msg="db txn commit" duration=0.12
|
||||
|
||||
# Handlers
|
||||
|
||||
The Handler interface defines where log lines are printed to and how they are formatted. Handler is a
|
||||
single interface that is inspired by net/http's handler interface:
|
||||
|
||||
type Handler interface {
|
||||
Log(r *Record) error
|
||||
}
|
||||
|
||||
Handlers can filter records, format them, or dispatch to multiple other Handlers.
|
||||
This package implements a number of Handlers for common logging patterns that are
|
||||
easily composed to create flexible, custom logging structures.
|
||||
|
||||
Here's an example handler that prints logfmt output to Stdout:
|
||||
|
||||
handler := log.StreamHandler(os.Stdout, log.LogfmtFormat())
|
||||
|
||||
Here's an example handler that defers to two other handlers. One handler only prints records
|
||||
from the rpc package in logfmt to standard out. The other prints records at Error level
|
||||
or above in JSON formatted output to the file /var/log/service.json
|
||||
|
||||
handler := log.MultiHandler(
|
||||
log.LvlFilterHandler(log.LvlError, log.Must.FileHandler("/var/log/service.json", log.JSONFormat())),
|
||||
log.MatchFilterHandler("pkg", "app/rpc" log.StdoutHandler())
|
||||
)
|
||||
|
||||
# Logging File Names and Line Numbers
|
||||
|
||||
This package implements three Handlers that add debugging information to the
|
||||
context, CallerFileHandler, CallerFuncHandler and CallerStackHandler. Here's
|
||||
an example that adds the source file and line number of each logging call to
|
||||
the context.
|
||||
|
||||
h := log.CallerFileHandler(log.StdoutHandler)
|
||||
log.Root().SetHandler(h)
|
||||
...
|
||||
log.Error("open file", "err", err)
|
||||
|
||||
This will output a line that looks like:
|
||||
|
||||
lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" caller=data.go:42
|
||||
|
||||
Here's an example that logs the call stack rather than just the call site.
|
||||
|
||||
h := log.CallerStackHandler("%+v", log.StdoutHandler)
|
||||
log.Root().SetHandler(h)
|
||||
...
|
||||
log.Error("open file", "err", err)
|
||||
|
||||
This will output a line that looks like:
|
||||
|
||||
lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" stack="[pkg/data.go:42 pkg/cmd/main.go]"
|
||||
|
||||
The "%+v" format instructs the handler to include the path of the source file
|
||||
relative to the compile time GOPATH. The github.com/go-stack/stack package
|
||||
documents the full list of formatting verbs and modifiers available.
|
||||
|
||||
# Custom Handlers
|
||||
|
||||
The Handler interface is so simple that it's also trivial to write your own. Let's create an
|
||||
example handler which tries to write to one handler, but if that fails it falls back to
|
||||
writing to another handler and includes the error that it encountered when trying to write
|
||||
to the primary. This might be useful when trying to log over a network socket, but if that
|
||||
fails you want to log those records to a file on disk.
|
||||
|
||||
type BackupHandler struct {
|
||||
Primary Handler
|
||||
Secondary Handler
|
||||
}
|
||||
|
||||
func (h *BackupHandler) Log (r *Record) error {
|
||||
err := h.Primary.Log(r)
|
||||
if err != nil {
|
||||
r.Ctx = append(ctx, "primary_err", err)
|
||||
return h.Secondary.Log(r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
This pattern is so useful that a generic version that handles an arbitrary number of Handlers
|
||||
is included as part of this library called FailoverHandler.
|
||||
|
||||
# Logging Expensive Operations
|
||||
|
||||
Sometimes, you want to log values that are extremely expensive to compute, but you don't want to pay
|
||||
the price of computing them if you haven't turned up your logging level to a high level of detail.
|
||||
|
||||
This package provides a simple type to annotate a logging operation that you want to be evaluated
|
||||
lazily, just when it is about to be logged, so that it would not be evaluated if an upstream Handler
|
||||
filters it out. Just wrap any function which takes no arguments with the log.Lazy type. For example:
|
||||
|
||||
func factorRSAKey() (factors []int) {
|
||||
// return the factors of a very large number
|
||||
}
|
||||
|
||||
log.Debug("factors", log.Lazy{factorRSAKey})
|
||||
|
||||
If this message is not logged for any reason (like logging at the Error level), then
|
||||
factorRSAKey is never evaluated.
|
||||
|
||||
# Dynamic context values
|
||||
|
||||
The same log.Lazy mechanism can be used to attach context to a logger which you want to be
|
||||
evaluated when the message is logged, but not when the logger is created. For example, let's imagine
|
||||
a game where you have Player objects:
|
||||
|
||||
type Player struct {
|
||||
name string
|
||||
alive bool
|
||||
log.Logger
|
||||
}
|
||||
|
||||
You always want to log a player's name and whether they're alive or dead, so when you create the player
|
||||
object, you might do:
|
||||
|
||||
p := &Player{name: name, alive: true}
|
||||
p.Logger = log.New("name", p.name, "alive", p.alive)
|
||||
|
||||
Only now, even after a player has died, the logger will still report they are alive because the logging
|
||||
context is evaluated when the logger was created. By using the Lazy wrapper, we can defer the evaluation
|
||||
of whether the player is alive or not to each log message, so that the log records will reflect the player's
|
||||
current state no matter when the log message is written:
|
||||
|
||||
p := &Player{name: name, alive: true}
|
||||
isAlive := func() bool { return p.alive }
|
||||
player.Logger = log.New("name", p.name, "alive", log.Lazy{isAlive})
|
||||
|
||||
# Terminal Format
|
||||
|
||||
If log15 detects that stdout is a terminal, it will configure the default
|
||||
handler for it (which is log.StdoutHandler) to use TerminalFormat. This format
|
||||
logs records nicely for your terminal, including color-coded output based
|
||||
on log level.
|
||||
|
||||
# Error Handling
|
||||
|
||||
Becasuse log15 allows you to step around the type system, there are a few ways you can specify
|
||||
invalid arguments to the logging functions. You could, for example, wrap something that is not
|
||||
a zero-argument function with log.Lazy or pass a context key that is not a string. Since logging libraries
|
||||
are typically the mechanism by which errors are reported, it would be onerous for the logging functions
|
||||
to return errors. Instead, log15 handles errors by making these guarantees to you:
|
||||
|
||||
- Any log record containing an error will still be printed with the error explained to you as part of the log record.
|
||||
|
||||
- Any log record containing an error will include the context key LOG15_ERROR, enabling you to easily
|
||||
(and if you like, automatically) detect if any of your logging calls are passing bad values.
|
||||
|
||||
Understanding this, you might wonder why the Handler interface can return an error value in its Log method. Handlers
|
||||
are encouraged to return errors only if they fail to write their log records out to an external source like if the
|
||||
syslog daemon is not responding. This allows the construction of useful handlers which cope with those failures
|
||||
like the FailoverHandler.
|
||||
|
||||
# Library Use
|
||||
|
||||
log15 is intended to be useful for library authors as a way to provide configurable logging to
|
||||
users of their library. Best practice for use in a library is to always disable all output for your logger
|
||||
by default and to provide a public Logger instance that consumers of your library can configure. Like so:
|
||||
|
||||
package yourlib
|
||||
|
||||
import "github.com/inconshreveable/log15"
|
||||
|
||||
var Log = log.New()
|
||||
|
||||
func init() {
|
||||
Log.SetHandler(log.DiscardHandler())
|
||||
}
|
||||
|
||||
Users of your library may then enable it if they like:
|
||||
|
||||
import "github.com/inconshreveable/log15"
|
||||
import "example.com/yourlib"
|
||||
|
||||
func main() {
|
||||
handler := // custom handler setup
|
||||
yourlib.Log.SetHandler(handler)
|
||||
}
|
||||
|
||||
# Best practices attaching logger context
|
||||
|
||||
The ability to attach context to a logger is a powerful one. Where should you do it and why?
|
||||
I favor embedding a Logger directly into any persistent object in my application and adding
|
||||
unique, tracing context keys to it. For instance, imagine I am writing a web browser:
|
||||
|
||||
type Tab struct {
|
||||
url string
|
||||
render *RenderingContext
|
||||
// ...
|
||||
|
||||
Logger
|
||||
}
|
||||
|
||||
func NewTab(url string) *Tab {
|
||||
return &Tab {
|
||||
// ...
|
||||
url: url,
|
||||
|
||||
Logger: log.New("url", url),
|
||||
}
|
||||
}
|
||||
|
||||
When a new tab is created, I assign a logger to it with the url of
|
||||
the tab as context so it can easily be traced through the logs.
|
||||
Now, whenever we perform any operation with the tab, we'll log with its
|
||||
embedded logger and it will include the tab title automatically:
|
||||
|
||||
tab.Debug("moved position", "idx", tab.idx)
|
||||
|
||||
There's only one problem. What if the tab url changes? We could
|
||||
use log.Lazy to make sure the current url is always written, but that
|
||||
would mean that we couldn't trace a tab's full lifetime through our
|
||||
logs after the user navigate to a new URL.
|
||||
|
||||
Instead, think about what values to attach to your loggers the
|
||||
same way you think about what to use as a key in a SQL database schema.
|
||||
If it's possible to use a natural key that is unique for the lifetime of the
|
||||
object, do so. But otherwise, log15's ext package has a handy RandId
|
||||
function to let you generate what you might call "surrogate keys"
|
||||
They're just random hex identifiers to use for tracing. Back to our
|
||||
Tab example, we would prefer to set up our Logger like so:
|
||||
|
||||
import logext "github.com/inconshreveable/log15/ext"
|
||||
|
||||
t := &Tab {
|
||||
// ...
|
||||
url: url,
|
||||
}
|
||||
|
||||
t.Logger = log.New("id", logext.RandId(8), "url", log.Lazy{t.getUrl})
|
||||
return t
|
||||
|
||||
Now we'll have a unique traceable identifier even across loading new urls, but
|
||||
we'll still be able to see the tab's current url in the log messages.
|
||||
|
||||
# Must
|
||||
|
||||
For all Handler functions which can return an error, there is a version of that
|
||||
function which will return no error but panics on failure. They are all available
|
||||
on the Must object. For example:
|
||||
|
||||
log.Must.FileHandler("/path", log.JSONFormat)
|
||||
log.Must.NetHandler("tcp", ":1234", log.JSONFormat)
|
||||
|
||||
# Inspiration and Credit
|
||||
|
||||
All of the following excellent projects inspired the design of this library:
|
||||
|
||||
code.google.com/p/log4go
|
||||
|
||||
github.com/op/go-logging
|
||||
|
||||
github.com/technoweenie/grohl
|
||||
|
||||
github.com/Sirupsen/logrus
|
||||
|
||||
github.com/kr/logfmt
|
||||
|
||||
github.com/spacemonkeygo/spacelog
|
||||
|
||||
golang's stdlib, notably io and net/http
|
||||
|
||||
# The Name
|
||||
|
||||
https://xkcd.com/927/
|
||||
*/
|
||||
package log
|
||||
+66
-271
@@ -2,18 +2,15 @@ package log
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/holiman/uint256"
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -24,61 +21,19 @@ const (
|
||||
termCtxMaxPadding = 40
|
||||
)
|
||||
|
||||
// ResetGlobalState resets the fieldPadding, which is useful for producing
|
||||
// predictable output.
|
||||
func ResetGlobalState() {
|
||||
fieldPaddingLock.Lock()
|
||||
fieldPadding = make(map[string]int)
|
||||
fieldPaddingLock.Unlock()
|
||||
}
|
||||
|
||||
// locationTrims are trimmed for display to avoid unwieldy log lines.
|
||||
var locationTrims = []string{
|
||||
"github.com/ethereum/go-ethereum/",
|
||||
}
|
||||
|
||||
// PrintOrigins sets or unsets log location (file:line) printing for terminal
|
||||
// format output.
|
||||
func PrintOrigins(print bool) {
|
||||
locationEnabled.Store(print)
|
||||
if print {
|
||||
stackEnabled.Store(true)
|
||||
}
|
||||
}
|
||||
|
||||
// stackEnabled is an atomic flag controlling whether the log handler needs
|
||||
// to store the callsite stack. This is needed in case any handler wants to
|
||||
// print locations (locationEnabled), use vmodule, or print full stacks (BacktraceAt).
|
||||
var stackEnabled atomic.Bool
|
||||
|
||||
// locationEnabled is an atomic flag controlling whether the terminal formatter
|
||||
// should append the log locations too when printing entries.
|
||||
var locationEnabled atomic.Bool
|
||||
|
||||
// locationLength is the maxmimum path length encountered, which all logs are
|
||||
// padded to to aid in alignment.
|
||||
var locationLength atomic.Uint32
|
||||
|
||||
// fieldPadding is a global map with maximum field value lengths seen until now
|
||||
// to allow padding log contexts in a bit smarter way.
|
||||
var fieldPadding = make(map[string]int)
|
||||
|
||||
// fieldPaddingLock is a global mutex protecting the field padding map.
|
||||
var fieldPaddingLock sync.RWMutex
|
||||
|
||||
type Format interface {
|
||||
Format(r *Record) []byte
|
||||
Format(r slog.Record) []byte
|
||||
}
|
||||
|
||||
// FormatFunc returns a new Format object which uses
|
||||
// the given function to perform record formatting.
|
||||
func FormatFunc(f func(*Record) []byte) Format {
|
||||
func FormatFunc(f func(slog.Record) []byte) Format {
|
||||
return formatFunc(f)
|
||||
}
|
||||
|
||||
type formatFunc func(*Record) []byte
|
||||
type formatFunc func(slog.Record) []byte
|
||||
|
||||
func (f formatFunc) Format(r *Record) []byte {
|
||||
func (f formatFunc) Format(r slog.Record) []byte {
|
||||
return f(r)
|
||||
}
|
||||
|
||||
@@ -89,263 +44,100 @@ type TerminalStringer interface {
|
||||
TerminalString() string
|
||||
}
|
||||
|
||||
// TerminalFormat formats log records optimized for human readability on
|
||||
// a terminal with color-coded level output and terser human friendly timestamp.
|
||||
// This format should only be used for interactive programs or while developing.
|
||||
//
|
||||
// [LEVEL] [TIME] MESSAGE key=value key=value ...
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// [DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002
|
||||
func TerminalFormat(usecolor bool) Format {
|
||||
return FormatFunc(func(r *Record) []byte {
|
||||
msg := escapeMessage(r.Msg)
|
||||
var color = 0
|
||||
if usecolor {
|
||||
switch r.Lvl {
|
||||
case LvlCrit:
|
||||
color = 35
|
||||
case LvlError:
|
||||
color = 31
|
||||
case LvlWarn:
|
||||
color = 33
|
||||
case LvlInfo:
|
||||
color = 32
|
||||
case LvlDebug:
|
||||
color = 36
|
||||
case LvlTrace:
|
||||
color = 34
|
||||
}
|
||||
func (h *TerminalHandler) TerminalFormat(r slog.Record, usecolor bool) []byte {
|
||||
msg := escapeMessage(r.Message)
|
||||
var color = 0
|
||||
if usecolor {
|
||||
switch r.Level {
|
||||
case LevelCrit:
|
||||
color = 35
|
||||
case slog.LevelError:
|
||||
color = 31
|
||||
case slog.LevelWarn:
|
||||
color = 33
|
||||
case slog.LevelInfo:
|
||||
color = 32
|
||||
case slog.LevelDebug:
|
||||
color = 36
|
||||
case LevelTrace:
|
||||
color = 34
|
||||
}
|
||||
}
|
||||
|
||||
b := &bytes.Buffer{}
|
||||
lvl := r.Lvl.AlignedString()
|
||||
if locationEnabled.Load() {
|
||||
// Log origin printing was requested, format the location path and line number
|
||||
location := fmt.Sprintf("%+v", r.Call)
|
||||
for _, prefix := range locationTrims {
|
||||
location = strings.TrimPrefix(location, prefix)
|
||||
}
|
||||
// Maintain the maximum location length for fancyer alignment
|
||||
align := int(locationLength.Load())
|
||||
if align < len(location) {
|
||||
align = len(location)
|
||||
locationLength.Store(uint32(align))
|
||||
}
|
||||
padding := strings.Repeat(" ", align-len(location))
|
||||
b := &bytes.Buffer{}
|
||||
lvl := LevelAlignedString(r.Level)
|
||||
if color > 0 {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), msg)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), msg)
|
||||
}
|
||||
// try to justify the log output for short messages
|
||||
length := utf8.RuneCountInString(msg)
|
||||
if r.NumAttrs() > 0 && length < termMsgJust {
|
||||
b.Write(bytes.Repeat([]byte{' '}, termMsgJust-length))
|
||||
}
|
||||
// print the keys logfmt style
|
||||
h.logfmt(b, r, color)
|
||||
|
||||
// Assemble and print the log heading
|
||||
if color > 0 {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s|%s]%s %s ", color, lvl, r.Time.Format(termTimeFormat), location, padding, msg)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s[%s|%s]%s %s ", lvl, r.Time.Format(termTimeFormat), location, padding, msg)
|
||||
}
|
||||
} else {
|
||||
if color > 0 {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), msg)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), msg)
|
||||
}
|
||||
}
|
||||
// try to justify the log output for short messages
|
||||
length := utf8.RuneCountInString(msg)
|
||||
if len(r.Ctx) > 0 && length < termMsgJust {
|
||||
b.Write(bytes.Repeat([]byte{' '}, termMsgJust-length))
|
||||
}
|
||||
// print the keys logfmt style
|
||||
logfmt(b, r.Ctx, color, true)
|
||||
return b.Bytes()
|
||||
})
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable
|
||||
// format for key/value pairs.
|
||||
//
|
||||
// For more details see: http://godoc.org/github.com/kr/logfmt
|
||||
func LogfmtFormat() Format {
|
||||
return FormatFunc(func(r *Record) []byte {
|
||||
common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
|
||||
buf := &bytes.Buffer{}
|
||||
logfmt(buf, append(common, r.Ctx...), 0, false)
|
||||
return buf.Bytes()
|
||||
func (h *TerminalHandler) logfmt(buf *bytes.Buffer, r slog.Record, color int) {
|
||||
attrs := []slog.Attr{}
|
||||
r.Attrs(func(attr slog.Attr) bool {
|
||||
attrs = append(attrs, attr)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func logfmt(buf *bytes.Buffer, ctx []interface{}, color int, term bool) {
|
||||
for i := 0; i < len(ctx); i += 2 {
|
||||
attrs = append(h.attrs, attrs...)
|
||||
|
||||
for i, attr := range attrs {
|
||||
if i != 0 {
|
||||
buf.WriteByte(' ')
|
||||
}
|
||||
|
||||
k, ok := ctx[i].(string)
|
||||
v := formatLogfmtValue(ctx[i+1], term)
|
||||
if !ok {
|
||||
k, v = errorKey, fmt.Sprintf("%+T is not a string key", ctx[i])
|
||||
} else {
|
||||
k = escapeString(k)
|
||||
}
|
||||
key := escapeString(attr.Key)
|
||||
rawVal := attr.Value.Any()
|
||||
val := FormatLogfmtValue(rawVal, true)
|
||||
|
||||
// XXX: we should probably check that all of your key bytes aren't invalid
|
||||
fieldPaddingLock.RLock()
|
||||
padding := fieldPadding[k]
|
||||
fieldPaddingLock.RUnlock()
|
||||
// TODO (jwasinger) above comment was from log15 code. what does it mean? check that key bytes are ascii characters?
|
||||
padding := h.fieldPadding[key]
|
||||
|
||||
length := utf8.RuneCountInString(v)
|
||||
length := utf8.RuneCountInString(val)
|
||||
if padding < length && length <= termCtxMaxPadding {
|
||||
padding = length
|
||||
|
||||
fieldPaddingLock.Lock()
|
||||
fieldPadding[k] = padding
|
||||
fieldPaddingLock.Unlock()
|
||||
h.fieldPadding[key] = padding
|
||||
}
|
||||
if color > 0 {
|
||||
fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=", color, k)
|
||||
fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=", color, key)
|
||||
} else {
|
||||
buf.WriteString(k)
|
||||
buf.WriteString(key)
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
buf.WriteString(v)
|
||||
if i < len(ctx)-2 && padding > length {
|
||||
buf.WriteString(val)
|
||||
if i < r.NumAttrs()-1 && padding > length {
|
||||
buf.Write(bytes.Repeat([]byte{' '}, padding-length))
|
||||
}
|
||||
}
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
|
||||
// JSONFormat formats log records as JSON objects separated by newlines.
|
||||
// It is the equivalent of JSONFormatEx(false, true).
|
||||
func JSONFormat() Format {
|
||||
return JSONFormatEx(false, true)
|
||||
}
|
||||
|
||||
// JSONFormatOrderedEx formats log records as JSON arrays. If pretty is true,
|
||||
// records will be pretty-printed. If lineSeparated is true, records
|
||||
// will be logged with a new line between each record.
|
||||
func JSONFormatOrderedEx(pretty, lineSeparated bool) Format {
|
||||
jsonMarshal := json.Marshal
|
||||
if pretty {
|
||||
jsonMarshal = func(v interface{}) ([]byte, error) {
|
||||
return json.MarshalIndent(v, "", " ")
|
||||
}
|
||||
// formatValue formats a value for serialization
|
||||
func FormatLogfmtValue(value interface{}, term bool) (result string) {
|
||||
if value == nil {
|
||||
return "<nil>"
|
||||
}
|
||||
return FormatFunc(func(r *Record) []byte {
|
||||
props := map[string]interface{}{
|
||||
r.KeyNames.Time: r.Time,
|
||||
r.KeyNames.Lvl: r.Lvl.String(),
|
||||
r.KeyNames.Msg: r.Msg,
|
||||
}
|
||||
|
||||
ctx := make([]string, len(r.Ctx))
|
||||
for i := 0; i < len(r.Ctx); i += 2 {
|
||||
if k, ok := r.Ctx[i].(string); ok {
|
||||
ctx[i] = k
|
||||
ctx[i+1] = formatLogfmtValue(r.Ctx[i+1], true)
|
||||
} else {
|
||||
props[errorKey] = fmt.Sprintf("%+T is not a string key,", r.Ctx[i])
|
||||
}
|
||||
}
|
||||
props[r.KeyNames.Ctx] = ctx
|
||||
|
||||
b, err := jsonMarshal(props)
|
||||
if err != nil {
|
||||
b, _ = jsonMarshal(map[string]string{
|
||||
errorKey: err.Error(),
|
||||
})
|
||||
return b
|
||||
}
|
||||
if lineSeparated {
|
||||
b = append(b, '\n')
|
||||
}
|
||||
return b
|
||||
})
|
||||
}
|
||||
|
||||
// JSONFormatEx formats log records as JSON objects. If pretty is true,
|
||||
// records will be pretty-printed. If lineSeparated is true, records
|
||||
// will be logged with a new line between each record.
|
||||
func JSONFormatEx(pretty, lineSeparated bool) Format {
|
||||
jsonMarshal := json.Marshal
|
||||
if pretty {
|
||||
jsonMarshal = func(v interface{}) ([]byte, error) {
|
||||
return json.MarshalIndent(v, "", " ")
|
||||
}
|
||||
}
|
||||
|
||||
return FormatFunc(func(r *Record) []byte {
|
||||
props := map[string]interface{}{
|
||||
r.KeyNames.Time: r.Time,
|
||||
r.KeyNames.Lvl: r.Lvl.String(),
|
||||
r.KeyNames.Msg: r.Msg,
|
||||
}
|
||||
|
||||
for i := 0; i < len(r.Ctx); i += 2 {
|
||||
k, ok := r.Ctx[i].(string)
|
||||
if !ok {
|
||||
props[errorKey] = fmt.Sprintf("%+T is not a string key", r.Ctx[i])
|
||||
} else {
|
||||
props[k] = formatJSONValue(r.Ctx[i+1])
|
||||
}
|
||||
}
|
||||
|
||||
b, err := jsonMarshal(props)
|
||||
if err != nil {
|
||||
b, _ = jsonMarshal(map[string]string{
|
||||
errorKey: err.Error(),
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
if lineSeparated {
|
||||
b = append(b, '\n')
|
||||
}
|
||||
|
||||
return b
|
||||
})
|
||||
}
|
||||
|
||||
func formatShared(value interface{}) (result interface{}) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() {
|
||||
result = "nil"
|
||||
result = "<nil>"
|
||||
} else {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
switch v := value.(type) {
|
||||
case time.Time:
|
||||
return v.Format(timeFormat)
|
||||
|
||||
case error:
|
||||
return v.Error()
|
||||
|
||||
case fmt.Stringer:
|
||||
return v.String()
|
||||
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func formatJSONValue(value interface{}) interface{} {
|
||||
value = formatShared(value)
|
||||
switch value.(type) {
|
||||
case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string:
|
||||
return value
|
||||
default:
|
||||
return fmt.Sprintf("%+v", value)
|
||||
}
|
||||
}
|
||||
|
||||
// formatValue formats a value for serialization
|
||||
func formatLogfmtValue(value interface{}, term bool) string {
|
||||
if value == nil {
|
||||
return "nil"
|
||||
}
|
||||
|
||||
switch v := value.(type) {
|
||||
case time.Time:
|
||||
// Performance optimization: No need for escaping since the provided
|
||||
@@ -375,8 +167,11 @@ func formatLogfmtValue(value interface{}, term bool) string {
|
||||
return escapeString(s.TerminalString())
|
||||
}
|
||||
}
|
||||
value = formatShared(value)
|
||||
switch v := value.(type) {
|
||||
case error:
|
||||
return escapeString(v.Error())
|
||||
case fmt.Stringer:
|
||||
return escapeString(v.String())
|
||||
case bool:
|
||||
return strconv.FormatBool(v)
|
||||
case float32:
|
||||
|
||||
+176
-328
@@ -1,301 +1,25 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-stack/stack"
|
||||
"github.com/holiman/uint256"
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
// Handler defines where and how log records are written.
|
||||
// A Logger prints its log records by writing to a Handler.
|
||||
// Handlers are composable, providing you great flexibility in combining
|
||||
// them to achieve the logging structure that suits your applications.
|
||||
type Handler interface {
|
||||
Log(r *Record) error
|
||||
}
|
||||
|
||||
// FuncHandler returns a Handler that logs records with the given
|
||||
// function.
|
||||
func FuncHandler(fn func(r *Record) error) Handler {
|
||||
return funcHandler(fn)
|
||||
}
|
||||
|
||||
type funcHandler func(r *Record) error
|
||||
|
||||
func (h funcHandler) Log(r *Record) error {
|
||||
return h(r)
|
||||
}
|
||||
|
||||
// StreamHandler writes log records to an io.Writer
|
||||
// with the given format. StreamHandler can be used
|
||||
// to easily begin writing log records to other
|
||||
// outputs.
|
||||
// Lazy allows you to defer calculation of a logged value that is expensive
|
||||
// to compute until it is certain that it must be evaluated with the given filters.
|
||||
//
|
||||
// StreamHandler wraps itself with LazyHandler and SyncHandler
|
||||
// to evaluate Lazy objects and perform safe concurrent writes.
|
||||
func StreamHandler(wr io.Writer, fmtr Format) Handler {
|
||||
h := FuncHandler(func(r *Record) error {
|
||||
_, err := wr.Write(fmtr.Format(r))
|
||||
return err
|
||||
})
|
||||
return LazyHandler(SyncHandler(h))
|
||||
}
|
||||
|
||||
// SyncHandler can be wrapped around a handler to guarantee that
|
||||
// only a single Log operation can proceed at a time. It's necessary
|
||||
// for thread-safe concurrent writes.
|
||||
func SyncHandler(h Handler) Handler {
|
||||
var mu sync.Mutex
|
||||
return FuncHandler(func(r *Record) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
return h.Log(r)
|
||||
})
|
||||
}
|
||||
|
||||
// FileHandler returns a handler which writes log records to the give file
|
||||
// using the given format. If the path
|
||||
// already exists, FileHandler will append to the given file. If it does not,
|
||||
// FileHandler will create the file with mode 0644.
|
||||
func FileHandler(path string, fmtr Format) (Handler, error) {
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return closingHandler{f, StreamHandler(f, fmtr)}, nil
|
||||
}
|
||||
|
||||
// NetHandler opens a socket to the given address and writes records
|
||||
// over the connection.
|
||||
func NetHandler(network, addr string, fmtr Format) (Handler, error) {
|
||||
conn, err := net.Dial(network, addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return closingHandler{conn, StreamHandler(conn, fmtr)}, nil
|
||||
}
|
||||
|
||||
// XXX: closingHandler is essentially unused at the moment
|
||||
// it's meant for a future time when the Handler interface supports
|
||||
// a possible Close() operation
|
||||
type closingHandler struct {
|
||||
io.WriteCloser
|
||||
Handler
|
||||
}
|
||||
|
||||
func (h *closingHandler) Close() error {
|
||||
return h.WriteCloser.Close()
|
||||
}
|
||||
|
||||
// CallerFileHandler returns a Handler that adds the line number and file of
|
||||
// the calling function to the context with key "caller".
|
||||
func CallerFileHandler(h Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
r.Ctx = append(r.Ctx, "caller", fmt.Sprint(r.Call))
|
||||
return h.Log(r)
|
||||
})
|
||||
}
|
||||
|
||||
// CallerFuncHandler returns a Handler that adds the calling function name to
|
||||
// the context with key "fn".
|
||||
func CallerFuncHandler(h Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
r.Ctx = append(r.Ctx, "fn", formatCall("%+n", r.Call))
|
||||
return h.Log(r)
|
||||
})
|
||||
}
|
||||
|
||||
// This function is here to please go vet on Go < 1.8.
|
||||
func formatCall(format string, c stack.Call) string {
|
||||
return fmt.Sprintf(format, c)
|
||||
}
|
||||
|
||||
// CallerStackHandler returns a Handler that adds a stack trace to the context
|
||||
// with key "stack". The stack trace is formatted as a space separated list of
|
||||
// call sites inside matching []'s. The most recent call site is listed first.
|
||||
// Each call site is formatted according to format. See the documentation of
|
||||
// package github.com/go-stack/stack for the list of supported formats.
|
||||
func CallerStackHandler(format string, h Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
s := stack.Trace().TrimBelow(r.Call).TrimRuntime()
|
||||
if len(s) > 0 {
|
||||
r.Ctx = append(r.Ctx, "stack", fmt.Sprintf(format, s))
|
||||
}
|
||||
return h.Log(r)
|
||||
})
|
||||
}
|
||||
|
||||
// FilterHandler returns a Handler that only writes records to the
|
||||
// wrapped Handler if the given function evaluates true. For example,
|
||||
// to only log records where the 'err' key is not nil:
|
||||
//
|
||||
// logger.SetHandler(FilterHandler(func(r *Record) bool {
|
||||
// for i := 0; i < len(r.Ctx); i += 2 {
|
||||
// if r.Ctx[i] == "err" {
|
||||
// return r.Ctx[i+1] != nil
|
||||
// }
|
||||
// }
|
||||
// return false
|
||||
// }, h))
|
||||
func FilterHandler(fn func(r *Record) bool, h Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
if fn(r) {
|
||||
return h.Log(r)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// MatchFilterHandler returns a Handler that only writes records
|
||||
// to the wrapped Handler if the given key in the logged
|
||||
// context matches the value. For example, to only log records
|
||||
// from your ui package:
|
||||
//
|
||||
// log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler)
|
||||
func MatchFilterHandler(key string, value interface{}, h Handler) Handler {
|
||||
return FilterHandler(func(r *Record) (pass bool) {
|
||||
switch key {
|
||||
case r.KeyNames.Lvl:
|
||||
return r.Lvl == value
|
||||
case r.KeyNames.Time:
|
||||
return r.Time == value
|
||||
case r.KeyNames.Msg:
|
||||
return r.Msg == value
|
||||
}
|
||||
|
||||
for i := 0; i < len(r.Ctx); i += 2 {
|
||||
if r.Ctx[i] == key {
|
||||
return r.Ctx[i+1] == value
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, h)
|
||||
}
|
||||
|
||||
// LvlFilterHandler returns a Handler that only writes
|
||||
// records which are less than the given verbosity
|
||||
// level to the wrapped Handler. For example, to only
|
||||
// log Error/Crit records:
|
||||
//
|
||||
// log.LvlFilterHandler(log.LvlError, log.StdoutHandler)
|
||||
func LvlFilterHandler(maxLvl Lvl, h Handler) Handler {
|
||||
return FilterHandler(func(r *Record) (pass bool) {
|
||||
return r.Lvl <= maxLvl
|
||||
}, h)
|
||||
}
|
||||
|
||||
// MultiHandler dispatches any write to each of its handlers.
|
||||
// This is useful for writing different types of log information
|
||||
// to different locations. For example, to log to a file and
|
||||
// standard error:
|
||||
//
|
||||
// log.MultiHandler(
|
||||
// log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
|
||||
// log.StderrHandler)
|
||||
func MultiHandler(hs ...Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
for _, h := range hs {
|
||||
// what to do about failures?
|
||||
h.Log(r)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// FailoverHandler writes all log records to the first handler
|
||||
// specified, but will failover and write to the second handler if
|
||||
// the first handler has failed, and so on for all handlers specified.
|
||||
// For example you might want to log to a network socket, but failover
|
||||
// to writing to a file if the network fails, and then to
|
||||
// standard out if the file write fails:
|
||||
//
|
||||
// log.FailoverHandler(
|
||||
// log.Must.NetHandler("tcp", ":9090", log.JSONFormat()),
|
||||
// log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
|
||||
// log.StdoutHandler)
|
||||
//
|
||||
// All writes that do not go to the first handler will add context with keys of
|
||||
// the form "failover_err_{idx}" which explain the error encountered while
|
||||
// trying to write to the handlers before them in the list.
|
||||
func FailoverHandler(hs ...Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
var err error
|
||||
for i, h := range hs {
|
||||
err = h.Log(r)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
r.Ctx = append(r.Ctx, fmt.Sprintf("failover_err_%d", i), err)
|
||||
}
|
||||
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// ChannelHandler writes all records to the given channel.
|
||||
// It blocks if the channel is full. Useful for async processing
|
||||
// of log messages, it's used by BufferedHandler.
|
||||
func ChannelHandler(recs chan<- *Record) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
recs <- r
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// BufferedHandler writes all records to a buffered
|
||||
// channel of the given size which flushes into the wrapped
|
||||
// handler whenever it is available for writing. Since these
|
||||
// writes happen asynchronously, all writes to a BufferedHandler
|
||||
// never return an error and any errors from the wrapped handler are ignored.
|
||||
func BufferedHandler(bufSize int, h Handler) Handler {
|
||||
recs := make(chan *Record, bufSize)
|
||||
go func() {
|
||||
for m := range recs {
|
||||
_ = h.Log(m)
|
||||
}
|
||||
}()
|
||||
return ChannelHandler(recs)
|
||||
}
|
||||
|
||||
// LazyHandler writes all values to the wrapped handler after evaluating
|
||||
// any lazy functions in the record's context. It is already wrapped
|
||||
// around StreamHandler and SyslogHandler in this library, you'll only need
|
||||
// it if you write your own Handler.
|
||||
func LazyHandler(h Handler) Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
// go through the values (odd indices) and reassign
|
||||
// the values of any lazy fn to the result of its execution
|
||||
hadErr := false
|
||||
for i := 1; i < len(r.Ctx); i += 2 {
|
||||
lz, ok := r.Ctx[i].(Lazy)
|
||||
if ok {
|
||||
v, err := evaluateLazy(lz)
|
||||
if err != nil {
|
||||
hadErr = true
|
||||
r.Ctx[i] = err
|
||||
} else {
|
||||
if cs, ok := v.(stack.CallStack); ok {
|
||||
v = cs.TrimBelow(r.Call).TrimRuntime()
|
||||
}
|
||||
r.Ctx[i] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if hadErr {
|
||||
r.Ctx = append(r.Ctx, errorKey, "bad lazy")
|
||||
}
|
||||
|
||||
return h.Log(r)
|
||||
})
|
||||
// You may wrap any function which takes no arguments to Lazy. It may return any
|
||||
// number of values of any type.
|
||||
type Lazy struct {
|
||||
Fn interface{}
|
||||
}
|
||||
|
||||
func evaluateLazy(lz Lazy) (interface{}, error) {
|
||||
@@ -325,51 +49,175 @@ func evaluateLazy(lz Lazy) (interface{}, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// DiscardHandler reports success for all writes but does nothing.
|
||||
// It is useful for dynamically disabling logging at runtime via
|
||||
// a Logger's SetHandler method.
|
||||
func DiscardHandler() Handler {
|
||||
return FuncHandler(func(r *Record) error {
|
||||
return nil
|
||||
type discardHandler struct{}
|
||||
|
||||
// DiscardHandler returns a no-op handler
|
||||
func DiscardHandler() slog.Handler {
|
||||
return &discardHandler{}
|
||||
}
|
||||
|
||||
func (h *discardHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *discardHandler) Enabled(_ context.Context, level slog.Level) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *discardHandler) WithGroup(name string) slog.Handler {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
func (h *discardHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &discardHandler{}
|
||||
}
|
||||
|
||||
type TerminalHandler struct {
|
||||
mu sync.Mutex
|
||||
wr io.Writer
|
||||
lvl slog.Level
|
||||
useColor bool
|
||||
attrs []slog.Attr
|
||||
// fieldPadding is a map with maximum field value lengths seen until now
|
||||
// to allow padding log contexts in a bit smarter way.
|
||||
fieldPadding map[string]int
|
||||
}
|
||||
|
||||
// NewTerminalHandler returns a handler which formats log records at all levels optimized for human readability on
|
||||
// a terminal with color-coded level output and terser human friendly timestamp.
|
||||
// This format should only be used for interactive programs or while developing.
|
||||
//
|
||||
// [LEVEL] [TIME] MESSAGE key=value key=value ...
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// [DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002
|
||||
func NewTerminalHandler(wr io.Writer, useColor bool) *TerminalHandler {
|
||||
return NewTerminalHandlerWithLevel(wr, levelMaxVerbosity, useColor)
|
||||
}
|
||||
|
||||
// NewTerminalHandlerWithLevel returns the same handler as NewTerminalHandler but only outputs
|
||||
// records which are less than or equal to the specified verbosity level.
|
||||
func NewTerminalHandlerWithLevel(wr io.Writer, lvl slog.Level, useColor bool) *TerminalHandler {
|
||||
return &TerminalHandler{
|
||||
wr: wr,
|
||||
lvl: lvl,
|
||||
useColor: useColor,
|
||||
fieldPadding: make(map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *TerminalHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.wr.Write(h.TerminalFormat(r, h.useColor))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *TerminalHandler) Enabled(_ context.Context, level slog.Level) bool {
|
||||
return level >= h.lvl
|
||||
}
|
||||
|
||||
func (h *TerminalHandler) WithGroup(name string) slog.Handler {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &TerminalHandler{
|
||||
wr: h.wr,
|
||||
lvl: h.lvl,
|
||||
useColor: h.useColor,
|
||||
attrs: append(h.attrs, attrs...),
|
||||
fieldPadding: make(map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
// ResetFieldPadding zeroes the field-padding for all attribute pairs.
|
||||
func (t *TerminalHandler) ResetFieldPadding() {
|
||||
t.mu.Lock()
|
||||
t.fieldPadding = make(map[string]int)
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
type leveler struct{ minLevel slog.Level }
|
||||
|
||||
func (l *leveler) Level() slog.Level {
|
||||
return l.minLevel
|
||||
}
|
||||
|
||||
func JSONHandler(wr io.Writer) slog.Handler {
|
||||
return slog.NewJSONHandler(wr, &slog.HandlerOptions{
|
||||
ReplaceAttr: builtinReplaceJSON,
|
||||
})
|
||||
}
|
||||
|
||||
// Must provides the following Handler creation functions
|
||||
// which instead of returning an error parameter only return a Handler
|
||||
// and panic on failure: FileHandler, NetHandler, SyslogHandler, SyslogNetHandler
|
||||
var Must muster
|
||||
// LogfmtHandler returns a handler which prints records in logfmt format, an easy machine-parseable but human-readable
|
||||
// format for key/value pairs.
|
||||
//
|
||||
// For more details see: http://godoc.org/github.com/kr/logfmt
|
||||
func LogfmtHandler(wr io.Writer) slog.Handler {
|
||||
return slog.NewTextHandler(wr, &slog.HandlerOptions{
|
||||
ReplaceAttr: builtinReplaceLogfmt,
|
||||
})
|
||||
}
|
||||
|
||||
func must(h Handler, err error) Handler {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
// LogfmtHandlerWithLevel returns the same handler as LogfmtHandler but it only outputs
|
||||
// records which are less than or equal to the specified verbosity level.
|
||||
func LogfmtHandlerWithLevel(wr io.Writer, level slog.Level) slog.Handler {
|
||||
return slog.NewTextHandler(wr, &slog.HandlerOptions{
|
||||
ReplaceAttr: builtinReplaceLogfmt,
|
||||
Level: &leveler{level},
|
||||
})
|
||||
}
|
||||
|
||||
func builtinReplaceLogfmt(_ []string, attr slog.Attr) slog.Attr {
|
||||
return builtinReplace(nil, attr, true)
|
||||
}
|
||||
|
||||
func builtinReplaceJSON(_ []string, attr slog.Attr) slog.Attr {
|
||||
return builtinReplace(nil, attr, false)
|
||||
}
|
||||
|
||||
func builtinReplace(_ []string, attr slog.Attr, logfmt bool) slog.Attr {
|
||||
switch attr.Key {
|
||||
case slog.TimeKey:
|
||||
if attr.Value.Kind() == slog.KindTime {
|
||||
if logfmt {
|
||||
return slog.String("t", attr.Value.Time().Format(timeFormat))
|
||||
} else {
|
||||
return slog.Attr{Key: "t", Value: attr.Value}
|
||||
}
|
||||
}
|
||||
case slog.LevelKey:
|
||||
if l, ok := attr.Value.Any().(slog.Level); ok {
|
||||
attr = slog.Any("lvl", LevelString(l))
|
||||
return attr
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
type muster struct{}
|
||||
|
||||
func (m muster) FileHandler(path string, fmtr Format) Handler {
|
||||
return must(FileHandler(path, fmtr))
|
||||
}
|
||||
|
||||
func (m muster) NetHandler(network, addr string, fmtr Format) Handler {
|
||||
return must(NetHandler(network, addr, fmtr))
|
||||
}
|
||||
|
||||
// swapHandler wraps another handler that may be swapped out
|
||||
// dynamically at runtime in a thread-safe fashion.
|
||||
type swapHandler struct {
|
||||
handler atomic.Value
|
||||
}
|
||||
|
||||
func (h *swapHandler) Log(r *Record) error {
|
||||
return (*h.handler.Load().(*Handler)).Log(r)
|
||||
}
|
||||
|
||||
func (h *swapHandler) Swap(newHandler Handler) {
|
||||
h.handler.Store(&newHandler)
|
||||
}
|
||||
|
||||
func (h *swapHandler) Get() Handler {
|
||||
return *h.handler.Load().(*Handler)
|
||||
switch v := attr.Value.Any().(type) {
|
||||
case time.Time:
|
||||
if logfmt {
|
||||
attr = slog.String(attr.Key, v.Format(timeFormat))
|
||||
}
|
||||
case *big.Int:
|
||||
if v == nil {
|
||||
attr.Value = slog.StringValue("<nil>")
|
||||
} else {
|
||||
attr.Value = slog.StringValue(v.String())
|
||||
}
|
||||
case *uint256.Int:
|
||||
if v == nil {
|
||||
attr.Value = slog.StringValue("<nil>")
|
||||
} else {
|
||||
attr.Value = slog.StringValue(v.Dec())
|
||||
}
|
||||
case fmt.Stringer:
|
||||
if v == nil || (reflect.ValueOf(v).Kind() == reflect.Pointer && reflect.ValueOf(v).IsNil()) {
|
||||
attr.Value = slog.StringValue("<nil>")
|
||||
} else {
|
||||
attr.Value = slog.StringValue(v.String())
|
||||
}
|
||||
}
|
||||
return attr
|
||||
}
|
||||
|
||||
+64
-91
@@ -17,6 +17,7 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
@@ -25,54 +26,47 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
// errVmoduleSyntax is returned when a user vmodule pattern is invalid.
|
||||
var errVmoduleSyntax = errors.New("expect comma-separated list of filename=N")
|
||||
|
||||
// errTraceSyntax is returned when a user backtrace pattern is invalid.
|
||||
var errTraceSyntax = errors.New("expect file.go:234")
|
||||
|
||||
// GlogHandler is a log handler that mimics the filtering features of Google's
|
||||
// glog logger: setting global log levels; overriding with callsite pattern
|
||||
// matches; and requesting backtraces at certain positions.
|
||||
type GlogHandler struct {
|
||||
origin Handler // The origin handler this wraps
|
||||
origin slog.Handler // The origin handler this wraps
|
||||
|
||||
level atomic.Uint32 // Current log level, atomically accessible
|
||||
override atomic.Bool // Flag whether overrides are used, atomically accessible
|
||||
backtrace atomic.Bool // Flag whether backtrace location is set
|
||||
level atomic.Int32 // Current log level, atomically accessible
|
||||
override atomic.Bool // Flag whether overrides are used, atomically accessible
|
||||
|
||||
patterns []pattern // Current list of patterns to override with
|
||||
siteCache map[uintptr]Lvl // Cache of callsite pattern evaluations
|
||||
location string // file:line location where to do a stackdump at
|
||||
lock sync.RWMutex // Lock protecting the override pattern list
|
||||
patterns []pattern // Current list of patterns to override with
|
||||
siteCache map[uintptr]slog.Level // Cache of callsite pattern evaluations
|
||||
location string // file:line location where to do a stackdump at
|
||||
lock sync.RWMutex // Lock protecting the override pattern list
|
||||
}
|
||||
|
||||
// NewGlogHandler creates a new log handler with filtering functionality similar
|
||||
// to Google's glog logger. The returned handler implements Handler.
|
||||
func NewGlogHandler(h Handler) *GlogHandler {
|
||||
func NewGlogHandler(h slog.Handler) *GlogHandler {
|
||||
return &GlogHandler{
|
||||
origin: h,
|
||||
}
|
||||
}
|
||||
|
||||
// SetHandler updates the handler to write records to the specified sub-handler.
|
||||
func (h *GlogHandler) SetHandler(nh Handler) {
|
||||
h.origin = nh
|
||||
}
|
||||
|
||||
// pattern contains a filter for the Vmodule option, holding a verbosity level
|
||||
// and a file pattern to match.
|
||||
type pattern struct {
|
||||
pattern *regexp.Regexp
|
||||
level Lvl
|
||||
level slog.Level
|
||||
}
|
||||
|
||||
// Verbosity sets the glog verbosity ceiling. The verbosity of individual packages
|
||||
// and source files can be raised using Vmodule.
|
||||
func (h *GlogHandler) Verbosity(level Lvl) {
|
||||
h.level.Store(uint32(level))
|
||||
func (h *GlogHandler) Verbosity(level slog.Level) {
|
||||
h.level.Store(int32(level))
|
||||
}
|
||||
|
||||
// Vmodule sets the glog verbosity pattern.
|
||||
@@ -108,11 +102,13 @@ func (h *GlogHandler) Vmodule(ruleset string) error {
|
||||
return errVmoduleSyntax
|
||||
}
|
||||
// Parse the level and if correct, assemble the filter rule
|
||||
level, err := strconv.Atoi(parts[1])
|
||||
l, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return errVmoduleSyntax
|
||||
}
|
||||
if level <= 0 {
|
||||
level := FromLegacyLevel(l)
|
||||
|
||||
if level == LevelCrit {
|
||||
continue // Ignore. It's harmless but no point in paying the overhead.
|
||||
}
|
||||
// Compile the rule pattern into a regular expression
|
||||
@@ -130,107 +126,84 @@ func (h *GlogHandler) Vmodule(ruleset string) error {
|
||||
matcher = matcher + "$"
|
||||
|
||||
re, _ := regexp.Compile(matcher)
|
||||
filter = append(filter, pattern{re, Lvl(level)})
|
||||
filter = append(filter, pattern{re, level})
|
||||
}
|
||||
// Swap out the vmodule pattern for the new filter system
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
|
||||
h.patterns = filter
|
||||
h.siteCache = make(map[uintptr]Lvl)
|
||||
h.siteCache = make(map[uintptr]slog.Level)
|
||||
h.override.Store(len(filter) != 0)
|
||||
// Enable location storage (globally)
|
||||
if len(h.patterns) > 0 {
|
||||
stackEnabled.Store(true)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// BacktraceAt sets the glog backtrace location. When set to a file and line
|
||||
// number holding a logging statement, a stack trace will be written to the Info
|
||||
// log whenever execution hits that statement.
|
||||
//
|
||||
// Unlike with Vmodule, the ".go" must be present.
|
||||
func (h *GlogHandler) BacktraceAt(location string) error {
|
||||
// Ensure the backtrace location contains two non-empty elements
|
||||
parts := strings.Split(location, ":")
|
||||
if len(parts) != 2 {
|
||||
return errTraceSyntax
|
||||
}
|
||||
parts[0] = strings.TrimSpace(parts[0])
|
||||
parts[1] = strings.TrimSpace(parts[1])
|
||||
if len(parts[0]) == 0 || len(parts[1]) == 0 {
|
||||
return errTraceSyntax
|
||||
}
|
||||
// Ensure the .go prefix is present and the line is valid
|
||||
if !strings.HasSuffix(parts[0], ".go") {
|
||||
return errTraceSyntax
|
||||
}
|
||||
if _, err := strconv.Atoi(parts[1]); err != nil {
|
||||
return errTraceSyntax
|
||||
}
|
||||
// All seems valid
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
func (h *GlogHandler) Enabled(ctx context.Context, lvl slog.Level) bool {
|
||||
// fast-track skipping logging if override not enabled and the provided verbosity is above configured
|
||||
return h.override.Load() || slog.Level(h.level.Load()) <= lvl
|
||||
}
|
||||
|
||||
h.location = location
|
||||
h.backtrace.Store(len(location) > 0)
|
||||
// Enable location storage (globally)
|
||||
stackEnabled.Store(true)
|
||||
return nil
|
||||
func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
h.lock.RLock()
|
||||
siteCache := make(map[uintptr]slog.Level)
|
||||
for k, v := range h.siteCache {
|
||||
siteCache[k] = v
|
||||
}
|
||||
h.lock.RUnlock()
|
||||
|
||||
patterns := []pattern{}
|
||||
patterns = append(patterns, h.patterns...)
|
||||
|
||||
res := GlogHandler{
|
||||
origin: h.origin.WithAttrs(attrs),
|
||||
patterns: patterns,
|
||||
siteCache: siteCache,
|
||||
location: h.location,
|
||||
}
|
||||
|
||||
res.level.Store(h.level.Load())
|
||||
res.override.Store(h.override.Load())
|
||||
return &res
|
||||
}
|
||||
|
||||
func (h *GlogHandler) WithGroup(name string) slog.Handler {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
// Log implements Handler.Log, filtering a log record through the global, local
|
||||
// and backtrace filters, finally emitting it if either allow it through.
|
||||
func (h *GlogHandler) Log(r *Record) error {
|
||||
// If backtracing is requested, check whether this is the callsite
|
||||
if h.backtrace.Load() {
|
||||
// Everything below here is slow. Although we could cache the call sites the
|
||||
// same way as for vmodule, backtracing is so rare it's not worth the extra
|
||||
// complexity.
|
||||
h.lock.RLock()
|
||||
match := h.location == r.Call.String()
|
||||
h.lock.RUnlock()
|
||||
|
||||
if match {
|
||||
// Callsite matched, raise the log level to info and gather the stacks
|
||||
r.Lvl = LvlInfo
|
||||
|
||||
buf := make([]byte, 1024*1024)
|
||||
buf = buf[:runtime.Stack(buf, true)]
|
||||
r.Msg += "\n\n" + string(buf)
|
||||
}
|
||||
}
|
||||
func (h *GlogHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
// If the global log level allows, fast track logging
|
||||
if h.level.Load() >= uint32(r.Lvl) {
|
||||
return h.origin.Log(r)
|
||||
}
|
||||
// If no local overrides are present, fast track skipping
|
||||
if !h.override.Load() {
|
||||
return nil
|
||||
if slog.Level(h.level.Load()) <= r.Level {
|
||||
return h.origin.Handle(context.Background(), r)
|
||||
}
|
||||
|
||||
// Check callsite cache for previously calculated log levels
|
||||
h.lock.RLock()
|
||||
lvl, ok := h.siteCache[r.Call.Frame().PC]
|
||||
lvl, ok := h.siteCache[r.PC]
|
||||
h.lock.RUnlock()
|
||||
|
||||
// If we didn't cache the callsite yet, calculate it
|
||||
if !ok {
|
||||
h.lock.Lock()
|
||||
|
||||
fs := runtime.CallersFrames([]uintptr{r.PC})
|
||||
frame, _ := fs.Next()
|
||||
|
||||
for _, rule := range h.patterns {
|
||||
if rule.pattern.MatchString(fmt.Sprintf("%+s", r.Call)) {
|
||||
h.siteCache[r.Call.Frame().PC], lvl, ok = rule.level, rule.level, true
|
||||
break
|
||||
if rule.pattern.MatchString(fmt.Sprintf("%+s", frame.File)) {
|
||||
h.siteCache[r.PC], lvl, ok = rule.level, rule.level, true
|
||||
}
|
||||
}
|
||||
// If no rule matched, remember to drop log the next time
|
||||
if !ok {
|
||||
h.siteCache[r.Call.Frame().PC] = 0
|
||||
h.siteCache[r.PC] = 0
|
||||
}
|
||||
h.lock.Unlock()
|
||||
}
|
||||
if lvl >= r.Lvl {
|
||||
return h.origin.Log(r)
|
||||
if lvl <= r.Level {
|
||||
return h.origin.Handle(context.Background(), r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+151
-223
@@ -1,294 +1,222 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
"math"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/go-stack/stack"
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
const timeKey = "t"
|
||||
const lvlKey = "lvl"
|
||||
const msgKey = "msg"
|
||||
const ctxKey = "ctx"
|
||||
const errorKey = "LOG15_ERROR"
|
||||
const skipLevel = 2
|
||||
|
||||
type Lvl int
|
||||
const errorKey = "LOG_ERROR"
|
||||
|
||||
const (
|
||||
LvlCrit Lvl = iota
|
||||
LvlError
|
||||
LvlWarn
|
||||
LvlInfo
|
||||
LvlDebug
|
||||
LvlTrace
|
||||
legacyLevelCrit = iota
|
||||
legacyLevelError
|
||||
legacyLevelWarn
|
||||
legacyLevelInfo
|
||||
legacyLevelDebug
|
||||
legacyLevelTrace
|
||||
)
|
||||
|
||||
// AlignedString returns a 5-character string containing the name of a Lvl.
|
||||
func (l Lvl) AlignedString() string {
|
||||
const (
|
||||
levelMaxVerbosity slog.Level = math.MinInt
|
||||
LevelTrace slog.Level = -8
|
||||
LevelDebug = slog.LevelDebug
|
||||
LevelInfo = slog.LevelInfo
|
||||
LevelWarn = slog.LevelWarn
|
||||
LevelError = slog.LevelError
|
||||
LevelCrit slog.Level = 12
|
||||
|
||||
// for backward-compatibility
|
||||
LvlTrace = LevelTrace
|
||||
LvlInfo = LevelInfo
|
||||
LvlDebug = LevelDebug
|
||||
)
|
||||
|
||||
// convert from old Geth verbosity level constants
|
||||
// to levels defined by slog
|
||||
func FromLegacyLevel(lvl int) slog.Level {
|
||||
switch lvl {
|
||||
case legacyLevelCrit:
|
||||
return LevelCrit
|
||||
case legacyLevelError:
|
||||
return slog.LevelError
|
||||
case legacyLevelWarn:
|
||||
return slog.LevelWarn
|
||||
case legacyLevelInfo:
|
||||
return slog.LevelInfo
|
||||
case legacyLevelDebug:
|
||||
return slog.LevelDebug
|
||||
case legacyLevelTrace:
|
||||
return LevelTrace
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// TODO: should we allow use of custom levels or force them to match existing max/min if they fall outside the range as I am doing here?
|
||||
if lvl > legacyLevelTrace {
|
||||
return LevelTrace
|
||||
}
|
||||
return LevelCrit
|
||||
}
|
||||
|
||||
// LevelAlignedString returns a 5-character string containing the name of a Lvl.
|
||||
func LevelAlignedString(l slog.Level) string {
|
||||
switch l {
|
||||
case LvlTrace:
|
||||
case LevelTrace:
|
||||
return "TRACE"
|
||||
case LvlDebug:
|
||||
case slog.LevelDebug:
|
||||
return "DEBUG"
|
||||
case LvlInfo:
|
||||
case slog.LevelInfo:
|
||||
return "INFO "
|
||||
case LvlWarn:
|
||||
case slog.LevelWarn:
|
||||
return "WARN "
|
||||
case LvlError:
|
||||
case slog.LevelError:
|
||||
return "ERROR"
|
||||
case LvlCrit:
|
||||
case LevelCrit:
|
||||
return "CRIT "
|
||||
default:
|
||||
panic("bad level")
|
||||
return "unknown level"
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the name of a Lvl.
|
||||
func (l Lvl) String() string {
|
||||
// LevelString returns a 5-character string containing the name of a Lvl.
|
||||
func LevelString(l slog.Level) string {
|
||||
switch l {
|
||||
case LvlTrace:
|
||||
return "trce"
|
||||
case LvlDebug:
|
||||
return "dbug"
|
||||
case LvlInfo:
|
||||
case LevelTrace:
|
||||
return "trace"
|
||||
case slog.LevelDebug:
|
||||
return "debug"
|
||||
case slog.LevelInfo:
|
||||
return "info"
|
||||
case LvlWarn:
|
||||
case slog.LevelWarn:
|
||||
return "warn"
|
||||
case LvlError:
|
||||
case slog.LevelError:
|
||||
return "eror"
|
||||
case LvlCrit:
|
||||
case LevelCrit:
|
||||
return "crit"
|
||||
default:
|
||||
panic("bad level")
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// LvlFromString returns the appropriate Lvl from a string name.
|
||||
// Useful for parsing command line args and configuration files.
|
||||
func LvlFromString(lvlString string) (Lvl, error) {
|
||||
switch lvlString {
|
||||
case "trace", "trce":
|
||||
return LvlTrace, nil
|
||||
case "debug", "dbug":
|
||||
return LvlDebug, nil
|
||||
case "info":
|
||||
return LvlInfo, nil
|
||||
case "warn":
|
||||
return LvlWarn, nil
|
||||
case "error", "eror":
|
||||
return LvlError, nil
|
||||
case "crit":
|
||||
return LvlCrit, nil
|
||||
default:
|
||||
return LvlDebug, fmt.Errorf("unknown level: %v", lvlString)
|
||||
}
|
||||
}
|
||||
|
||||
// A Record is what a Logger asks its handler to write
|
||||
type Record struct {
|
||||
Time time.Time
|
||||
Lvl Lvl
|
||||
Msg string
|
||||
Ctx []interface{}
|
||||
Call stack.Call
|
||||
KeyNames RecordKeyNames
|
||||
}
|
||||
|
||||
// RecordKeyNames gets stored in a Record when the write function is executed.
|
||||
type RecordKeyNames struct {
|
||||
Time string
|
||||
Msg string
|
||||
Lvl string
|
||||
Ctx string
|
||||
}
|
||||
|
||||
// A Logger writes key/value pairs to a Handler
|
||||
type Logger interface {
|
||||
// New returns a new Logger that has this logger's context plus the given context
|
||||
// With returns a new Logger that has this logger's attributes plus the given attributes
|
||||
With(ctx ...interface{}) Logger
|
||||
|
||||
// With returns a new Logger that has this logger's attributes plus the given attributes. Identical to 'With'.
|
||||
New(ctx ...interface{}) Logger
|
||||
|
||||
// GetHandler gets the handler associated with the logger.
|
||||
GetHandler() Handler
|
||||
// Log logs a message at the specified level with context key/value pairs
|
||||
Log(level slog.Level, msg string, ctx ...interface{})
|
||||
|
||||
// SetHandler updates the logger to write records to the specified handler.
|
||||
SetHandler(h Handler)
|
||||
|
||||
// Log a message at the trace level with context key/value pairs
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// log.Trace("msg")
|
||||
// log.Trace("msg", "key1", val1)
|
||||
// log.Trace("msg", "key1", val1, "key2", val2)
|
||||
// Trace log a message at the trace level with context key/value pairs
|
||||
Trace(msg string, ctx ...interface{})
|
||||
|
||||
// Log a message at the debug level with context key/value pairs
|
||||
//
|
||||
// # Usage Examples
|
||||
//
|
||||
// log.Debug("msg")
|
||||
// log.Debug("msg", "key1", val1)
|
||||
// log.Debug("msg", "key1", val1, "key2", val2)
|
||||
// Debug logs a message at the debug level with context key/value pairs
|
||||
Debug(msg string, ctx ...interface{})
|
||||
|
||||
// Log a message at the info level with context key/value pairs
|
||||
//
|
||||
// # Usage Examples
|
||||
//
|
||||
// log.Info("msg")
|
||||
// log.Info("msg", "key1", val1)
|
||||
// log.Info("msg", "key1", val1, "key2", val2)
|
||||
// Info logs a message at the info level with context key/value pairs
|
||||
Info(msg string, ctx ...interface{})
|
||||
|
||||
// Log a message at the warn level with context key/value pairs
|
||||
//
|
||||
// # Usage Examples
|
||||
//
|
||||
// log.Warn("msg")
|
||||
// log.Warn("msg", "key1", val1)
|
||||
// log.Warn("msg", "key1", val1, "key2", val2)
|
||||
// Warn logs a message at the warn level with context key/value pairs
|
||||
Warn(msg string, ctx ...interface{})
|
||||
|
||||
// Log a message at the error level with context key/value pairs
|
||||
//
|
||||
// # Usage Examples
|
||||
//
|
||||
// log.Error("msg")
|
||||
// log.Error("msg", "key1", val1)
|
||||
// log.Error("msg", "key1", val1, "key2", val2)
|
||||
// Error logs a message at the error level with context key/value pairs
|
||||
Error(msg string, ctx ...interface{})
|
||||
|
||||
// Log a message at the crit level with context key/value pairs, and then exit.
|
||||
//
|
||||
// # Usage Examples
|
||||
//
|
||||
// log.Crit("msg")
|
||||
// log.Crit("msg", "key1", val1)
|
||||
// log.Crit("msg", "key1", val1, "key2", val2)
|
||||
// Crit logs a message at the crit level with context key/value pairs, and exits
|
||||
Crit(msg string, ctx ...interface{})
|
||||
|
||||
// Write logs a message at the specified level
|
||||
Write(level slog.Level, msg string, attrs ...any)
|
||||
}
|
||||
|
||||
type logger struct {
|
||||
ctx []interface{}
|
||||
h *swapHandler
|
||||
inner *slog.Logger
|
||||
}
|
||||
|
||||
func (l *logger) write(msg string, lvl Lvl, ctx []interface{}, skip int) {
|
||||
record := &Record{
|
||||
Time: time.Now(),
|
||||
Lvl: lvl,
|
||||
Msg: msg,
|
||||
Ctx: newContext(l.ctx, ctx),
|
||||
KeyNames: RecordKeyNames{
|
||||
Time: timeKey,
|
||||
Msg: msgKey,
|
||||
Lvl: lvlKey,
|
||||
Ctx: ctxKey,
|
||||
},
|
||||
// NewLogger returns a logger with the specified handler set
|
||||
func NewLogger(h slog.Handler) Logger {
|
||||
return &logger{
|
||||
slog.New(h),
|
||||
}
|
||||
if stackEnabled.Load() {
|
||||
record.Call = stack.Caller(skip)
|
||||
}
|
||||
|
||||
// write logs a message at the specified level:
|
||||
func (l *logger) Write(level slog.Level, msg string, attrs ...any) {
|
||||
if !l.inner.Enabled(context.Background(), level) {
|
||||
return
|
||||
}
|
||||
l.h.Log(record)
|
||||
}
|
||||
|
||||
func (l *logger) New(ctx ...interface{}) Logger {
|
||||
child := &logger{newContext(l.ctx, ctx), new(swapHandler)}
|
||||
child.SetHandler(l.h)
|
||||
return child
|
||||
}
|
||||
var pcs [1]uintptr
|
||||
runtime.Callers(3, pcs[:])
|
||||
|
||||
func newContext(prefix []interface{}, suffix []interface{}) []interface{} {
|
||||
normalizedSuffix := normalize(suffix)
|
||||
newCtx := make([]interface{}, len(prefix)+len(normalizedSuffix))
|
||||
n := copy(newCtx, prefix)
|
||||
copy(newCtx[n:], normalizedSuffix)
|
||||
return newCtx
|
||||
}
|
||||
if len(attrs)%2 != 0 {
|
||||
attrs = append(attrs, nil, errorKey, "Normalized odd number of arguments by adding nil")
|
||||
}
|
||||
|
||||
func (l *logger) Trace(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlTrace, ctx, skipLevel)
|
||||
}
|
||||
|
||||
func (l *logger) Debug(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlDebug, ctx, skipLevel)
|
||||
}
|
||||
|
||||
func (l *logger) Info(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlInfo, ctx, skipLevel)
|
||||
}
|
||||
|
||||
func (l *logger) Warn(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlWarn, ctx, skipLevel)
|
||||
}
|
||||
|
||||
func (l *logger) Error(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlError, ctx, skipLevel)
|
||||
}
|
||||
|
||||
func (l *logger) Crit(msg string, ctx ...interface{}) {
|
||||
l.write(msg, LvlCrit, ctx, skipLevel)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (l *logger) GetHandler() Handler {
|
||||
return l.h.Get()
|
||||
}
|
||||
|
||||
func (l *logger) SetHandler(h Handler) {
|
||||
l.h.Swap(h)
|
||||
}
|
||||
|
||||
func normalize(ctx []interface{}) []interface{} {
|
||||
// if the caller passed a Ctx object, then expand it
|
||||
if len(ctx) == 1 {
|
||||
if ctxMap, ok := ctx[0].(Ctx); ok {
|
||||
ctx = ctxMap.toArray()
|
||||
// evaluate lazy values
|
||||
var hadErr bool
|
||||
for i := 1; i < len(attrs); i += 2 {
|
||||
lz, ok := attrs[i].(Lazy)
|
||||
if ok {
|
||||
v, err := evaluateLazy(lz)
|
||||
if err != nil {
|
||||
hadErr = true
|
||||
attrs[i] = err
|
||||
} else {
|
||||
attrs[i] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ctx needs to be even because it's a series of key/value pairs
|
||||
// no one wants to check for errors on logging functions,
|
||||
// so instead of erroring on bad input, we'll just make sure
|
||||
// that things are the right length and users can fix bugs
|
||||
// when they see the output looks wrong
|
||||
if len(ctx)%2 != 0 {
|
||||
ctx = append(ctx, nil, errorKey, "Normalized odd number of arguments by adding nil")
|
||||
if hadErr {
|
||||
attrs = append(attrs, errorKey, "bad lazy")
|
||||
}
|
||||
|
||||
return ctx
|
||||
r := slog.NewRecord(time.Now(), level, msg, pcs[0])
|
||||
r.Add(attrs...)
|
||||
l.inner.Handler().Handle(context.Background(), r)
|
||||
}
|
||||
|
||||
// Lazy allows you to defer calculation of a logged value that is expensive
|
||||
// to compute until it is certain that it must be evaluated with the given filters.
|
||||
//
|
||||
// Lazy may also be used in conjunction with a Logger's New() function
|
||||
// to generate a child logger which always reports the current value of changing
|
||||
// state.
|
||||
//
|
||||
// You may wrap any function which takes no arguments to Lazy. It may return any
|
||||
// number of values of any type.
|
||||
type Lazy struct {
|
||||
Fn interface{}
|
||||
func (l *logger) Log(level slog.Level, msg string, attrs ...any) {
|
||||
l.Write(level, msg, attrs...)
|
||||
}
|
||||
|
||||
// Ctx is a map of key/value pairs to pass as context to a log function
|
||||
// Use this only if you really need greater safety around the arguments you pass
|
||||
// to the logging functions.
|
||||
type Ctx map[string]interface{}
|
||||
func (l *logger) With(ctx ...interface{}) Logger {
|
||||
return &logger{l.inner.With(ctx...)}
|
||||
}
|
||||
|
||||
func (c Ctx) toArray() []interface{} {
|
||||
arr := make([]interface{}, len(c)*2)
|
||||
func (l *logger) New(ctx ...interface{}) Logger {
|
||||
return l.With(ctx...)
|
||||
}
|
||||
|
||||
i := 0
|
||||
for k, v := range c {
|
||||
arr[i] = k
|
||||
arr[i+1] = v
|
||||
i += 2
|
||||
}
|
||||
func (l *logger) Trace(msg string, ctx ...interface{}) {
|
||||
l.Write(LevelTrace, msg, ctx...)
|
||||
}
|
||||
|
||||
return arr
|
||||
func (l *logger) Debug(msg string, ctx ...interface{}) {
|
||||
l.Write(slog.LevelDebug, msg, ctx...)
|
||||
}
|
||||
|
||||
func (l *logger) Info(msg string, ctx ...interface{}) {
|
||||
l.Write(slog.LevelInfo, msg, ctx...)
|
||||
}
|
||||
|
||||
func (l *logger) Warn(msg string, ctx ...any) {
|
||||
l.Write(slog.LevelWarn, msg, ctx...)
|
||||
}
|
||||
|
||||
func (l *logger) Error(msg string, ctx ...interface{}) {
|
||||
l.Write(slog.LevelError, msg, ctx...)
|
||||
}
|
||||
|
||||
func (l *logger) Crit(msg string, ctx ...interface{}) {
|
||||
l.Write(LevelCrit, msg, ctx...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
+24
-38
@@ -5,48 +5,18 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestLoggingWithTrace checks that if BackTraceAt is set, then the
|
||||
// gloghandler is capable of spitting out a stacktrace
|
||||
func TestLoggingWithTrace(t *testing.T) {
|
||||
defer stackEnabled.Store(stackEnabled.Load())
|
||||
out := new(bytes.Buffer)
|
||||
logger := New()
|
||||
{
|
||||
glog := NewGlogHandler(StreamHandler(out, TerminalFormat(false)))
|
||||
glog.Verbosity(LvlTrace)
|
||||
if err := glog.BacktraceAt("logger_test.go:24"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logger.SetHandler(glog)
|
||||
}
|
||||
logger.Trace("a message", "foo", "bar") // Will be bumped to INFO
|
||||
have := out.String()
|
||||
if !strings.HasPrefix(have, "INFO") {
|
||||
t.Fatalf("backtraceat should bump level to info: %s", have)
|
||||
}
|
||||
// The timestamp is locale-dependent, so we want to trim that off
|
||||
// "INFO [01-01|00:00:00.000] a messag ..." -> "a messag..."
|
||||
have = strings.Split(have, "]")[1]
|
||||
wantPrefix := " a message\n\ngoroutine"
|
||||
if !strings.HasPrefix(have, wantPrefix) {
|
||||
t.Errorf("\nhave: %q\nwant: %q\n", have, wantPrefix)
|
||||
}
|
||||
}
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
// TestLoggingWithVmodule checks that vmodule works.
|
||||
func TestLoggingWithVmodule(t *testing.T) {
|
||||
defer stackEnabled.Store(stackEnabled.Load())
|
||||
out := new(bytes.Buffer)
|
||||
logger := New()
|
||||
{
|
||||
glog := NewGlogHandler(StreamHandler(out, TerminalFormat(false)))
|
||||
glog.Verbosity(LvlCrit)
|
||||
logger.SetHandler(glog)
|
||||
logger.Warn("This should not be seen", "ignored", "true")
|
||||
glog.Vmodule("logger_test.go=5")
|
||||
}
|
||||
glog := NewGlogHandler(NewTerminalHandlerWithLevel(out, LevelTrace, false))
|
||||
glog.Verbosity(LevelCrit)
|
||||
logger := NewLogger(glog)
|
||||
logger.Warn("This should not be seen", "ignored", "true")
|
||||
glog.Vmodule("logger_test.go=5")
|
||||
logger.Trace("a message", "foo", "bar")
|
||||
have := out.String()
|
||||
// The timestamp is locale-dependent, so we want to trim that off
|
||||
@@ -58,8 +28,24 @@ func TestLoggingWithVmodule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalHandlerWithAttrs(t *testing.T) {
|
||||
out := new(bytes.Buffer)
|
||||
glog := NewGlogHandler(NewTerminalHandlerWithLevel(out, LevelTrace, false).WithAttrs([]slog.Attr{slog.String("baz", "bat")}))
|
||||
glog.Verbosity(LevelTrace)
|
||||
logger := NewLogger(glog)
|
||||
logger.Trace("a message", "foo", "bar")
|
||||
have := out.String()
|
||||
// The timestamp is locale-dependent, so we want to trim that off
|
||||
// "INFO [01-01|00:00:00.000] a messag ..." -> "a messag..."
|
||||
have = strings.Split(have, "]")[1]
|
||||
want := " a message baz=bat foo=bar\n"
|
||||
if have != want {
|
||||
t.Errorf("\nhave: %q\nwant: %q\n", have, want)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTraceLogging(b *testing.B) {
|
||||
Root().SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(os.Stderr, TerminalFormat(true))))
|
||||
SetDefault(NewLogger(NewTerminalHandler(os.Stderr, true)))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Trace("a message", "v", i)
|
||||
|
||||
+24
-25
@@ -2,31 +2,33 @@ package log
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
var (
|
||||
root = &logger{[]interface{}{}, new(swapHandler)}
|
||||
StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat())
|
||||
StderrHandler = StreamHandler(os.Stderr, LogfmtFormat())
|
||||
)
|
||||
var root atomic.Value
|
||||
|
||||
func init() {
|
||||
root.SetHandler(DiscardHandler())
|
||||
defaultLogger := &logger{slog.New(DiscardHandler())}
|
||||
SetDefault(defaultLogger)
|
||||
}
|
||||
|
||||
// New returns a new logger with the given context.
|
||||
// New is a convenient alias for Root().New
|
||||
func New(ctx ...interface{}) Logger {
|
||||
return root.New(ctx...)
|
||||
// SetDefault sets the default global logger
|
||||
func SetDefault(l Logger) {
|
||||
root.Store(l)
|
||||
if lg, ok := l.(*logger); ok {
|
||||
slog.SetDefault(lg.inner)
|
||||
}
|
||||
}
|
||||
|
||||
// Root returns the root logger
|
||||
func Root() Logger {
|
||||
return root
|
||||
return root.Load().(Logger)
|
||||
}
|
||||
|
||||
// The following functions bypass the exported logger methods (logger.Debug,
|
||||
// etc.) to keep the call depth the same for all paths to logger.write so
|
||||
// etc.) to keep the call depth the same for all paths to logger.Write so
|
||||
// runtime.Caller(2) always refers to the call site in client code.
|
||||
|
||||
// Trace is a convenient alias for Root().Trace
|
||||
@@ -39,7 +41,7 @@ func Root() Logger {
|
||||
// log.Trace("msg", "key1", val1)
|
||||
// log.Trace("msg", "key1", val1, "key2", val2)
|
||||
func Trace(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlTrace, ctx, skipLevel)
|
||||
Root().Write(LevelTrace, msg, ctx...)
|
||||
}
|
||||
|
||||
// Debug is a convenient alias for Root().Debug
|
||||
@@ -52,7 +54,7 @@ func Trace(msg string, ctx ...interface{}) {
|
||||
// log.Debug("msg", "key1", val1)
|
||||
// log.Debug("msg", "key1", val1, "key2", val2)
|
||||
func Debug(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlDebug, ctx, skipLevel)
|
||||
Root().Write(slog.LevelDebug, msg, ctx...)
|
||||
}
|
||||
|
||||
// Info is a convenient alias for Root().Info
|
||||
@@ -65,7 +67,7 @@ func Debug(msg string, ctx ...interface{}) {
|
||||
// log.Info("msg", "key1", val1)
|
||||
// log.Info("msg", "key1", val1, "key2", val2)
|
||||
func Info(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlInfo, ctx, skipLevel)
|
||||
Root().Write(slog.LevelInfo, msg, ctx...)
|
||||
}
|
||||
|
||||
// Warn is a convenient alias for Root().Warn
|
||||
@@ -78,7 +80,7 @@ func Info(msg string, ctx ...interface{}) {
|
||||
// log.Warn("msg", "key1", val1)
|
||||
// log.Warn("msg", "key1", val1, "key2", val2)
|
||||
func Warn(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlWarn, ctx, skipLevel)
|
||||
Root().Write(slog.LevelWarn, msg, ctx...)
|
||||
}
|
||||
|
||||
// Error is a convenient alias for Root().Error
|
||||
@@ -91,7 +93,7 @@ func Warn(msg string, ctx ...interface{}) {
|
||||
// log.Error("msg", "key1", val1)
|
||||
// log.Error("msg", "key1", val1, "key2", val2)
|
||||
func Error(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlError, ctx, skipLevel)
|
||||
Root().Write(slog.LevelError, msg, ctx...)
|
||||
}
|
||||
|
||||
// Crit is a convenient alias for Root().Crit
|
||||
@@ -104,15 +106,12 @@ func Error(msg string, ctx ...interface{}) {
|
||||
// log.Crit("msg", "key1", val1)
|
||||
// log.Crit("msg", "key1", val1, "key2", val2)
|
||||
func Crit(msg string, ctx ...interface{}) {
|
||||
root.write(msg, LvlCrit, ctx, skipLevel)
|
||||
Root().Write(LevelCrit, msg, ctx...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Output is a convenient alias for write, allowing for the modification of
|
||||
// the calldepth (number of stack frames to skip).
|
||||
// calldepth influences the reported line number of the log message.
|
||||
// A calldepth of zero reports the immediate caller of Output.
|
||||
// Non-zero calldepth skips as many stack frames.
|
||||
func Output(msg string, lvl Lvl, calldepth int, ctx ...interface{}) {
|
||||
root.write(msg, lvl, ctx, calldepth+skipLevel)
|
||||
// New returns a new logger with the given context.
|
||||
// New is a convenient alias for Root().New
|
||||
func New(ctx ...interface{}) Logger {
|
||||
return Root().With(ctx...)
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
//go:build !windows && !plan9
|
||||
// +build !windows,!plan9
|
||||
|
||||
package log
|
||||
|
||||
import (
|
||||
"log/syslog"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SyslogHandler opens a connection to the system syslog daemon by calling
|
||||
// syslog.New and writes all records to it.
|
||||
func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
|
||||
wr, err := syslog.New(priority, tag)
|
||||
return sharedSyslog(fmtr, wr, err)
|
||||
}
|
||||
|
||||
// SyslogNetHandler opens a connection to a log daemon over the network and writes
|
||||
// all log records to it.
|
||||
func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
|
||||
wr, err := syslog.Dial(net, addr, priority, tag)
|
||||
return sharedSyslog(fmtr, wr, err)
|
||||
}
|
||||
|
||||
func sharedSyslog(fmtr Format, sysWr *syslog.Writer, err error) (Handler, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := FuncHandler(func(r *Record) error {
|
||||
var syslogFn = sysWr.Info
|
||||
switch r.Lvl {
|
||||
case LvlCrit:
|
||||
syslogFn = sysWr.Crit
|
||||
case LvlError:
|
||||
syslogFn = sysWr.Err
|
||||
case LvlWarn:
|
||||
syslogFn = sysWr.Warning
|
||||
case LvlInfo:
|
||||
syslogFn = sysWr.Info
|
||||
case LvlDebug:
|
||||
syslogFn = sysWr.Debug
|
||||
case LvlTrace:
|
||||
syslogFn = func(m string) error { return nil } // There's no syslog level for trace
|
||||
}
|
||||
|
||||
s := strings.TrimSpace(string(fmtr.Format(r)))
|
||||
return syslogFn(s)
|
||||
})
|
||||
return LazyHandler(&closingHandler{sysWr, h}), nil
|
||||
}
|
||||
|
||||
func (m muster) SyslogHandler(priority syslog.Priority, tag string, fmtr Format) Handler {
|
||||
return must(SyslogHandler(priority, tag, fmtr))
|
||||
}
|
||||
|
||||
func (m muster) SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) Handler {
|
||||
return must(SyslogNetHandler(net, addr, priority, tag, fmtr))
|
||||
}
|
||||
Reference in New Issue
Block a user