Bo-Yi Wu
6 years ago
56 changed files with 5423 additions and 2174 deletions
@ -0,0 +1 @@ |
|||||
|
zerolog.io |
@ -0,0 +1,566 @@ |
|||||
|
# Zero Allocation JSON Logger |
||||
|
|
||||
|
[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/zerolog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zerolog/master/LICENSE) [![Build Status](https://travis-ci.org/rs/zerolog.svg?branch=master)](https://travis-ci.org/rs/zerolog) [![Coverage](http://gocover.io/_badge/github.com/rs/zerolog)](http://gocover.io/github.com/rs/zerolog) |
||||
|
|
||||
|
The zerolog package provides a fast and simple logger dedicated to JSON output. |
||||
|
|
||||
|
Zerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection. |
||||
|
|
||||
|
Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance. |
||||
|
|
||||
|
To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) `zerolog.ConsoleWriter`. |
||||
|
|
||||
|
![Pretty Logging Image](pretty.png) |
||||
|
|
||||
|
## Who uses zerolog |
||||
|
|
||||
|
Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list. |
||||
|
|
||||
|
## Features |
||||
|
|
||||
|
* Blazing fast |
||||
|
* Low to zero allocation |
||||
|
* Level logging |
||||
|
* Sampling |
||||
|
* Hooks |
||||
|
* Contextual fields |
||||
|
* `context.Context` integration |
||||
|
* `net/http` helpers |
||||
|
* JSON and CBOR encoding formats |
||||
|
* Pretty logging for development |
||||
|
|
||||
|
## Installation |
||||
|
|
||||
|
```go |
||||
|
go get -u github.com/rs/zerolog/log |
||||
|
``` |
||||
|
|
||||
|
## Getting Started |
||||
|
|
||||
|
### Simple Logging Example |
||||
|
|
||||
|
For simple logging, import the global logger package **github.com/rs/zerolog/log** |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
// UNIX Time is faster and smaller than most timestamps |
||||
|
// If you set zerolog.TimeFieldFormat to an empty string, |
||||
|
// logs will write with UNIX time |
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
|
||||
|
log.Print("hello world") |
||||
|
} |
||||
|
|
||||
|
// Output: {"time":1516134303,"level":"debug","message":"hello world"} |
||||
|
``` |
||||
|
> Note: By default log writes to `os.Stderr` |
||||
|
> Note: The default log level for `log.Print` is *debug* |
||||
|
|
||||
|
### Contextual Logging |
||||
|
|
||||
|
**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below: |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
|
||||
|
log.Debug(). |
||||
|
Str("Scale", "833 cents"). |
||||
|
Float64("Interval", 833.09). |
||||
|
Msg("Fibonacci is everywhere") |
||||
|
} |
||||
|
|
||||
|
// Output: {"time":1524104936,"level":"debug","Scale":"833 cents","Interval":833.09,"message":"Fibonacci is everywhere"} |
||||
|
``` |
||||
|
|
||||
|
> You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types) |
||||
|
|
||||
|
### Leveled Logging |
||||
|
|
||||
|
#### Simple Leveled Logging Example |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
|
||||
|
log.Info().Msg("hello world") |
||||
|
} |
||||
|
|
||||
|
// Output: {"time":1516134303,"level":"info","message":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this. |
||||
|
|
||||
|
**zerolog** allows for logging at the following levels (from highest to lowest): |
||||
|
|
||||
|
* panic (`zerolog.PanicLevel`, 5) |
||||
|
* fatal (`zerolog.FatalLevel`, 4) |
||||
|
* error (`zerolog.ErrorLevel`, 3) |
||||
|
* warn (`zerolog.WarnLevel`, 2) |
||||
|
* info (`zerolog.InfoLevel`, 1) |
||||
|
* debug (`zerolog.DebugLevel`, 0) |
||||
|
|
||||
|
You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant. |
||||
|
|
||||
|
#### Setting Global Log Level |
||||
|
|
||||
|
This example uses command-line flags to demonstrate various outputs depending on the chosen log level. |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"flag" |
||||
|
|
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
debug := flag.Bool("debug", false, "sets log level to debug") |
||||
|
|
||||
|
flag.Parse() |
||||
|
|
||||
|
// Default level for this example is info, unless debug flag is present |
||||
|
zerolog.SetGlobalLevel(zerolog.InfoLevel) |
||||
|
if *debug { |
||||
|
zerolog.SetGlobalLevel(zerolog.DebugLevel) |
||||
|
} |
||||
|
|
||||
|
log.Debug().Msg("This message appears only when log level set to Debug") |
||||
|
log.Info().Msg("This message appears when log level set to Debug or Info") |
||||
|
|
||||
|
if e := log.Debug(); e.Enabled() { |
||||
|
// Compute log output only if enabled. |
||||
|
value := "bar" |
||||
|
e.Str("foo", value).Msg("some debug message") |
||||
|
} |
||||
|
} |
||||
|
``` |
||||
|
|
||||
|
Info Output (no flag) |
||||
|
|
||||
|
```bash |
||||
|
$ ./logLevelExample |
||||
|
{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"} |
||||
|
``` |
||||
|
|
||||
|
Debug Output (debug flag set) |
||||
|
|
||||
|
```bash |
||||
|
$ ./logLevelExample -debug |
||||
|
{"time":1516387573,"level":"debug","message":"This message appears only when log level set to Debug"} |
||||
|
{"time":1516387573,"level":"info","message":"This message appears when log level set to Debug or Info"} |
||||
|
{"time":1516387573,"level":"debug","foo":"bar","message":"some debug message"} |
||||
|
``` |
||||
|
|
||||
|
#### Logging without Level or Message |
||||
|
|
||||
|
You may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below. |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
|
||||
|
log.Log(). |
||||
|
Str("foo", "bar"). |
||||
|
Msg("") |
||||
|
} |
||||
|
|
||||
|
// Output: {"time":1494567715,"foo":"bar"} |
||||
|
``` |
||||
|
|
||||
|
#### Logging Fatal Messages |
||||
|
|
||||
|
```go |
||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"errors" |
||||
|
|
||||
|
"github.com/rs/zerolog" |
||||
|
"github.com/rs/zerolog/log" |
||||
|
) |
||||
|
|
||||
|
func main() { |
||||
|
err := errors.New("A repo man spends his life getting into tense situations") |
||||
|
service := "myservice" |
||||
|
|
||||
|
zerolog.TimeFieldFormat = "" |
||||
|
|
||||
|
log.Fatal(). |
||||
|
Err(err). |
||||
|
Str("service", service). |
||||
|
Msgf("Cannot start %s", service) |
||||
|
} |
||||
|
|
||||
|
// Output: {"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"} |
||||
|
// exit status 1 |
||||
|
``` |
||||
|
|
||||
|
> NOTE: Using `Msgf` generates one allocation even when the logger is disabled. |
||||
|
|
||||
|
### Create logger instance to manage different outputs |
||||
|
|
||||
|
```go |
||||
|
logger := zerolog.New(os.Stderr).With().Timestamp().Logger() |
||||
|
|
||||
|
logger.Info().Str("foo", "bar").Msg("hello world") |
||||
|
|
||||
|
// Output: {"level":"info","time":1494567715,"message":"hello world","foo":"bar"} |
||||
|
``` |
||||
|
|
||||
|
### Sub-loggers let you chain loggers with additional context |
||||
|
|
||||
|
```go |
||||
|
sublogger := log.With(). |
||||
|
Str("component", "foo"). |
||||
|
Logger() |
||||
|
sublogger.Info().Msg("hello world") |
||||
|
|
||||
|
// Output: {"level":"info","time":1494567715,"message":"hello world","component":"foo"} |
||||
|
``` |
||||
|
|
||||
|
### Pretty logging |
||||
|
|
||||
|
```go |
||||
|
if isConsole { |
||||
|
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) |
||||
|
} |
||||
|
|
||||
|
log.Info().Str("foo", "bar").Msg("Hello world") |
||||
|
|
||||
|
// Output: 1494567715 |INFO| Hello world foo=bar |
||||
|
``` |
||||
|
|
||||
|
### Sub dictionary |
||||
|
|
||||
|
```go |
||||
|
log.Info(). |
||||
|
Str("foo", "bar"). |
||||
|
Dict("dict", zerolog.Dict(). |
||||
|
Str("bar", "baz"). |
||||
|
Int("n", 1), |
||||
|
).Msg("hello world") |
||||
|
|
||||
|
// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
### Customize automatic field names |
||||
|
|
||||
|
```go |
||||
|
zerolog.TimestampFieldName = "t" |
||||
|
zerolog.LevelFieldName = "l" |
||||
|
zerolog.MessageFieldName = "m" |
||||
|
|
||||
|
log.Info().Msg("hello world") |
||||
|
|
||||
|
// Output: {"l":"info","t":1494567715,"m":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
### Add contextual fields to the global logger |
||||
|
|
||||
|
```go |
||||
|
log.Logger = log.With().Str("foo", "bar").Logger() |
||||
|
``` |
||||
|
|
||||
|
### Add file and line number to log |
||||
|
|
||||
|
```go |
||||
|
log.Logger = log.With().Caller().Logger() |
||||
|
log.Info().Msg("hello world") |
||||
|
|
||||
|
// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"} |
||||
|
``` |
||||
|
|
||||
|
|
||||
|
### Thread-safe, lock-free, non-blocking writer |
||||
|
|
||||
|
If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follow: |
||||
|
|
||||
|
```go |
||||
|
wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) { |
||||
|
fmt.Printf("Logger Dropped %d messages", missed) |
||||
|
}) |
||||
|
log := zerolog.New(w) |
||||
|
log.Print("test") |
||||
|
``` |
||||
|
|
||||
|
You will need to install `code.cloudfoundry.org/go-diodes` to use this feature. |
||||
|
|
||||
|
### Log Sampling |
||||
|
|
||||
|
```go |
||||
|
sampled := log.Sample(&zerolog.BasicSampler{N: 10}) |
||||
|
sampled.Info().Msg("will be logged every 10 messages") |
||||
|
|
||||
|
// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"} |
||||
|
``` |
||||
|
|
||||
|
More advanced sampling: |
||||
|
|
||||
|
```go |
||||
|
// Will let 5 debug messages per period of 1 second. |
||||
|
// Over 5 debug message, 1 every 100 debug messages are logged. |
||||
|
// Other levels are not sampled. |
||||
|
sampled := log.Sample(zerolog.LevelSampler{ |
||||
|
DebugSampler: &zerolog.BurstSampler{ |
||||
|
Burst: 5, |
||||
|
Period: 1*time.Second, |
||||
|
NextSampler: &zerolog.BasicSampler{N: 100}, |
||||
|
}, |
||||
|
}) |
||||
|
sampled.Debug().Msg("hello world") |
||||
|
|
||||
|
// Output: {"time":1494567715,"level":"debug","message":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
### Hooks |
||||
|
|
||||
|
```go |
||||
|
type SeverityHook struct{} |
||||
|
|
||||
|
func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { |
||||
|
if level != zerolog.NoLevel { |
||||
|
e.Str("severity", level.String()) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
hooked := log.Hook(SeverityHook{}) |
||||
|
hooked.Warn().Msg("") |
||||
|
|
||||
|
// Output: {"level":"warn","severity":"warn"} |
||||
|
``` |
||||
|
|
||||
|
### Pass a sub-logger by context |
||||
|
|
||||
|
```go |
||||
|
ctx := log.With().Str("component", "module").Logger().WithContext(ctx) |
||||
|
|
||||
|
log.Ctx(ctx).Info().Msg("hello world") |
||||
|
|
||||
|
// Output: {"component":"module","level":"info","message":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
### Set as standard logger output |
||||
|
|
||||
|
```go |
||||
|
log := zerolog.New(os.Stdout).With(). |
||||
|
Str("foo", "bar"). |
||||
|
Logger() |
||||
|
|
||||
|
stdlog.SetFlags(0) |
||||
|
stdlog.SetOutput(log) |
||||
|
|
||||
|
stdlog.Print("hello world") |
||||
|
|
||||
|
// Output: {"foo":"bar","message":"hello world"} |
||||
|
``` |
||||
|
|
||||
|
### Integration with `net/http` |
||||
|
|
||||
|
The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`. |
||||
|
|
||||
|
In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability. |
||||
|
|
||||
|
```go |
||||
|
log := zerolog.New(os.Stdout).With(). |
||||
|
Timestamp(). |
||||
|
Str("role", "my-service"). |
||||
|
Str("host", host). |
||||
|
Logger() |
||||
|
|
||||
|
c := alice.New() |
||||
|
|
||||
|
// Install the logger handler with default output on the console |
||||
|
c = c.Append(hlog.NewHandler(log)) |
||||
|
|
||||
|
// Install some provided extra handler to set some request's context fields. |
||||
|
// Thanks to those handler, all our logs will come with some pre-populated fields. |
||||
|
c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { |
||||
|
hlog.FromRequest(r).Info(). |
||||
|
Str("method", r.Method). |
||||
|
Str("url", r.URL.String()). |
||||
|
Int("status", status). |
||||
|
Int("size", size). |
||||
|
Dur("duration", duration). |
||||
|
Msg("") |
||||
|
})) |
||||
|
c = c.Append(hlog.RemoteAddrHandler("ip")) |
||||
|
c = c.Append(hlog.UserAgentHandler("user_agent")) |
||||
|
c = c.Append(hlog.RefererHandler("referer")) |
||||
|
c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id")) |
||||
|
|
||||
|
// Here is your final handler |
||||
|
h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||
|
// Get the logger from the request's context. You can safely assume it |
||||
|
// will be always there: if the handler is removed, hlog.FromRequest |
||||
|
// will return a no-op logger. |
||||
|
hlog.FromRequest(r).Info(). |
||||
|
Str("user", "current user"). |
||||
|
Str("status", "ok"). |
||||
|
Msg("Something happened") |
||||
|
|
||||
|
// Output: {"level":"info","time":"2001-02-03T04:05:06Z","role":"my-service","host":"local-hostname","req_id":"b4g0l5t6tfid6dtrapu0","user":"current user","status":"ok","message":"Something happened"} |
||||
|
})) |
||||
|
http.Handle("/", h) |
||||
|
|
||||
|
if err := http.ListenAndServe(":8080", nil); err != nil { |
||||
|
log.Fatal().Err(err).Msg("Startup failed") |
||||
|
} |
||||
|
``` |
||||
|
|
||||
|
## Global Settings |
||||
|
|
||||
|
Some settings can be changed and will by applied to all loggers: |
||||
|
|
||||
|
* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods). |
||||
|
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Set this to `zerolog.Disabled` to disable logging altogether (quiet mode). |
||||
|
* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events. |
||||
|
* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name. |
||||
|
* `zerolog.LevelFieldName`: Can be set to customize level field name. |
||||
|
* `zerolog.MessageFieldName`: Can be set to customize message field name. |
||||
|
* `zerolog.ErrorFieldName`: Can be set to customize `Err` field name. |
||||
|
* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with an empty string, times are formated as UNIX timestamp. |
||||
|
// DurationFieldUnit defines the unit for time.Duration type fields added |
||||
|
// using the Dur method. |
||||
|
* `DurationFieldUnit`: Sets the unit of the fields added by `Dur` (default: `time.Millisecond`). |
||||
|
* `DurationFieldInteger`: If set to true, `Dur` fields are formatted as integers instead of floats. |
||||
|
|
||||
|
## Field Types |
||||
|
|
||||
|
### Standard Types |
||||
|
|
||||
|
* `Str` |
||||
|
* `Bool` |
||||
|
* `Int`, `Int8`, `Int16`, `Int32`, `Int64` |
||||
|
* `Uint`, `Uint8`, `Uint16`, `Uint32`, `Uint64` |
||||
|
* `Float32`, `Float64` |
||||
|
|
||||
|
### Advanced Fields |
||||
|
|
||||
|
* `Err`: Takes an `error` and render it as a string using the `zerolog.ErrorFieldName` field name. |
||||
|
* `Timestamp`: Insert a timestamp field with `zerolog.TimestampFieldName` field name and formatted using `zerolog.TimeFieldFormat`. |
||||
|
* `Time`: Adds a field with the time formated with the `zerolog.TimeFieldFormat`. |
||||
|
* `Dur`: Adds a field with a `time.Duration`. |
||||
|
* `Dict`: Adds a sub-key/value as a field of the event. |
||||
|
* `Interface`: Uses reflection to marshal the type. |
||||
|
|
||||
|
## Binary Encoding |
||||
|
|
||||
|
In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows: |
||||
|
|
||||
|
```bash |
||||
|
go build -tags binary_log . |
||||
|
``` |
||||
|
|
||||
|
To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work |
||||
|
with zerolog library is [CSD](https://github.com/toravir/csd/). |
||||
|
|
||||
|
## Related Projects |
||||
|
|
||||
|
* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog` |
||||
|
|
||||
|
## Benchmarks |
||||
|
|
||||
|
See [logbench](http://hackemist.com/logbench/) for more comprehensive and up-to-date benchmarks. |
||||
|
|
||||
|
All operations are allocation free (those numbers *include* JSON encoding): |
||||
|
|
||||
|
```text |
||||
|
BenchmarkLogEmpty-8 100000000 19.1 ns/op 0 B/op 0 allocs/op |
||||
|
BenchmarkDisabled-8 500000000 4.07 ns/op 0 B/op 0 allocs/op |
||||
|
BenchmarkInfo-8 30000000 42.5 ns/op 0 B/op 0 allocs/op |
||||
|
BenchmarkContextFields-8 30000000 44.9 ns/op 0 B/op 0 allocs/op |
||||
|
BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op |
||||
|
``` |
||||
|
|
||||
|
There are a few Go logging benchmarks and comparisons that include zerolog. |
||||
|
|
||||
|
* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) |
||||
|
* [uber-common/zap](https://github.com/uber-go/zap#performance) |
||||
|
|
||||
|
Using Uber's zap comparison benchmark: |
||||
|
|
||||
|
Log a message and 10 fields: |
||||
|
|
||||
|
| Library | Time | Bytes Allocated | Objects Allocated | |
||||
|
| :--- | :---: | :---: | :---: | |
||||
|
| zerolog | 767 ns/op | 552 B/op | 6 allocs/op | |
||||
|
| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op | |
||||
|
| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op | |
||||
|
| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op | |
||||
|
| lion | 5392 ns/op | 5807 B/op | 63 allocs/op | |
||||
|
| logrus | 5661 ns/op | 6092 B/op | 78 allocs/op | |
||||
|
| apex/log | 15332 ns/op | 3832 B/op | 65 allocs/op | |
||||
|
| log15 | 20657 ns/op | 5632 B/op | 93 allocs/op | |
||||
|
|
||||
|
Log a message with a logger that already has 10 fields of context: |
||||
|
|
||||
|
| Library | Time | Bytes Allocated | Objects Allocated | |
||||
|
| :--- | :---: | :---: | :---: | |
||||
|
| zerolog | 52 ns/op | 0 B/op | 0 allocs/op | |
||||
|
| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op | |
||||
|
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | |
||||
|
| lion | 2702 ns/op | 4074 B/op | 38 allocs/op | |
||||
|
| go-kit | 3378 ns/op | 3046 B/op | 52 allocs/op | |
||||
|
| logrus | 4309 ns/op | 4564 B/op | 63 allocs/op | |
||||
|
| apex/log | 13456 ns/op | 2898 B/op | 51 allocs/op | |
||||
|
| log15 | 14179 ns/op | 2642 B/op | 44 allocs/op | |
||||
|
|
||||
|
Log a static string, without any context or `printf`-style templating: |
||||
|
|
||||
|
| Library | Time | Bytes Allocated | Objects Allocated | |
||||
|
| :--- | :---: | :---: | :---: | |
||||
|
| zerolog | 50 ns/op | 0 B/op | 0 allocs/op | |
||||
|
| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op | |
||||
|
| standard library | 453 ns/op | 80 B/op | 2 allocs/op | |
||||
|
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | |
||||
|
| go-kit | 508 ns/op | 656 B/op | 13 allocs/op | |
||||
|
| lion | 771 ns/op | 1224 B/op | 10 allocs/op | |
||||
|
| logrus | 1244 ns/op | 1505 B/op | 27 allocs/op | |
||||
|
| apex/log | 2751 ns/op | 584 B/op | 11 allocs/op | |
||||
|
| log15 | 5181 ns/op | 1592 B/op | 26 allocs/op | |
||||
|
|
||||
|
## Caveats |
||||
|
|
||||
|
Note that zerolog does de-duplication fields. Using the same key multiple times creates multiple keys in final JSON: |
||||
|
|
||||
|
```go |
||||
|
logger := zerolog.New(os.Stderr).With().Timestamp().Logger() |
||||
|
logger.Info(). |
||||
|
Timestamp(). |
||||
|
Msg("dup") |
||||
|
// Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} |
||||
|
``` |
||||
|
|
||||
|
However, it’s not a big deal as JSON accepts dup keys; the last one prevails. |
@ -0,0 +1 @@ |
|||||
|
remote_theme: rs/gh-readme |
@ -0,0 +1,224 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"net" |
||||
|
"sync" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
var arrayPool = &sync.Pool{ |
||||
|
New: func() interface{} { |
||||
|
return &Array{ |
||||
|
buf: make([]byte, 0, 500), |
||||
|
} |
||||
|
}, |
||||
|
} |
||||
|
|
||||
|
// Array is used to prepopulate an array of items
|
||||
|
// which can be re-used to add to log messages.
|
||||
|
type Array struct { |
||||
|
buf []byte |
||||
|
} |
||||
|
|
||||
|
func putArray(a *Array) { |
||||
|
// Proper usage of a sync.Pool requires each entry to have approximately
|
||||
|
// the same memory cost. To obtain this property when the stored type
|
||||
|
// contains a variably-sized buffer, we add a hard limit on the maximum buffer
|
||||
|
// to place back in the pool.
|
||||
|
//
|
||||
|
// See https://golang.org/issue/23199
|
||||
|
const maxSize = 1 << 16 // 64KiB
|
||||
|
if cap(a.buf) > maxSize { |
||||
|
return |
||||
|
} |
||||
|
arrayPool.Put(a) |
||||
|
} |
||||
|
|
||||
|
// Arr creates an array to be added to an Event or Context.
|
||||
|
func Arr() *Array { |
||||
|
a := arrayPool.Get().(*Array) |
||||
|
a.buf = a.buf[:0] |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// MarshalZerologArray method here is no-op - since data is
|
||||
|
// already in the needed format.
|
||||
|
func (*Array) MarshalZerologArray(*Array) { |
||||
|
} |
||||
|
|
||||
|
func (a *Array) write(dst []byte) []byte { |
||||
|
dst = enc.AppendArrayStart(dst) |
||||
|
if len(a.buf) > 0 { |
||||
|
dst = append(append(dst, a.buf...)) |
||||
|
} |
||||
|
dst = enc.AppendArrayEnd(dst) |
||||
|
putArray(a) |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// Object marshals an object that implement the LogObjectMarshaler
|
||||
|
// interface and append append it to the array.
|
||||
|
func (a *Array) Object(obj LogObjectMarshaler) *Array { |
||||
|
e := Dict() |
||||
|
obj.MarshalZerologObject(e) |
||||
|
e.buf = enc.AppendEndMarker(e.buf) |
||||
|
a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) |
||||
|
putEvent(e) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Str append append the val as a string to the array.
|
||||
|
func (a *Array) Str(val string) *Array { |
||||
|
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Bytes append append the val as a string to the array.
|
||||
|
func (a *Array) Bytes(val []byte) *Array { |
||||
|
a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Hex append append the val as a hex string to the array.
|
||||
|
func (a *Array) Hex(val []byte) *Array { |
||||
|
a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Err serializes and appends the err to the array.
|
||||
|
func (a *Array) Err(err error) *Array { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case LogObjectMarshaler: |
||||
|
e := newEvent(nil, 0) |
||||
|
e.buf = e.buf[:0] |
||||
|
e.appendObject(m) |
||||
|
a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) |
||||
|
putEvent(e) |
||||
|
case error: |
||||
|
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m.Error()) |
||||
|
case string: |
||||
|
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m) |
||||
|
default: |
||||
|
a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), m) |
||||
|
} |
||||
|
|
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Bool append append the val as a bool to the array.
|
||||
|
func (a *Array) Bool(b bool) *Array { |
||||
|
a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Int append append i as a int to the array.
|
||||
|
func (a *Array) Int(i int) *Array { |
||||
|
a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Int8 append append i as a int8 to the array.
|
||||
|
func (a *Array) Int8(i int8) *Array { |
||||
|
a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Int16 append append i as a int16 to the array.
|
||||
|
func (a *Array) Int16(i int16) *Array { |
||||
|
a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Int32 append append i as a int32 to the array.
|
||||
|
func (a *Array) Int32(i int32) *Array { |
||||
|
a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Int64 append append i as a int64 to the array.
|
||||
|
func (a *Array) Int64(i int64) *Array { |
||||
|
a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Uint append append i as a uint to the array.
|
||||
|
func (a *Array) Uint(i uint) *Array { |
||||
|
a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Uint8 append append i as a uint8 to the array.
|
||||
|
func (a *Array) Uint8(i uint8) *Array { |
||||
|
a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Uint16 append append i as a uint16 to the array.
|
||||
|
func (a *Array) Uint16(i uint16) *Array { |
||||
|
a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Uint32 append append i as a uint32 to the array.
|
||||
|
func (a *Array) Uint32(i uint32) *Array { |
||||
|
a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Uint64 append append i as a uint64 to the array.
|
||||
|
func (a *Array) Uint64(i uint64) *Array { |
||||
|
a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Float32 append append f as a float32 to the array.
|
||||
|
func (a *Array) Float32(f float32) *Array { |
||||
|
a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Float64 append append f as a float64 to the array.
|
||||
|
func (a *Array) Float64(f float64) *Array { |
||||
|
a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Time append append t formated as string using zerolog.TimeFieldFormat.
|
||||
|
func (a *Array) Time(t time.Time) *Array { |
||||
|
a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Dur append append d to the array.
|
||||
|
func (a *Array) Dur(d time.Duration) *Array { |
||||
|
a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// Interface append append i marshaled using reflection.
|
||||
|
func (a *Array) Interface(i interface{}) *Array { |
||||
|
if obj, ok := i.(LogObjectMarshaler); ok { |
||||
|
return a.Object(obj) |
||||
|
} |
||||
|
a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), i) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// IPAddr adds IPv4 or IPv6 address to the array
|
||||
|
func (a *Array) IPAddr(ip net.IP) *Array { |
||||
|
a.buf = enc.AppendIPAddr(enc.AppendArrayDelim(a.buf), ip) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array
|
||||
|
func (a *Array) IPPrefix(pfx net.IPNet) *Array { |
||||
|
a.buf = enc.AppendIPPrefix(enc.AppendArrayDelim(a.buf), pfx) |
||||
|
return a |
||||
|
} |
||||
|
|
||||
|
// MACAddr adds a MAC (Ethernet) address to the array
|
||||
|
func (a *Array) MACAddr(ha net.HardwareAddr) *Array { |
||||
|
a.buf = enc.AppendMACAddr(enc.AppendArrayDelim(a.buf), ha) |
||||
|
return a |
||||
|
} |
@ -0,0 +1,150 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"bytes" |
||||
|
"encoding/json" |
||||
|
"fmt" |
||||
|
"io" |
||||
|
"sort" |
||||
|
"strconv" |
||||
|
"strings" |
||||
|
"sync" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
const ( |
||||
|
cReset = 0 |
||||
|
cBold = 1 |
||||
|
cRed = 31 |
||||
|
cGreen = 32 |
||||
|
cYellow = 33 |
||||
|
cBlue = 34 |
||||
|
cMagenta = 35 |
||||
|
cCyan = 36 |
||||
|
cGray = 37 |
||||
|
cDarkGray = 90 |
||||
|
) |
||||
|
|
||||
|
var consoleBufPool = sync.Pool{ |
||||
|
New: func() interface{} { |
||||
|
return bytes.NewBuffer(make([]byte, 0, 100)) |
||||
|
}, |
||||
|
} |
||||
|
|
||||
|
// LevelWidth defines the desired character width of the log level column.
|
||||
|
// Default 0 does not trim or pad (variable width based level text, e.g. "INFO" or "ERROR")
|
||||
|
var LevelWidth = 0 |
||||
|
|
||||
|
// ConsoleWriter reads a JSON object per write operation and output an
|
||||
|
// optionally colored human readable version on the Out writer.
|
||||
|
type ConsoleWriter struct { |
||||
|
Out io.Writer |
||||
|
NoColor bool |
||||
|
} |
||||
|
|
||||
|
func (w ConsoleWriter) Write(p []byte) (n int, err error) { |
||||
|
var event map[string]interface{} |
||||
|
p = decodeIfBinaryToBytes(p) |
||||
|
d := json.NewDecoder(bytes.NewReader(p)) |
||||
|
d.UseNumber() |
||||
|
err = d.Decode(&event) |
||||
|
if err != nil { |
||||
|
return |
||||
|
} |
||||
|
buf := consoleBufPool.Get().(*bytes.Buffer) |
||||
|
defer consoleBufPool.Put(buf) |
||||
|
lvlColor := cReset |
||||
|
level := "????" |
||||
|
if l, ok := event[LevelFieldName].(string); ok { |
||||
|
if !w.NoColor { |
||||
|
lvlColor = levelColor(l) |
||||
|
} |
||||
|
level = strings.ToUpper(l) |
||||
|
if LevelWidth > 0 { |
||||
|
if padding := LevelWidth - len(level); padding > 0 { |
||||
|
level += strings.Repeat(" ", padding) |
||||
|
} else { |
||||
|
level = level[0:LevelWidth] |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
fmt.Fprintf(buf, "%s |%s| %s", |
||||
|
colorize(formatTime(event[TimestampFieldName]), cDarkGray, !w.NoColor), |
||||
|
colorize(level, lvlColor, !w.NoColor), |
||||
|
colorize(event[MessageFieldName], cReset, !w.NoColor)) |
||||
|
fields := make([]string, 0, len(event)) |
||||
|
for field := range event { |
||||
|
switch field { |
||||
|
case LevelFieldName, TimestampFieldName, MessageFieldName: |
||||
|
continue |
||||
|
} |
||||
|
fields = append(fields, field) |
||||
|
} |
||||
|
sort.Strings(fields) |
||||
|
for _, field := range fields { |
||||
|
fmt.Fprintf(buf, " %s=", colorize(field, cCyan, !w.NoColor)) |
||||
|
switch value := event[field].(type) { |
||||
|
case string: |
||||
|
if needsQuote(value) { |
||||
|
buf.WriteString(strconv.Quote(value)) |
||||
|
} else { |
||||
|
buf.WriteString(value) |
||||
|
} |
||||
|
case json.Number: |
||||
|
fmt.Fprint(buf, value) |
||||
|
default: |
||||
|
b, err := json.Marshal(value) |
||||
|
if err != nil { |
||||
|
fmt.Fprintf(buf, "[error: %v]", err) |
||||
|
} else { |
||||
|
fmt.Fprint(buf, string(b)) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
buf.WriteByte('\n') |
||||
|
buf.WriteTo(w.Out) |
||||
|
n = len(p) |
||||
|
return |
||||
|
} |
||||
|
|
||||
|
func formatTime(t interface{}) string { |
||||
|
switch t := t.(type) { |
||||
|
case string: |
||||
|
return t |
||||
|
case json.Number: |
||||
|
u, _ := t.Int64() |
||||
|
return time.Unix(u, 0).Format(time.RFC3339) |
||||
|
} |
||||
|
return "<nil>" |
||||
|
} |
||||
|
|
||||
|
func colorize(s interface{}, color int, enabled bool) string { |
||||
|
if !enabled { |
||||
|
return fmt.Sprintf("%v", s) |
||||
|
} |
||||
|
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", color, s) |
||||
|
} |
||||
|
|
||||
|
func levelColor(level string) int { |
||||
|
switch level { |
||||
|
case "debug": |
||||
|
return cMagenta |
||||
|
case "info": |
||||
|
return cGreen |
||||
|
case "warn": |
||||
|
return cYellow |
||||
|
case "error", "fatal", "panic": |
||||
|
return cRed |
||||
|
default: |
||||
|
return cReset |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
func needsQuote(s string) bool { |
||||
|
for i := range s { |
||||
|
if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' { |
||||
|
return true |
||||
|
} |
||||
|
} |
||||
|
return false |
||||
|
} |
@ -0,0 +1,381 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"io/ioutil" |
||||
|
"net" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
// Context configures a new sub-logger with contextual fields.
|
||||
|
type Context struct { |
||||
|
l Logger |
||||
|
} |
||||
|
|
||||
|
// Logger returns the logger with the context previously set.
|
||||
|
func (c Context) Logger() Logger { |
||||
|
return c.l |
||||
|
} |
||||
|
|
||||
|
// Fields is a helper function to use a map to set fields using type assertion.
|
||||
|
func (c Context) Fields(fields map[string]interface{}) Context { |
||||
|
c.l.context = appendFields(c.l.context, fields) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Dict adds the field key with the dict to the logger context.
|
||||
|
func (c Context) Dict(key string, dict *Event) Context { |
||||
|
dict.buf = enc.AppendEndMarker(dict.buf) |
||||
|
c.l.context = append(enc.AppendKey(c.l.context, key), dict.buf...) |
||||
|
putEvent(dict) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Array adds the field key with an array to the event context.
|
||||
|
// Use zerolog.Arr() to create the array or pass a type that
|
||||
|
// implement the LogArrayMarshaler interface.
|
||||
|
func (c Context) Array(key string, arr LogArrayMarshaler) Context { |
||||
|
c.l.context = enc.AppendKey(c.l.context, key) |
||||
|
if arr, ok := arr.(*Array); ok { |
||||
|
c.l.context = arr.write(c.l.context) |
||||
|
return c |
||||
|
} |
||||
|
var a *Array |
||||
|
if aa, ok := arr.(*Array); ok { |
||||
|
a = aa |
||||
|
} else { |
||||
|
a = Arr() |
||||
|
arr.MarshalZerologArray(a) |
||||
|
} |
||||
|
c.l.context = a.write(c.l.context) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Object marshals an object that implement the LogObjectMarshaler interface.
|
||||
|
func (c Context) Object(key string, obj LogObjectMarshaler) Context { |
||||
|
e := newEvent(levelWriterAdapter{ioutil.Discard}, 0) |
||||
|
e.Object(key, obj) |
||||
|
c.l.context = enc.AppendObjectData(c.l.context, e.buf) |
||||
|
putEvent(e) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.
|
||||
|
func (c Context) EmbedObject(obj LogObjectMarshaler) Context { |
||||
|
e := newEvent(levelWriterAdapter{ioutil.Discard}, 0) |
||||
|
e.EmbedObject(obj) |
||||
|
c.l.context = enc.AppendObjectData(c.l.context, e.buf) |
||||
|
putEvent(e) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Str adds the field key with val as a string to the logger context.
|
||||
|
func (c Context) Str(key, val string) Context { |
||||
|
c.l.context = enc.AppendString(enc.AppendKey(c.l.context, key), val) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Strs adds the field key with val as a string to the logger context.
|
||||
|
func (c Context) Strs(key string, vals []string) Context { |
||||
|
c.l.context = enc.AppendStrings(enc.AppendKey(c.l.context, key), vals) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Bytes adds the field key with val as a []byte to the logger context.
|
||||
|
func (c Context) Bytes(key string, val []byte) Context { |
||||
|
c.l.context = enc.AppendBytes(enc.AppendKey(c.l.context, key), val) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Hex adds the field key with val as a hex string to the logger context.
|
||||
|
func (c Context) Hex(key string, val []byte) Context { |
||||
|
c.l.context = enc.AppendHex(enc.AppendKey(c.l.context, key), val) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// RawJSON adds already encoded JSON to context.
|
||||
|
//
|
||||
|
// No sanity check is performed on b; it must not contain carriage returns and
|
||||
|
// be valid JSON.
|
||||
|
func (c Context) RawJSON(key string, b []byte) Context { |
||||
|
c.l.context = appendJSON(enc.AppendKey(c.l.context, key), b) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// AnErr adds the field key with serialized err to the logger context.
|
||||
|
func (c Context) AnErr(key string, err error) Context { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case nil: |
||||
|
return c |
||||
|
case LogObjectMarshaler: |
||||
|
return c.Object(key, m) |
||||
|
case error: |
||||
|
return c.Str(key, m.Error()) |
||||
|
case string: |
||||
|
return c.Str(key, m) |
||||
|
default: |
||||
|
return c.Interface(key, m) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Errs adds the field key with errs as an array of serialized errors to the
|
||||
|
// logger context.
|
||||
|
func (c Context) Errs(key string, errs []error) Context { |
||||
|
arr := Arr() |
||||
|
for _, err := range errs { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case LogObjectMarshaler: |
||||
|
arr = arr.Object(m) |
||||
|
case error: |
||||
|
arr = arr.Str(m.Error()) |
||||
|
case string: |
||||
|
arr = arr.Str(m) |
||||
|
default: |
||||
|
arr = arr.Interface(m) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return c.Array(key, arr) |
||||
|
} |
||||
|
|
||||
|
// Err adds the field "error" with serialized err to the logger context.
|
||||
|
func (c Context) Err(err error) Context { |
||||
|
return c.AnErr(ErrorFieldName, err) |
||||
|
} |
||||
|
|
||||
|
// Bool adds the field key with val as a bool to the logger context.
|
||||
|
func (c Context) Bool(key string, b bool) Context { |
||||
|
c.l.context = enc.AppendBool(enc.AppendKey(c.l.context, key), b) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Bools adds the field key with val as a []bool to the logger context.
|
||||
|
func (c Context) Bools(key string, b []bool) Context { |
||||
|
c.l.context = enc.AppendBools(enc.AppendKey(c.l.context, key), b) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Int adds the field key with i as a int to the logger context.
|
||||
|
func (c Context) Int(key string, i int) Context { |
||||
|
c.l.context = enc.AppendInt(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Ints adds the field key with i as a []int to the logger context.
|
||||
|
func (c Context) Ints(key string, i []int) Context { |
||||
|
c.l.context = enc.AppendInts(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Int8 adds the field key with i as a int8 to the logger context.
|
||||
|
func (c Context) Int8(key string, i int8) Context { |
||||
|
c.l.context = enc.AppendInt8(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Ints8 adds the field key with i as a []int8 to the logger context.
|
||||
|
func (c Context) Ints8(key string, i []int8) Context { |
||||
|
c.l.context = enc.AppendInts8(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Int16 adds the field key with i as a int16 to the logger context.
|
||||
|
func (c Context) Int16(key string, i int16) Context { |
||||
|
c.l.context = enc.AppendInt16(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Ints16 adds the field key with i as a []int16 to the logger context.
|
||||
|
func (c Context) Ints16(key string, i []int16) Context { |
||||
|
c.l.context = enc.AppendInts16(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Int32 adds the field key with i as a int32 to the logger context.
|
||||
|
func (c Context) Int32(key string, i int32) Context { |
||||
|
c.l.context = enc.AppendInt32(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Ints32 adds the field key with i as a []int32 to the logger context.
|
||||
|
func (c Context) Ints32(key string, i []int32) Context { |
||||
|
c.l.context = enc.AppendInts32(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Int64 adds the field key with i as a int64 to the logger context.
|
||||
|
func (c Context) Int64(key string, i int64) Context { |
||||
|
c.l.context = enc.AppendInt64(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Ints64 adds the field key with i as a []int64 to the logger context.
|
||||
|
func (c Context) Ints64(key string, i []int64) Context { |
||||
|
c.l.context = enc.AppendInts64(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uint adds the field key with i as a uint to the logger context.
|
||||
|
func (c Context) Uint(key string, i uint) Context { |
||||
|
c.l.context = enc.AppendUint(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uints adds the field key with i as a []uint to the logger context.
|
||||
|
func (c Context) Uints(key string, i []uint) Context { |
||||
|
c.l.context = enc.AppendUints(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uint8 adds the field key with i as a uint8 to the logger context.
|
||||
|
func (c Context) Uint8(key string, i uint8) Context { |
||||
|
c.l.context = enc.AppendUint8(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uints8 adds the field key with i as a []uint8 to the logger context.
|
||||
|
func (c Context) Uints8(key string, i []uint8) Context { |
||||
|
c.l.context = enc.AppendUints8(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uint16 adds the field key with i as a uint16 to the logger context.
|
||||
|
func (c Context) Uint16(key string, i uint16) Context { |
||||
|
c.l.context = enc.AppendUint16(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uints16 adds the field key with i as a []uint16 to the logger context.
|
||||
|
func (c Context) Uints16(key string, i []uint16) Context { |
||||
|
c.l.context = enc.AppendUints16(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uint32 adds the field key with i as a uint32 to the logger context.
|
||||
|
func (c Context) Uint32(key string, i uint32) Context { |
||||
|
c.l.context = enc.AppendUint32(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uints32 adds the field key with i as a []uint32 to the logger context.
|
||||
|
func (c Context) Uints32(key string, i []uint32) Context { |
||||
|
c.l.context = enc.AppendUints32(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uint64 adds the field key with i as a uint64 to the logger context.
|
||||
|
func (c Context) Uint64(key string, i uint64) Context { |
||||
|
c.l.context = enc.AppendUint64(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Uints64 adds the field key with i as a []uint64 to the logger context.
|
||||
|
func (c Context) Uints64(key string, i []uint64) Context { |
||||
|
c.l.context = enc.AppendUints64(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Float32 adds the field key with f as a float32 to the logger context.
|
||||
|
func (c Context) Float32(key string, f float32) Context { |
||||
|
c.l.context = enc.AppendFloat32(enc.AppendKey(c.l.context, key), f) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Floats32 adds the field key with f as a []float32 to the logger context.
|
||||
|
func (c Context) Floats32(key string, f []float32) Context { |
||||
|
c.l.context = enc.AppendFloats32(enc.AppendKey(c.l.context, key), f) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Float64 adds the field key with f as a float64 to the logger context.
|
||||
|
func (c Context) Float64(key string, f float64) Context { |
||||
|
c.l.context = enc.AppendFloat64(enc.AppendKey(c.l.context, key), f) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Floats64 adds the field key with f as a []float64 to the logger context.
|
||||
|
func (c Context) Floats64(key string, f []float64) Context { |
||||
|
c.l.context = enc.AppendFloats64(enc.AppendKey(c.l.context, key), f) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
type timestampHook struct{} |
||||
|
|
||||
|
func (ts timestampHook) Run(e *Event, level Level, msg string) { |
||||
|
e.Timestamp() |
||||
|
} |
||||
|
|
||||
|
var th = timestampHook{} |
||||
|
|
||||
|
// Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key.
|
||||
|
// To customize the key name, change zerolog.TimestampFieldName.
|
||||
|
//
|
||||
|
// NOTE: It won't dedupe the "time" key if the *Context has one already.
|
||||
|
func (c Context) Timestamp() Context { |
||||
|
c.l = c.l.Hook(th) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
|
||||
|
func (c Context) Time(key string, t time.Time) Context { |
||||
|
c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
|
||||
|
func (c Context) Times(key string, t []time.Time) Context { |
||||
|
c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Dur adds the fields key with d divided by unit and stored as a float.
|
||||
|
func (c Context) Dur(key string, d time.Duration) Context { |
||||
|
c.l.context = enc.AppendDuration(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Durs adds the fields key with d divided by unit and stored as a float.
|
||||
|
func (c Context) Durs(key string, d []time.Duration) Context { |
||||
|
c.l.context = enc.AppendDurations(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// Interface adds the field key with obj marshaled using reflection.
|
||||
|
func (c Context) Interface(key string, i interface{}) Context { |
||||
|
c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
type callerHook struct{} |
||||
|
|
||||
|
func (ch callerHook) Run(e *Event, level Level, msg string) { |
||||
|
// Three extra frames to skip (added by hook infra).
|
||||
|
e.caller(CallerSkipFrameCount + 3) |
||||
|
} |
||||
|
|
||||
|
var ch = callerHook{} |
||||
|
|
||||
|
// Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
|
||||
|
func (c Context) Caller() Context { |
||||
|
c.l = c.l.Hook(ch) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// IPAddr adds IPv4 or IPv6 Address to the context
|
||||
|
func (c Context) IPAddr(key string, ip net.IP) Context { |
||||
|
c.l.context = enc.AppendIPAddr(enc.AppendKey(c.l.context, key), ip) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context
|
||||
|
func (c Context) IPPrefix(key string, pfx net.IPNet) Context { |
||||
|
c.l.context = enc.AppendIPPrefix(enc.AppendKey(c.l.context, key), pfx) |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// MACAddr adds MAC address to the context
|
||||
|
func (c Context) MACAddr(key string, ha net.HardwareAddr) Context { |
||||
|
c.l.context = enc.AppendMACAddr(enc.AppendKey(c.l.context, key), ha) |
||||
|
return c |
||||
|
} |
@ -0,0 +1,47 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"context" |
||||
|
) |
||||
|
|
||||
|
var disabledLogger *Logger |
||||
|
|
||||
|
func init() { |
||||
|
l := Nop() |
||||
|
disabledLogger = &l |
||||
|
} |
||||
|
|
||||
|
type ctxKey struct{} |
||||
|
|
||||
|
// WithContext returns a copy of ctx with l associated. If an instance of Logger
|
||||
|
// is already in the context, the context is not updated.
|
||||
|
//
|
||||
|
// For instance, to add a field to an existing logger in the context, use this
|
||||
|
// notation:
|
||||
|
//
|
||||
|
// ctx := r.Context()
|
||||
|
// l := zerolog.Ctx(ctx)
|
||||
|
// l.UpdateContext(func(c Context) Context {
|
||||
|
// return c.Str("bar", "baz")
|
||||
|
// })
|
||||
|
func (l *Logger) WithContext(ctx context.Context) context.Context { |
||||
|
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok { |
||||
|
if lp == l { |
||||
|
// Do not store same logger.
|
||||
|
return ctx |
||||
|
} |
||||
|
} else if l.level == Disabled { |
||||
|
// Do not store disabled logger.
|
||||
|
return ctx |
||||
|
} |
||||
|
return context.WithValue(ctx, ctxKey{}, l) |
||||
|
} |
||||
|
|
||||
|
// Ctx returns the Logger associated with the ctx. If no logger
|
||||
|
// is associated, a disabled logger is returned.
|
||||
|
func Ctx(ctx context.Context) *Logger { |
||||
|
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok { |
||||
|
return l |
||||
|
} |
||||
|
return disabledLogger |
||||
|
} |
@ -0,0 +1,56 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"net" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
type encoder interface { |
||||
|
AppendArrayDelim(dst []byte) []byte |
||||
|
AppendArrayEnd(dst []byte) []byte |
||||
|
AppendArrayStart(dst []byte) []byte |
||||
|
AppendBeginMarker(dst []byte) []byte |
||||
|
AppendBool(dst []byte, val bool) []byte |
||||
|
AppendBools(dst []byte, vals []bool) []byte |
||||
|
AppendBytes(dst, s []byte) []byte |
||||
|
AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte |
||||
|
AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte |
||||
|
AppendEndMarker(dst []byte) []byte |
||||
|
AppendFloat32(dst []byte, val float32) []byte |
||||
|
AppendFloat64(dst []byte, val float64) []byte |
||||
|
AppendFloats32(dst []byte, vals []float32) []byte |
||||
|
AppendFloats64(dst []byte, vals []float64) []byte |
||||
|
AppendHex(dst, s []byte) []byte |
||||
|
AppendIPAddr(dst []byte, ip net.IP) []byte |
||||
|
AppendIPPrefix(dst []byte, pfx net.IPNet) []byte |
||||
|
AppendInt(dst []byte, val int) []byte |
||||
|
AppendInt16(dst []byte, val int16) []byte |
||||
|
AppendInt32(dst []byte, val int32) []byte |
||||
|
AppendInt64(dst []byte, val int64) []byte |
||||
|
AppendInt8(dst []byte, val int8) []byte |
||||
|
AppendInterface(dst []byte, i interface{}) []byte |
||||
|
AppendInts(dst []byte, vals []int) []byte |
||||
|
AppendInts16(dst []byte, vals []int16) []byte |
||||
|
AppendInts32(dst []byte, vals []int32) []byte |
||||
|
AppendInts64(dst []byte, vals []int64) []byte |
||||
|
AppendInts8(dst []byte, vals []int8) []byte |
||||
|
AppendKey(dst []byte, key string) []byte |
||||
|
AppendLineBreak(dst []byte) []byte |
||||
|
AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte |
||||
|
AppendNil(dst []byte) []byte |
||||
|
AppendObjectData(dst []byte, o []byte) []byte |
||||
|
AppendString(dst []byte, s string) []byte |
||||
|
AppendStrings(dst []byte, vals []string) []byte |
||||
|
AppendTime(dst []byte, t time.Time, format string) []byte |
||||
|
AppendTimes(dst []byte, vals []time.Time, format string) []byte |
||||
|
AppendUint(dst []byte, val uint) []byte |
||||
|
AppendUint16(dst []byte, val uint16) []byte |
||||
|
AppendUint32(dst []byte, val uint32) []byte |
||||
|
AppendUint64(dst []byte, val uint64) []byte |
||||
|
AppendUint8(dst []byte, val uint8) []byte |
||||
|
AppendUints(dst []byte, vals []uint) []byte |
||||
|
AppendUints16(dst []byte, vals []uint16) []byte |
||||
|
AppendUints32(dst []byte, vals []uint32) []byte |
||||
|
AppendUints64(dst []byte, vals []uint64) []byte |
||||
|
AppendUints8(dst []byte, vals []uint8) []byte |
||||
|
} |
@ -0,0 +1,35 @@ |
|||||
|
// +build binary_log
|
||||
|
|
||||
|
package zerolog |
||||
|
|
||||
|
// This file contains bindings to do binary encoding.
|
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog/internal/cbor" |
||||
|
) |
||||
|
|
||||
|
var ( |
||||
|
_ encoder = (*cbor.Encoder)(nil) |
||||
|
|
||||
|
enc = cbor.Encoder{} |
||||
|
) |
||||
|
|
||||
|
func appendJSON(dst []byte, j []byte) []byte { |
||||
|
return cbor.AppendEmbeddedJSON(dst, j) |
||||
|
} |
||||
|
|
||||
|
// decodeIfBinaryToString - converts a binary formatted log msg to a
|
||||
|
// JSON formatted String Log message.
|
||||
|
func decodeIfBinaryToString(in []byte) string { |
||||
|
return cbor.DecodeIfBinaryToString(in) |
||||
|
} |
||||
|
|
||||
|
func decodeObjectToStr(in []byte) string { |
||||
|
return cbor.DecodeObjectToStr(in) |
||||
|
} |
||||
|
|
||||
|
// decodeIfBinaryToBytes - converts a binary formatted log msg to a
|
||||
|
// JSON formatted Bytes Log message.
|
||||
|
func decodeIfBinaryToBytes(in []byte) []byte { |
||||
|
return cbor.DecodeIfBinaryToBytes(in) |
||||
|
} |
@ -0,0 +1,32 @@ |
|||||
|
// +build !binary_log
|
||||
|
|
||||
|
package zerolog |
||||
|
|
||||
|
// encoder_json.go file contains bindings to generate
|
||||
|
// JSON encoded byte stream.
|
||||
|
|
||||
|
import ( |
||||
|
"github.com/rs/zerolog/internal/json" |
||||
|
) |
||||
|
|
||||
|
var ( |
||||
|
_ encoder = (*json.Encoder)(nil) |
||||
|
|
||||
|
enc = json.Encoder{} |
||||
|
) |
||||
|
|
||||
|
func appendJSON(dst []byte, j []byte) []byte { |
||||
|
return append(dst, j...) |
||||
|
} |
||||
|
|
||||
|
func decodeIfBinaryToString(in []byte) string { |
||||
|
return string(in) |
||||
|
} |
||||
|
|
||||
|
func decodeObjectToStr(in []byte) string { |
||||
|
return string(in) |
||||
|
} |
||||
|
|
||||
|
func decodeIfBinaryToBytes(in []byte) []byte { |
||||
|
return in |
||||
|
} |
@ -0,0 +1,673 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"fmt" |
||||
|
"net" |
||||
|
"os" |
||||
|
"runtime" |
||||
|
"strconv" |
||||
|
"sync" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
var eventPool = &sync.Pool{ |
||||
|
New: func() interface{} { |
||||
|
return &Event{ |
||||
|
buf: make([]byte, 0, 500), |
||||
|
} |
||||
|
}, |
||||
|
} |
||||
|
|
||||
|
// ErrorMarshalFunc allows customization of global error marshaling
|
||||
|
var ErrorMarshalFunc = func(err error) interface{} { |
||||
|
return err |
||||
|
} |
||||
|
|
||||
|
// Event represents a log event. It is instanced by one of the level method of
|
||||
|
// Logger and finalized by the Msg or Msgf method.
|
||||
|
type Event struct { |
||||
|
buf []byte |
||||
|
w LevelWriter |
||||
|
level Level |
||||
|
done func(msg string) |
||||
|
ch []Hook // hooks from context
|
||||
|
} |
||||
|
|
||||
|
func putEvent(e *Event) { |
||||
|
// Proper usage of a sync.Pool requires each entry to have approximately
|
||||
|
// the same memory cost. To obtain this property when the stored type
|
||||
|
// contains a variably-sized buffer, we add a hard limit on the maximum buffer
|
||||
|
// to place back in the pool.
|
||||
|
//
|
||||
|
// See https://golang.org/issue/23199
|
||||
|
const maxSize = 1 << 16 // 64KiB
|
||||
|
if cap(e.buf) > maxSize { |
||||
|
return |
||||
|
} |
||||
|
eventPool.Put(e) |
||||
|
} |
||||
|
|
||||
|
// LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface
|
||||
|
// to be implemented by types used with Event/Context's Object methods.
|
||||
|
type LogObjectMarshaler interface { |
||||
|
MarshalZerologObject(e *Event) |
||||
|
} |
||||
|
|
||||
|
// LogArrayMarshaler provides a strongly-typed and encoding-agnostic interface
|
||||
|
// to be implemented by types used with Event/Context's Array methods.
|
||||
|
type LogArrayMarshaler interface { |
||||
|
MarshalZerologArray(a *Array) |
||||
|
} |
||||
|
|
||||
|
func newEvent(w LevelWriter, level Level) *Event { |
||||
|
e := eventPool.Get().(*Event) |
||||
|
e.buf = e.buf[:0] |
||||
|
e.ch = nil |
||||
|
e.buf = enc.AppendBeginMarker(e.buf) |
||||
|
e.w = w |
||||
|
e.level = level |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
func (e *Event) write() (err error) { |
||||
|
if e == nil { |
||||
|
return nil |
||||
|
} |
||||
|
if e.level != Disabled { |
||||
|
e.buf = enc.AppendEndMarker(e.buf) |
||||
|
e.buf = enc.AppendLineBreak(e.buf) |
||||
|
if e.w != nil { |
||||
|
_, err = e.w.WriteLevel(e.level, e.buf) |
||||
|
} |
||||
|
} |
||||
|
putEvent(e) |
||||
|
return |
||||
|
} |
||||
|
|
||||
|
// Enabled return false if the *Event is going to be filtered out by
|
||||
|
// log level or sampling.
|
||||
|
func (e *Event) Enabled() bool { |
||||
|
return e != nil && e.level != Disabled |
||||
|
} |
||||
|
|
||||
|
// Discard disables the event so Msg(f) won't print it.
|
||||
|
func (e *Event) Discard() *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.level = Disabled |
||||
|
return nil |
||||
|
} |
||||
|
|
||||
|
// Msg sends the *Event with msg added as the message field if not empty.
|
||||
|
//
|
||||
|
// NOTICE: once this method is called, the *Event should be disposed.
|
||||
|
// Calling Msg twice can have unexpected result.
|
||||
|
func (e *Event) Msg(msg string) { |
||||
|
if e == nil { |
||||
|
return |
||||
|
} |
||||
|
e.msg(msg) |
||||
|
} |
||||
|
|
||||
|
// Msgf sends the event with formated msg added as the message field if not empty.
|
||||
|
//
|
||||
|
// NOTICE: once this methid is called, the *Event should be disposed.
|
||||
|
// Calling Msg twice can have unexpected result.
|
||||
|
func (e *Event) Msgf(format string, v ...interface{}) { |
||||
|
if e == nil { |
||||
|
return |
||||
|
} |
||||
|
e.msg(fmt.Sprintf(format, v...)) |
||||
|
} |
||||
|
|
||||
|
func (e *Event) msg(msg string) { |
||||
|
if len(e.ch) > 0 { |
||||
|
e.ch[0].Run(e, e.level, msg) |
||||
|
if len(e.ch) > 1 { |
||||
|
for _, hook := range e.ch[1:] { |
||||
|
hook.Run(e, e.level, msg) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
if msg != "" { |
||||
|
e.buf = enc.AppendString(enc.AppendKey(e.buf, MessageFieldName), msg) |
||||
|
} |
||||
|
if e.done != nil { |
||||
|
defer e.done(msg) |
||||
|
} |
||||
|
if err := e.write(); err != nil { |
||||
|
fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v", err) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Fields is a helper function to use a map to set fields using type assertion.
|
||||
|
func (e *Event) Fields(fields map[string]interface{}) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = appendFields(e.buf, fields) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Dict adds the field key with a dict to the event context.
|
||||
|
// Use zerolog.Dict() to create the dictionary.
|
||||
|
func (e *Event) Dict(key string, dict *Event) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
dict.buf = enc.AppendEndMarker(dict.buf) |
||||
|
e.buf = append(enc.AppendKey(e.buf, key), dict.buf...) |
||||
|
putEvent(dict) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Dict creates an Event to be used with the *Event.Dict method.
|
||||
|
// Call usual field methods like Str, Int etc to add fields to this
|
||||
|
// event and give it as argument the *Event.Dict method.
|
||||
|
func Dict() *Event { |
||||
|
return newEvent(nil, 0) |
||||
|
} |
||||
|
|
||||
|
// Array adds the field key with an array to the event context.
|
||||
|
// Use zerolog.Arr() to create the array or pass a type that
|
||||
|
// implement the LogArrayMarshaler interface.
|
||||
|
func (e *Event) Array(key string, arr LogArrayMarshaler) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendKey(e.buf, key) |
||||
|
var a *Array |
||||
|
if aa, ok := arr.(*Array); ok { |
||||
|
a = aa |
||||
|
} else { |
||||
|
a = Arr() |
||||
|
arr.MarshalZerologArray(a) |
||||
|
} |
||||
|
e.buf = a.write(e.buf) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
func (e *Event) appendObject(obj LogObjectMarshaler) { |
||||
|
e.buf = enc.AppendBeginMarker(e.buf) |
||||
|
obj.MarshalZerologObject(e) |
||||
|
e.buf = enc.AppendEndMarker(e.buf) |
||||
|
} |
||||
|
|
||||
|
// Object marshals an object that implement the LogObjectMarshaler interface.
|
||||
|
func (e *Event) Object(key string, obj LogObjectMarshaler) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendKey(e.buf, key) |
||||
|
e.appendObject(obj) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Object marshals an object that implement the LogObjectMarshaler interface.
|
||||
|
func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
obj.MarshalZerologObject(e) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Str adds the field key with val as a string to the *Event context.
|
||||
|
func (e *Event) Str(key, val string) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendString(enc.AppendKey(e.buf, key), val) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Strs adds the field key with vals as a []string to the *Event context.
|
||||
|
func (e *Event) Strs(key string, vals []string) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendStrings(enc.AppendKey(e.buf, key), vals) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Bytes adds the field key with val as a string to the *Event context.
|
||||
|
//
|
||||
|
// Runes outside of normal ASCII ranges will be hex-encoded in the resulting
|
||||
|
// JSON.
|
||||
|
func (e *Event) Bytes(key string, val []byte) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendBytes(enc.AppendKey(e.buf, key), val) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Hex adds the field key with val as a hex string to the *Event context.
|
||||
|
func (e *Event) Hex(key string, val []byte) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendHex(enc.AppendKey(e.buf, key), val) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// RawJSON adds already encoded JSON to the log line under key.
|
||||
|
//
|
||||
|
// No sanity check is performed on b; it must not contain carriage returns and
|
||||
|
// be valid JSON.
|
||||
|
func (e *Event) RawJSON(key string, b []byte) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = appendJSON(enc.AppendKey(e.buf, key), b) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// AnErr adds the field key with serialized err to the *Event context.
|
||||
|
// If err is nil, no field is added.
|
||||
|
func (e *Event) AnErr(key string, err error) *Event { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case nil: |
||||
|
return e |
||||
|
case LogObjectMarshaler: |
||||
|
return e.Object(key, m) |
||||
|
case error: |
||||
|
return e.Str(key, m.Error()) |
||||
|
case string: |
||||
|
return e.Str(key, m) |
||||
|
default: |
||||
|
return e.Interface(key, m) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Errs adds the field key with errs as an array of serialized errors to the
|
||||
|
// *Event context.
|
||||
|
func (e *Event) Errs(key string, errs []error) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
arr := Arr() |
||||
|
for _, err := range errs { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case LogObjectMarshaler: |
||||
|
arr = arr.Object(m) |
||||
|
case error: |
||||
|
arr = arr.Err(m) |
||||
|
case string: |
||||
|
arr = arr.Str(m) |
||||
|
default: |
||||
|
arr = arr.Interface(m) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return e.Array(key, arr) |
||||
|
} |
||||
|
|
||||
|
// Err adds the field "error" with serialized err to the *Event context.
|
||||
|
// If err is nil, no field is added.
|
||||
|
// To customize the key name, change zerolog.ErrorFieldName.
|
||||
|
func (e *Event) Err(err error) *Event { |
||||
|
return e.AnErr(ErrorFieldName, err) |
||||
|
} |
||||
|
|
||||
|
// Bool adds the field key with val as a bool to the *Event context.
|
||||
|
func (e *Event) Bool(key string, b bool) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendBool(enc.AppendKey(e.buf, key), b) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Bools adds the field key with val as a []bool to the *Event context.
|
||||
|
func (e *Event) Bools(key string, b []bool) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendBools(enc.AppendKey(e.buf, key), b) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Int adds the field key with i as a int to the *Event context.
|
||||
|
func (e *Event) Int(key string, i int) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInt(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Ints adds the field key with i as a []int to the *Event context.
|
||||
|
func (e *Event) Ints(key string, i []int) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInts(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Int8 adds the field key with i as a int8 to the *Event context.
|
||||
|
func (e *Event) Int8(key string, i int8) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInt8(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Ints8 adds the field key with i as a []int8 to the *Event context.
|
||||
|
func (e *Event) Ints8(key string, i []int8) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInts8(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Int16 adds the field key with i as a int16 to the *Event context.
|
||||
|
func (e *Event) Int16(key string, i int16) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInt16(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Ints16 adds the field key with i as a []int16 to the *Event context.
|
||||
|
func (e *Event) Ints16(key string, i []int16) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInts16(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Int32 adds the field key with i as a int32 to the *Event context.
|
||||
|
func (e *Event) Int32(key string, i int32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInt32(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Ints32 adds the field key with i as a []int32 to the *Event context.
|
||||
|
func (e *Event) Ints32(key string, i []int32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInts32(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Int64 adds the field key with i as a int64 to the *Event context.
|
||||
|
func (e *Event) Int64(key string, i int64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInt64(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Ints64 adds the field key with i as a []int64 to the *Event context.
|
||||
|
func (e *Event) Ints64(key string, i []int64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendInts64(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uint adds the field key with i as a uint to the *Event context.
|
||||
|
func (e *Event) Uint(key string, i uint) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUint(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uints adds the field key with i as a []int to the *Event context.
|
||||
|
func (e *Event) Uints(key string, i []uint) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUints(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uint8 adds the field key with i as a uint8 to the *Event context.
|
||||
|
func (e *Event) Uint8(key string, i uint8) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUint8(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uints8 adds the field key with i as a []int8 to the *Event context.
|
||||
|
func (e *Event) Uints8(key string, i []uint8) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUints8(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uint16 adds the field key with i as a uint16 to the *Event context.
|
||||
|
func (e *Event) Uint16(key string, i uint16) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUint16(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uints16 adds the field key with i as a []int16 to the *Event context.
|
||||
|
func (e *Event) Uints16(key string, i []uint16) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUints16(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uint32 adds the field key with i as a uint32 to the *Event context.
|
||||
|
func (e *Event) Uint32(key string, i uint32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUint32(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uints32 adds the field key with i as a []int32 to the *Event context.
|
||||
|
func (e *Event) Uints32(key string, i []uint32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUints32(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uint64 adds the field key with i as a uint64 to the *Event context.
|
||||
|
func (e *Event) Uint64(key string, i uint64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUint64(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Uints64 adds the field key with i as a []int64 to the *Event context.
|
||||
|
func (e *Event) Uints64(key string, i []uint64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendUints64(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Float32 adds the field key with f as a float32 to the *Event context.
|
||||
|
func (e *Event) Float32(key string, f float32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendFloat32(enc.AppendKey(e.buf, key), f) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Floats32 adds the field key with f as a []float32 to the *Event context.
|
||||
|
func (e *Event) Floats32(key string, f []float32) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendFloats32(enc.AppendKey(e.buf, key), f) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Float64 adds the field key with f as a float64 to the *Event context.
|
||||
|
func (e *Event) Float64(key string, f float64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendFloat64(enc.AppendKey(e.buf, key), f) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Floats64 adds the field key with f as a []float64 to the *Event context.
|
||||
|
func (e *Event) Floats64(key string, f []float64) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendFloats64(enc.AppendKey(e.buf, key), f) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key.
|
||||
|
// To customize the key name, change zerolog.TimestampFieldName.
|
||||
|
//
|
||||
|
// NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one
|
||||
|
// already.
|
||||
|
func (e *Event) Timestamp() *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendTime(enc.AppendKey(e.buf, TimestampFieldName), TimestampFunc(), TimeFieldFormat) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
|
||||
|
func (e *Event) Time(key string, t time.Time) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendTime(enc.AppendKey(e.buf, key), t, TimeFieldFormat) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
|
||||
|
func (e *Event) Times(key string, t []time.Time) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendTimes(enc.AppendKey(e.buf, key), t, TimeFieldFormat) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit.
|
||||
|
// If zerolog.DurationFieldInteger is true, durations are rendered as integer
|
||||
|
// instead of float.
|
||||
|
func (e *Event) Dur(key string, d time.Duration) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Durs adds the field key with duration d stored as zerolog.DurationFieldUnit.
|
||||
|
// If zerolog.DurationFieldInteger is true, durations are rendered as integer
|
||||
|
// instead of float.
|
||||
|
func (e *Event) Durs(key string, d []time.Duration) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendDurations(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// TimeDiff adds the field key with positive duration between time t and start.
|
||||
|
// If time t is not greater than start, duration will be 0.
|
||||
|
// Duration format follows the same principle as Dur().
|
||||
|
func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
var d time.Duration |
||||
|
if t.After(start) { |
||||
|
d = t.Sub(start) |
||||
|
} |
||||
|
e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Interface adds the field key with i marshaled using reflection.
|
||||
|
func (e *Event) Interface(key string, i interface{}) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
if obj, ok := i.(LogObjectMarshaler); ok { |
||||
|
return e.Object(key, obj) |
||||
|
} |
||||
|
e.buf = enc.AppendInterface(enc.AppendKey(e.buf, key), i) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
|
||||
|
func (e *Event) Caller() *Event { |
||||
|
return e.caller(CallerSkipFrameCount) |
||||
|
} |
||||
|
|
||||
|
func (e *Event) caller(skip int) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
_, file, line, ok := runtime.Caller(skip) |
||||
|
if !ok { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), file+":"+strconv.Itoa(line)) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// IPAddr adds IPv4 or IPv6 Address to the event
|
||||
|
func (e *Event) IPAddr(key string, ip net.IP) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendIPAddr(enc.AppendKey(e.buf, key), ip) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event
|
||||
|
func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendIPPrefix(enc.AppendKey(e.buf, key), pfx) |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// MACAddr adds MAC address to the event
|
||||
|
func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event { |
||||
|
if e == nil { |
||||
|
return e |
||||
|
} |
||||
|
e.buf = enc.AppendMACAddr(enc.AppendKey(e.buf, key), ha) |
||||
|
return e |
||||
|
} |
@ -0,0 +1,178 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"net" |
||||
|
"sort" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
func appendFields(dst []byte, fields map[string]interface{}) []byte { |
||||
|
keys := make([]string, 0, len(fields)) |
||||
|
for key := range fields { |
||||
|
keys = append(keys, key) |
||||
|
} |
||||
|
sort.Strings(keys) |
||||
|
for _, key := range keys { |
||||
|
dst = enc.AppendKey(dst, key) |
||||
|
val := fields[key] |
||||
|
if val, ok := val.(LogObjectMarshaler); ok { |
||||
|
e := newEvent(nil, 0) |
||||
|
e.buf = e.buf[:0] |
||||
|
e.appendObject(val) |
||||
|
dst = append(dst, e.buf...) |
||||
|
putEvent(e) |
||||
|
continue |
||||
|
} |
||||
|
switch val := val.(type) { |
||||
|
case string: |
||||
|
dst = enc.AppendString(dst, val) |
||||
|
case []byte: |
||||
|
dst = enc.AppendBytes(dst, val) |
||||
|
case error: |
||||
|
marshaled := ErrorMarshalFunc(val) |
||||
|
switch m := marshaled.(type) { |
||||
|
case LogObjectMarshaler: |
||||
|
e := newEvent(nil, 0) |
||||
|
e.buf = e.buf[:0] |
||||
|
e.appendObject(m) |
||||
|
dst = append(dst, e.buf...) |
||||
|
putEvent(e) |
||||
|
case error: |
||||
|
dst = enc.AppendString(dst, m.Error()) |
||||
|
case string: |
||||
|
dst = enc.AppendString(dst, m) |
||||
|
default: |
||||
|
dst = enc.AppendInterface(dst, m) |
||||
|
} |
||||
|
case []error: |
||||
|
dst = enc.AppendArrayStart(dst) |
||||
|
for i, err := range val { |
||||
|
marshaled := ErrorMarshalFunc(err) |
||||
|
switch m := marshaled.(type) { |
||||
|
case LogObjectMarshaler: |
||||
|
e := newEvent(nil, 0) |
||||
|
e.buf = e.buf[:0] |
||||
|
e.appendObject(m) |
||||
|
dst = append(dst, e.buf...) |
||||
|
putEvent(e) |
||||
|
case error: |
||||
|
dst = enc.AppendString(dst, m.Error()) |
||||
|
case string: |
||||
|
dst = enc.AppendString(dst, m) |
||||
|
default: |
||||
|
dst = enc.AppendInterface(dst, m) |
||||
|
} |
||||
|
|
||||
|
if i < (len(val) - 1) { |
||||
|
enc.AppendArrayDelim(dst) |
||||
|
} |
||||
|
} |
||||
|
dst = enc.AppendArrayEnd(dst) |
||||
|
case bool: |
||||
|
dst = enc.AppendBool(dst, val) |
||||
|
case int: |
||||
|
dst = enc.AppendInt(dst, val) |
||||
|
case int8: |
||||
|
dst = enc.AppendInt8(dst, val) |
||||
|
case int16: |
||||
|
dst = enc.AppendInt16(dst, val) |
||||
|
case int32: |
||||
|
dst = enc.AppendInt32(dst, val) |
||||
|
case int64: |
||||
|
dst = enc.AppendInt64(dst, val) |
||||
|
case uint: |
||||
|
dst = enc.AppendUint(dst, val) |
||||
|
case uint8: |
||||
|
dst = enc.AppendUint8(dst, val) |
||||
|
case uint16: |
||||
|
dst = enc.AppendUint16(dst, val) |
||||
|
case uint32: |
||||
|
dst = enc.AppendUint32(dst, val) |
||||
|
case uint64: |
||||
|
dst = enc.AppendUint64(dst, val) |
||||
|
case float32: |
||||
|
dst = enc.AppendFloat32(dst, val) |
||||
|
case float64: |
||||
|
dst = enc.AppendFloat64(dst, val) |
||||
|
case time.Time: |
||||
|
dst = enc.AppendTime(dst, val, TimeFieldFormat) |
||||
|
case time.Duration: |
||||
|
dst = enc.AppendDuration(dst, val, DurationFieldUnit, DurationFieldInteger) |
||||
|
case *string: |
||||
|
dst = enc.AppendString(dst, *val) |
||||
|
case *bool: |
||||
|
dst = enc.AppendBool(dst, *val) |
||||
|
case *int: |
||||
|
dst = enc.AppendInt(dst, *val) |
||||
|
case *int8: |
||||
|
dst = enc.AppendInt8(dst, *val) |
||||
|
case *int16: |
||||
|
dst = enc.AppendInt16(dst, *val) |
||||
|
case *int32: |
||||
|
dst = enc.AppendInt32(dst, *val) |
||||
|
case *int64: |
||||
|
dst = enc.AppendInt64(dst, *val) |
||||
|
case *uint: |
||||
|
dst = enc.AppendUint(dst, *val) |
||||
|
case *uint8: |
||||
|
dst = enc.AppendUint8(dst, *val) |
||||
|
case *uint16: |
||||
|
dst = enc.AppendUint16(dst, *val) |
||||
|
case *uint32: |
||||
|
dst = enc.AppendUint32(dst, *val) |
||||
|
case *uint64: |
||||
|
dst = enc.AppendUint64(dst, *val) |
||||
|
case *float32: |
||||
|
dst = enc.AppendFloat32(dst, *val) |
||||
|
case *float64: |
||||
|
dst = enc.AppendFloat64(dst, *val) |
||||
|
case *time.Time: |
||||
|
dst = enc.AppendTime(dst, *val, TimeFieldFormat) |
||||
|
case *time.Duration: |
||||
|
dst = enc.AppendDuration(dst, *val, DurationFieldUnit, DurationFieldInteger) |
||||
|
case []string: |
||||
|
dst = enc.AppendStrings(dst, val) |
||||
|
case []bool: |
||||
|
dst = enc.AppendBools(dst, val) |
||||
|
case []int: |
||||
|
dst = enc.AppendInts(dst, val) |
||||
|
case []int8: |
||||
|
dst = enc.AppendInts8(dst, val) |
||||
|
case []int16: |
||||
|
dst = enc.AppendInts16(dst, val) |
||||
|
case []int32: |
||||
|
dst = enc.AppendInts32(dst, val) |
||||
|
case []int64: |
||||
|
dst = enc.AppendInts64(dst, val) |
||||
|
case []uint: |
||||
|
dst = enc.AppendUints(dst, val) |
||||
|
// case []uint8:
|
||||
|
// dst = enc.AppendUints8(dst, val)
|
||||
|
case []uint16: |
||||
|
dst = enc.AppendUints16(dst, val) |
||||
|
case []uint32: |
||||
|
dst = enc.AppendUints32(dst, val) |
||||
|
case []uint64: |
||||
|
dst = enc.AppendUints64(dst, val) |
||||
|
case []float32: |
||||
|
dst = enc.AppendFloats32(dst, val) |
||||
|
case []float64: |
||||
|
dst = enc.AppendFloats64(dst, val) |
||||
|
case []time.Time: |
||||
|
dst = enc.AppendTimes(dst, val, TimeFieldFormat) |
||||
|
case []time.Duration: |
||||
|
dst = enc.AppendDurations(dst, val, DurationFieldUnit, DurationFieldInteger) |
||||
|
case nil: |
||||
|
dst = enc.AppendNil(dst) |
||||
|
case net.IP: |
||||
|
dst = enc.AppendIPAddr(dst, val) |
||||
|
case net.IPNet: |
||||
|
dst = enc.AppendIPPrefix(dst, val) |
||||
|
case net.HardwareAddr: |
||||
|
dst = enc.AppendMACAddr(dst, val) |
||||
|
default: |
||||
|
dst = enc.AppendInterface(dst, val) |
||||
|
} |
||||
|
} |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,71 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import "time" |
||||
|
import "sync/atomic" |
||||
|
|
||||
|
var ( |
||||
|
// TimestampFieldName is the field name used for the timestamp field.
|
||||
|
TimestampFieldName = "time" |
||||
|
|
||||
|
// LevelFieldName is the field name used for the level field.
|
||||
|
LevelFieldName = "level" |
||||
|
|
||||
|
// MessageFieldName is the field name used for the message field.
|
||||
|
MessageFieldName = "message" |
||||
|
|
||||
|
// ErrorFieldName is the field name used for error fields.
|
||||
|
ErrorFieldName = "error" |
||||
|
|
||||
|
// CallerFieldName is the field name used for caller field.
|
||||
|
CallerFieldName = "caller" |
||||
|
|
||||
|
// CallerSkipFrameCount is the number of stack frames to skip to find the caller.
|
||||
|
CallerSkipFrameCount = 2 |
||||
|
|
||||
|
// TimeFieldFormat defines the time format of the Time field type.
|
||||
|
// If set to an empty string, the time is formatted as an UNIX timestamp
|
||||
|
// as integer.
|
||||
|
TimeFieldFormat = time.RFC3339 |
||||
|
|
||||
|
// TimestampFunc defines the function called to generate a timestamp.
|
||||
|
TimestampFunc = time.Now |
||||
|
|
||||
|
// DurationFieldUnit defines the unit for time.Duration type fields added
|
||||
|
// using the Dur method.
|
||||
|
DurationFieldUnit = time.Millisecond |
||||
|
|
||||
|
// DurationFieldInteger renders Dur fields as integer instead of float if
|
||||
|
// set to true.
|
||||
|
DurationFieldInteger = false |
||||
|
) |
||||
|
|
||||
|
var ( |
||||
|
gLevel = new(uint32) |
||||
|
disableSampling = new(uint32) |
||||
|
) |
||||
|
|
||||
|
// SetGlobalLevel sets the global override for log level. If this
|
||||
|
// values is raised, all Loggers will use at least this value.
|
||||
|
//
|
||||
|
// To globally disable logs, set GlobalLevel to Disabled.
|
||||
|
func SetGlobalLevel(l Level) { |
||||
|
atomic.StoreUint32(gLevel, uint32(l)) |
||||
|
} |
||||
|
|
||||
|
// GlobalLevel returns the current global log level
|
||||
|
func GlobalLevel() Level { |
||||
|
return Level(atomic.LoadUint32(gLevel)) |
||||
|
} |
||||
|
|
||||
|
// DisableSampling will disable sampling in all Loggers if true.
|
||||
|
func DisableSampling(v bool) { |
||||
|
var i uint32 |
||||
|
if v { |
||||
|
i = 1 |
||||
|
} |
||||
|
atomic.StoreUint32(disableSampling, i) |
||||
|
} |
||||
|
|
||||
|
func samplingDisabled() bool { |
||||
|
return atomic.LoadUint32(disableSampling) == 1 |
||||
|
} |
@ -0,0 +1 @@ |
|||||
|
module github.com/rs/zerolog |
@ -0,0 +1,60 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
// Hook defines an interface to a log hook.
|
||||
|
type Hook interface { |
||||
|
// Run runs the hook with the event.
|
||||
|
Run(e *Event, level Level, message string) |
||||
|
} |
||||
|
|
||||
|
// HookFunc is an adaptor to allow the use of an ordinary function
|
||||
|
// as a Hook.
|
||||
|
type HookFunc func(e *Event, level Level, message string) |
||||
|
|
||||
|
// Run implements the Hook interface.
|
||||
|
func (h HookFunc) Run(e *Event, level Level, message string) { |
||||
|
h(e, level, message) |
||||
|
} |
||||
|
|
||||
|
// LevelHook applies a different hook for each level.
|
||||
|
type LevelHook struct { |
||||
|
NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook |
||||
|
} |
||||
|
|
||||
|
// Run implements the Hook interface.
|
||||
|
func (h LevelHook) Run(e *Event, level Level, message string) { |
||||
|
switch level { |
||||
|
case DebugLevel: |
||||
|
if h.DebugHook != nil { |
||||
|
h.DebugHook.Run(e, level, message) |
||||
|
} |
||||
|
case InfoLevel: |
||||
|
if h.InfoHook != nil { |
||||
|
h.InfoHook.Run(e, level, message) |
||||
|
} |
||||
|
case WarnLevel: |
||||
|
if h.WarnHook != nil { |
||||
|
h.WarnHook.Run(e, level, message) |
||||
|
} |
||||
|
case ErrorLevel: |
||||
|
if h.ErrorHook != nil { |
||||
|
h.ErrorHook.Run(e, level, message) |
||||
|
} |
||||
|
case FatalLevel: |
||||
|
if h.FatalHook != nil { |
||||
|
h.FatalHook.Run(e, level, message) |
||||
|
} |
||||
|
case PanicLevel: |
||||
|
if h.PanicHook != nil { |
||||
|
h.PanicHook.Run(e, level, message) |
||||
|
} |
||||
|
case NoLevel: |
||||
|
if h.NoLevelHook != nil { |
||||
|
h.NoLevelHook.Run(e, level, message) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// NewLevelHook returns a new LevelHook.
|
||||
|
func NewLevelHook() LevelHook { |
||||
|
return LevelHook{} |
||||
|
} |
@ -0,0 +1,56 @@ |
|||||
|
## Reference: |
||||
|
CBOR Encoding is described in [RFC7049](https://tools.ietf.org/html/rfc7049) |
||||
|
|
||||
|
## Comparison of JSON vs CBOR |
||||
|
|
||||
|
Two main areas of reduction are: |
||||
|
|
||||
|
1. CPU usage to write a log msg |
||||
|
2. Size (in bytes) of log messages. |
||||
|
|
||||
|
|
||||
|
CPU Usage savings are below: |
||||
|
``` |
||||
|
name JSON time/op CBOR time/op delta |
||||
|
Info-32 15.3ns ± 1% 11.7ns ± 3% -23.78% (p=0.000 n=9+10) |
||||
|
ContextFields-32 16.2ns ± 2% 12.3ns ± 3% -23.97% (p=0.000 n=9+9) |
||||
|
ContextAppend-32 6.70ns ± 0% 6.20ns ± 0% -7.44% (p=0.000 n=9+9) |
||||
|
LogFields-32 66.4ns ± 0% 24.6ns ± 2% -62.89% (p=0.000 n=10+9) |
||||
|
LogArrayObject-32 911ns ±11% 768ns ± 6% -15.64% (p=0.000 n=10+10) |
||||
|
LogFieldType/Floats-32 70.3ns ± 2% 29.5ns ± 1% -57.98% (p=0.000 n=10+10) |
||||
|
LogFieldType/Err-32 14.0ns ± 3% 12.1ns ± 8% -13.20% (p=0.000 n=8+10) |
||||
|
LogFieldType/Dur-32 17.2ns ± 2% 13.1ns ± 1% -24.27% (p=0.000 n=10+9) |
||||
|
LogFieldType/Object-32 54.3ns ±11% 52.3ns ± 7% ~ (p=0.239 n=10+10) |
||||
|
LogFieldType/Ints-32 20.3ns ± 2% 15.1ns ± 2% -25.50% (p=0.000 n=9+10) |
||||
|
LogFieldType/Interfaces-32 642ns ±11% 621ns ± 9% ~ (p=0.118 n=10+10) |
||||
|
LogFieldType/Interface(Objects)-32 635ns ±13% 632ns ± 9% ~ (p=0.592 n=10+10) |
||||
|
LogFieldType/Times-32 294ns ± 0% 27ns ± 1% -90.71% (p=0.000 n=10+9) |
||||
|
LogFieldType/Durs-32 121ns ± 0% 33ns ± 2% -72.44% (p=0.000 n=9+9) |
||||
|
LogFieldType/Interface(Object)-32 56.6ns ± 8% 52.3ns ± 8% -7.54% (p=0.007 n=10+10) |
||||
|
LogFieldType/Errs-32 17.8ns ± 3% 16.1ns ± 2% -9.71% (p=0.000 n=10+9) |
||||
|
LogFieldType/Time-32 40.5ns ± 1% 12.7ns ± 6% -68.66% (p=0.000 n=8+9) |
||||
|
LogFieldType/Bool-32 12.0ns ± 5% 10.2ns ± 2% -15.18% (p=0.000 n=10+8) |
||||
|
LogFieldType/Bools-32 17.2ns ± 2% 12.6ns ± 4% -26.63% (p=0.000 n=10+10) |
||||
|
LogFieldType/Int-32 12.3ns ± 2% 11.2ns ± 4% -9.27% (p=0.000 n=9+10) |
||||
|
LogFieldType/Float-32 16.7ns ± 1% 12.6ns ± 2% -24.42% (p=0.000 n=7+9) |
||||
|
LogFieldType/Str-32 12.7ns ± 7% 11.3ns ± 7% -10.88% (p=0.000 n=10+9) |
||||
|
LogFieldType/Strs-32 20.3ns ± 3% 18.2ns ± 3% -10.25% (p=0.000 n=9+10) |
||||
|
LogFieldType/Interface-32 183ns ±12% 175ns ± 9% ~ (p=0.078 n=10+10) |
||||
|
``` |
||||
|
|
||||
|
Log message size savings is greatly dependent on the number and type of fields in the log message. |
||||
|
Assuming this log message (with an Integer, timestamp and string, in addition to level). |
||||
|
|
||||
|
`{"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"}` |
||||
|
|
||||
|
Two measurements were done for the log file sizes - one without any compression, second |
||||
|
using [compress/zlib](https://golang.org/pkg/compress/zlib/). |
||||
|
|
||||
|
Results for 10,000 log messages: |
||||
|
|
||||
|
| Log Format | Plain File Size (in KB) | Compressed File Size (in KB) | |
||||
|
| :--- | :---: | :---: | |
||||
|
| JSON | 920 | 28 | |
||||
|
| CBOR | 550 | 28 | |
||||
|
|
||||
|
The example used to calculate the above data is available in [Examples](examples). |
@ -0,0 +1,11 @@ |
|||||
|
package cbor |
||||
|
|
||||
|
type Encoder struct{} |
||||
|
|
||||
|
// AppendKey adds a key (string) to the binary encoded log message
|
||||
|
func (e Encoder) AppendKey(dst []byte, key string) []byte { |
||||
|
if len(dst) < 1 { |
||||
|
dst = e.AppendBeginMarker(dst) |
||||
|
} |
||||
|
return e.AppendString(dst, key) |
||||
|
} |
@ -0,0 +1,100 @@ |
|||||
|
// Package cbor provides primitives for storing different data
|
||||
|
// in the CBOR (binary) format. CBOR is defined in RFC7049.
|
||||
|
package cbor |
||||
|
|
||||
|
import "time" |
||||
|
|
||||
|
const ( |
||||
|
majorOffset = 5 |
||||
|
additionalMax = 23 |
||||
|
|
||||
|
// Non Values.
|
||||
|
additionalTypeBoolFalse byte = 20 |
||||
|
additionalTypeBoolTrue byte = 21 |
||||
|
additionalTypeNull byte = 22 |
||||
|
|
||||
|
// Integer (+ve and -ve) Sub-types.
|
||||
|
additionalTypeIntUint8 byte = 24 |
||||
|
additionalTypeIntUint16 byte = 25 |
||||
|
additionalTypeIntUint32 byte = 26 |
||||
|
additionalTypeIntUint64 byte = 27 |
||||
|
|
||||
|
// Float Sub-types.
|
||||
|
additionalTypeFloat16 byte = 25 |
||||
|
additionalTypeFloat32 byte = 26 |
||||
|
additionalTypeFloat64 byte = 27 |
||||
|
additionalTypeBreak byte = 31 |
||||
|
|
||||
|
// Tag Sub-types.
|
||||
|
additionalTypeTimestamp byte = 01 |
||||
|
|
||||
|
// Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml
|
||||
|
additionalTypeTagNetworkAddr uint16 = 260 |
||||
|
additionalTypeTagNetworkPrefix uint16 = 261 |
||||
|
additionalTypeEmbeddedJSON uint16 = 262 |
||||
|
additionalTypeTagHexString uint16 = 263 |
||||
|
|
||||
|
// Unspecified number of elements.
|
||||
|
additionalTypeInfiniteCount byte = 31 |
||||
|
) |
||||
|
const ( |
||||
|
majorTypeUnsignedInt byte = iota << majorOffset // Major type 0
|
||||
|
majorTypeNegativeInt // Major type 1
|
||||
|
majorTypeByteString // Major type 2
|
||||
|
majorTypeUtf8String // Major type 3
|
||||
|
majorTypeArray // Major type 4
|
||||
|
majorTypeMap // Major type 5
|
||||
|
majorTypeTags // Major type 6
|
||||
|
majorTypeSimpleAndFloat // Major type 7
|
||||
|
) |
||||
|
|
||||
|
const ( |
||||
|
maskOutAdditionalType byte = (7 << majorOffset) |
||||
|
maskOutMajorType byte = 31 |
||||
|
) |
||||
|
|
||||
|
const ( |
||||
|
float32Nan = "\xfa\x7f\xc0\x00\x00" |
||||
|
float32PosInfinity = "\xfa\x7f\x80\x00\x00" |
||||
|
float32NegInfinity = "\xfa\xff\x80\x00\x00" |
||||
|
float64Nan = "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00" |
||||
|
float64PosInfinity = "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00" |
||||
|
float64NegInfinity = "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00" |
||||
|
) |
||||
|
|
||||
|
// IntegerTimeFieldFormat indicates the format of timestamp decoded
|
||||
|
// from an integer (time in seconds).
|
||||
|
var IntegerTimeFieldFormat = time.RFC3339 |
||||
|
|
||||
|
// NanoTimeFieldFormat indicates the format of timestamp decoded
|
||||
|
// from a float value (time in seconds and nano seconds).
|
||||
|
var NanoTimeFieldFormat = time.RFC3339Nano |
||||
|
|
||||
|
func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte { |
||||
|
byteCount := 8 |
||||
|
var minor byte |
||||
|
switch { |
||||
|
case number < 256: |
||||
|
byteCount = 1 |
||||
|
minor = additionalTypeIntUint8 |
||||
|
|
||||
|
case number < 65536: |
||||
|
byteCount = 2 |
||||
|
minor = additionalTypeIntUint16 |
||||
|
|
||||
|
case number < 4294967296: |
||||
|
byteCount = 4 |
||||
|
minor = additionalTypeIntUint32 |
||||
|
|
||||
|
default: |
||||
|
byteCount = 8 |
||||
|
minor = additionalTypeIntUint64 |
||||
|
|
||||
|
} |
||||
|
dst = append(dst, byte(major|minor)) |
||||
|
byteCount-- |
||||
|
for ; byteCount >= 0; byteCount-- { |
||||
|
dst = append(dst, byte(number>>(uint(byteCount)*8))) |
||||
|
} |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,614 @@ |
|||||
|
package cbor |
||||
|
|
||||
|
// This file contains code to decode a stream of CBOR Data into JSON.
|
||||
|
|
||||
|
import ( |
||||
|
"bufio" |
||||
|
"bytes" |
||||
|
"fmt" |
||||
|
"io" |
||||
|
"math" |
||||
|
"net" |
||||
|
"runtime" |
||||
|
"strconv" |
||||
|
"strings" |
||||
|
"time" |
||||
|
"unicode/utf8" |
||||
|
) |
||||
|
|
||||
|
var decodeTimeZone *time.Location |
||||
|
|
||||
|
const hexTable = "0123456789abcdef" |
||||
|
|
||||
|
const isFloat32 = 4 |
||||
|
const isFloat64 = 8 |
||||
|
|
||||
|
func readNBytes(src *bufio.Reader, n int) []byte { |
||||
|
ret := make([]byte, n) |
||||
|
for i := 0; i < n; i++ { |
||||
|
ch, e := src.ReadByte() |
||||
|
if e != nil { |
||||
|
panic(fmt.Errorf("Tried to Read %d Bytes.. But hit end of file", n)) |
||||
|
} |
||||
|
ret[i] = ch |
||||
|
} |
||||
|
return ret |
||||
|
} |
||||
|
|
||||
|
func readByte(src *bufio.Reader) byte { |
||||
|
b, e := src.ReadByte() |
||||
|
if e != nil { |
||||
|
panic(fmt.Errorf("Tried to Read 1 Byte.. But hit end of file")) |
||||
|
} |
||||
|
return b |
||||
|
} |
||||
|
|
||||
|
func decodeIntAdditonalType(src *bufio.Reader, minor byte) int64 { |
||||
|
val := int64(0) |
||||
|
if minor <= 23 { |
||||
|
val = int64(minor) |
||||
|
} else { |
||||
|
bytesToRead := 0 |
||||
|
switch minor { |
||||
|
case additionalTypeIntUint8: |
||||
|
bytesToRead = 1 |
||||
|
case additionalTypeIntUint16: |
||||
|
bytesToRead = 2 |
||||
|
case additionalTypeIntUint32: |
||||
|
bytesToRead = 4 |
||||
|
case additionalTypeIntUint64: |
||||
|
bytesToRead = 8 |
||||
|
default: |
||||
|
panic(fmt.Errorf("Invalid Additional Type: %d in decodeInteger (expected <28)", minor)) |
||||
|
} |
||||
|
pb := readNBytes(src, bytesToRead) |
||||
|
for i := 0; i < bytesToRead; i++ { |
||||
|
val = val * 256 |
||||
|
val += int64(pb[i]) |
||||
|
} |
||||
|
} |
||||
|
return val |
||||
|
} |
||||
|
|
||||
|
func decodeInteger(src *bufio.Reader) int64 { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeUnsignedInt && major != majorTypeNegativeInt { |
||||
|
panic(fmt.Errorf("Major type is: %d in decodeInteger!! (expected 0 or 1)", major)) |
||||
|
} |
||||
|
val := decodeIntAdditonalType(src, minor) |
||||
|
if major == 0 { |
||||
|
return val |
||||
|
} |
||||
|
return (-1 - val) |
||||
|
} |
||||
|
|
||||
|
func decodeFloat(src *bufio.Reader) (float64, int) { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeSimpleAndFloat { |
||||
|
panic(fmt.Errorf("Incorrect Major type is: %d in decodeFloat", major)) |
||||
|
} |
||||
|
|
||||
|
switch minor { |
||||
|
case additionalTypeFloat16: |
||||
|
panic(fmt.Errorf("float16 is not suppported in decodeFloat")) |
||||
|
|
||||
|
case additionalTypeFloat32: |
||||
|
pb := readNBytes(src, 4) |
||||
|
switch string(pb) { |
||||
|
case float32Nan: |
||||
|
return math.NaN(), isFloat32 |
||||
|
case float32PosInfinity: |
||||
|
return math.Inf(0), isFloat32 |
||||
|
case float32NegInfinity: |
||||
|
return math.Inf(-1), isFloat32 |
||||
|
} |
||||
|
n := uint32(0) |
||||
|
for i := 0; i < 4; i++ { |
||||
|
n = n * 256 |
||||
|
n += uint32(pb[i]) |
||||
|
} |
||||
|
val := math.Float32frombits(n) |
||||
|
return float64(val), isFloat32 |
||||
|
case additionalTypeFloat64: |
||||
|
pb := readNBytes(src, 8) |
||||
|
switch string(pb) { |
||||
|
case float64Nan: |
||||
|
return math.NaN(), isFloat64 |
||||
|
case float64PosInfinity: |
||||
|
return math.Inf(0), isFloat64 |
||||
|
case float64NegInfinity: |
||||
|
return math.Inf(-1), isFloat64 |
||||
|
} |
||||
|
n := uint64(0) |
||||
|
for i := 0; i < 8; i++ { |
||||
|
n = n * 256 |
||||
|
n += uint64(pb[i]) |
||||
|
} |
||||
|
val := math.Float64frombits(n) |
||||
|
return val, isFloat64 |
||||
|
} |
||||
|
panic(fmt.Errorf("Invalid Additional Type: %d in decodeFloat", minor)) |
||||
|
} |
||||
|
|
||||
|
func decodeStringComplex(dst []byte, s string, pos uint) []byte { |
||||
|
i := int(pos) |
||||
|
start := 0 |
||||
|
|
||||
|
for i < len(s) { |
||||
|
b := s[i] |
||||
|
if b >= utf8.RuneSelf { |
||||
|
r, size := utf8.DecodeRuneInString(s[i:]) |
||||
|
if r == utf8.RuneError && size == 1 { |
||||
|
// In case of error, first append previous simple characters to
|
||||
|
// the byte slice if any and append a replacement character code
|
||||
|
// in place of the invalid sequence.
|
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
dst = append(dst, `\ufffd`...) |
||||
|
i += size |
||||
|
start = i |
||||
|
continue |
||||
|
} |
||||
|
i += size |
||||
|
continue |
||||
|
} |
||||
|
if b >= 0x20 && b <= 0x7e && b != '\\' && b != '"' { |
||||
|
i++ |
||||
|
continue |
||||
|
} |
||||
|
// We encountered a character that needs to be encoded.
|
||||
|
// Let's append the previous simple characters to the byte slice
|
||||
|
// and switch our operation to read and encode the remainder
|
||||
|
// characters byte-by-byte.
|
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
switch b { |
||||
|
case '"', '\\': |
||||
|
dst = append(dst, '\\', b) |
||||
|
case '\b': |
||||
|
dst = append(dst, '\\', 'b') |
||||
|
case '\f': |
||||
|
dst = append(dst, '\\', 'f') |
||||
|
case '\n': |
||||
|
dst = append(dst, '\\', 'n') |
||||
|
case '\r': |
||||
|
dst = append(dst, '\\', 'r') |
||||
|
case '\t': |
||||
|
dst = append(dst, '\\', 't') |
||||
|
default: |
||||
|
dst = append(dst, '\\', 'u', '0', '0', hexTable[b>>4], hexTable[b&0xF]) |
||||
|
} |
||||
|
i++ |
||||
|
start = i |
||||
|
} |
||||
|
if start < len(s) { |
||||
|
dst = append(dst, s[start:]...) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
func decodeString(src *bufio.Reader, noQuotes bool) []byte { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeByteString { |
||||
|
panic(fmt.Errorf("Major type is: %d in decodeString", major)) |
||||
|
} |
||||
|
result := []byte{} |
||||
|
if !noQuotes { |
||||
|
result = append(result, '"') |
||||
|
} |
||||
|
length := decodeIntAdditonalType(src, minor) |
||||
|
len := int(length) |
||||
|
pbs := readNBytes(src, len) |
||||
|
result = append(result, pbs...) |
||||
|
if noQuotes { |
||||
|
return result |
||||
|
} |
||||
|
return append(result, '"') |
||||
|
} |
||||
|
|
||||
|
func decodeUTF8String(src *bufio.Reader) []byte { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeUtf8String { |
||||
|
panic(fmt.Errorf("Major type is: %d in decodeUTF8String", major)) |
||||
|
} |
||||
|
result := []byte{'"'} |
||||
|
length := decodeIntAdditonalType(src, minor) |
||||
|
len := int(length) |
||||
|
pbs := readNBytes(src, len) |
||||
|
|
||||
|
for i := 0; i < len; i++ { |
||||
|
// Check if the character needs encoding. Control characters, slashes,
|
||||
|
// and the double quote need json encoding. Bytes above the ascii
|
||||
|
// boundary needs utf8 encoding.
|
||||
|
if pbs[i] < 0x20 || pbs[i] > 0x7e || pbs[i] == '\\' || pbs[i] == '"' { |
||||
|
// We encountered a character that needs to be encoded. Switch
|
||||
|
// to complex version of the algorithm.
|
||||
|
dst := []byte{'"'} |
||||
|
dst = decodeStringComplex(dst, string(pbs), uint(i)) |
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
} |
||||
|
// The string has no need for encoding an therefore is directly
|
||||
|
// appended to the byte slice.
|
||||
|
result = append(result, pbs...) |
||||
|
return append(result, '"') |
||||
|
} |
||||
|
|
||||
|
func array2Json(src *bufio.Reader, dst io.Writer) { |
||||
|
dst.Write([]byte{'['}) |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeArray { |
||||
|
panic(fmt.Errorf("Major type is: %d in array2Json", major)) |
||||
|
} |
||||
|
len := 0 |
||||
|
unSpecifiedCount := false |
||||
|
if minor == additionalTypeInfiniteCount { |
||||
|
unSpecifiedCount = true |
||||
|
} else { |
||||
|
length := decodeIntAdditonalType(src, minor) |
||||
|
len = int(length) |
||||
|
} |
||||
|
for i := 0; unSpecifiedCount || i < len; i++ { |
||||
|
if unSpecifiedCount { |
||||
|
pb, e := src.Peek(1) |
||||
|
if e != nil { |
||||
|
panic(e) |
||||
|
} |
||||
|
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { |
||||
|
readByte(src) |
||||
|
break |
||||
|
} |
||||
|
} |
||||
|
cbor2JsonOneObject(src, dst) |
||||
|
if unSpecifiedCount { |
||||
|
pb, e := src.Peek(1) |
||||
|
if e != nil { |
||||
|
panic(e) |
||||
|
} |
||||
|
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { |
||||
|
readByte(src) |
||||
|
break |
||||
|
} |
||||
|
dst.Write([]byte{','}) |
||||
|
} else if i+1 < len { |
||||
|
dst.Write([]byte{','}) |
||||
|
} |
||||
|
} |
||||
|
dst.Write([]byte{']'}) |
||||
|
} |
||||
|
|
||||
|
func map2Json(src *bufio.Reader, dst io.Writer) { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeMap { |
||||
|
panic(fmt.Errorf("Major type is: %d in map2Json", major)) |
||||
|
} |
||||
|
len := 0 |
||||
|
unSpecifiedCount := false |
||||
|
if minor == additionalTypeInfiniteCount { |
||||
|
unSpecifiedCount = true |
||||
|
} else { |
||||
|
length := decodeIntAdditonalType(src, minor) |
||||
|
len = int(length) |
||||
|
} |
||||
|
dst.Write([]byte{'{'}) |
||||
|
for i := 0; unSpecifiedCount || i < len; i++ { |
||||
|
if unSpecifiedCount { |
||||
|
pb, e := src.Peek(1) |
||||
|
if e != nil { |
||||
|
panic(e) |
||||
|
} |
||||
|
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { |
||||
|
readByte(src) |
||||
|
break |
||||
|
} |
||||
|
} |
||||
|
cbor2JsonOneObject(src, dst) |
||||
|
if i%2 == 0 { |
||||
|
// Even position values are keys.
|
||||
|
dst.Write([]byte{':'}) |
||||
|
} else { |
||||
|
if unSpecifiedCount { |
||||
|
pb, e := src.Peek(1) |
||||
|
if e != nil { |
||||
|
panic(e) |
||||
|
} |
||||
|
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) { |
||||
|
readByte(src) |
||||
|
break |
||||
|
} |
||||
|
dst.Write([]byte{','}) |
||||
|
} else if i+1 < len { |
||||
|
dst.Write([]byte{','}) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
dst.Write([]byte{'}'}) |
||||
|
} |
||||
|
|
||||
|
func decodeTagData(src *bufio.Reader) []byte { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeTags { |
||||
|
panic(fmt.Errorf("Major type is: %d in decodeTagData", major)) |
||||
|
} |
||||
|
switch minor { |
||||
|
case additionalTypeTimestamp: |
||||
|
return decodeTimeStamp(src) |
||||
|
|
||||
|
// Tag value is larger than 256 (so uint16).
|
||||
|
case additionalTypeIntUint16: |
||||
|
val := decodeIntAdditonalType(src, minor) |
||||
|
|
||||
|
switch uint16(val) { |
||||
|
case additionalTypeEmbeddedJSON: |
||||
|
pb := readByte(src) |
||||
|
dataMajor := pb & maskOutAdditionalType |
||||
|
if dataMajor != majorTypeByteString { |
||||
|
panic(fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedJSON", dataMajor)) |
||||
|
} |
||||
|
src.UnreadByte() |
||||
|
return decodeString(src, true) |
||||
|
|
||||
|
case additionalTypeTagNetworkAddr: |
||||
|
octets := decodeString(src, true) |
||||
|
ss := []byte{'"'} |
||||
|
switch len(octets) { |
||||
|
case 6: // MAC address.
|
||||
|
ha := net.HardwareAddr(octets) |
||||
|
ss = append(append(ss, ha.String()...), '"') |
||||
|
case 4: // IPv4 address.
|
||||
|
fallthrough |
||||
|
case 16: // IPv6 address.
|
||||
|
ip := net.IP(octets) |
||||
|
ss = append(append(ss, ip.String()...), '"') |
||||
|
default: |
||||
|
panic(fmt.Errorf("Unexpected Network Address length: %d (expected 4,6,16)", len(octets))) |
||||
|
} |
||||
|
return ss |
||||
|
|
||||
|
case additionalTypeTagNetworkPrefix: |
||||
|
pb := readByte(src) |
||||
|
if pb != byte(majorTypeMap|0x1) { |
||||
|
panic(fmt.Errorf("IP Prefix is NOT of MAP of 1 elements as expected")) |
||||
|
} |
||||
|
octets := decodeString(src, true) |
||||
|
val := decodeInteger(src) |
||||
|
ip := net.IP(octets) |
||||
|
var mask net.IPMask |
||||
|
pfxLen := int(val) |
||||
|
if len(octets) == 4 { |
||||
|
mask = net.CIDRMask(pfxLen, 32) |
||||
|
} else { |
||||
|
mask = net.CIDRMask(pfxLen, 128) |
||||
|
} |
||||
|
ipPfx := net.IPNet{IP: ip, Mask: mask} |
||||
|
ss := []byte{'"'} |
||||
|
ss = append(append(ss, ipPfx.String()...), '"') |
||||
|
return ss |
||||
|
|
||||
|
case additionalTypeTagHexString: |
||||
|
octets := decodeString(src, true) |
||||
|
ss := []byte{'"'} |
||||
|
for _, v := range octets { |
||||
|
ss = append(ss, hexTable[v>>4], hexTable[v&0x0f]) |
||||
|
} |
||||
|
return append(ss, '"') |
||||
|
|
||||
|
default: |
||||
|
panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val)) |
||||
|
} |
||||
|
} |
||||
|
panic(fmt.Errorf("Unsupported Additional Type: %d in decodeTagData", minor)) |
||||
|
} |
||||
|
|
||||
|
func decodeTimeStamp(src *bufio.Reader) []byte { |
||||
|
pb := readByte(src) |
||||
|
src.UnreadByte() |
||||
|
tsMajor := pb & maskOutAdditionalType |
||||
|
if tsMajor == majorTypeUnsignedInt || tsMajor == majorTypeNegativeInt { |
||||
|
n := decodeInteger(src) |
||||
|
t := time.Unix(n, 0) |
||||
|
if decodeTimeZone != nil { |
||||
|
t = t.In(decodeTimeZone) |
||||
|
} else { |
||||
|
t = t.In(time.UTC) |
||||
|
} |
||||
|
tsb := []byte{} |
||||
|
tsb = append(tsb, '"') |
||||
|
tsb = t.AppendFormat(tsb, IntegerTimeFieldFormat) |
||||
|
tsb = append(tsb, '"') |
||||
|
return tsb |
||||
|
} else if tsMajor == majorTypeSimpleAndFloat { |
||||
|
n, _ := decodeFloat(src) |
||||
|
secs := int64(n) |
||||
|
n -= float64(secs) |
||||
|
n *= float64(1e9) |
||||
|
t := time.Unix(secs, int64(n)) |
||||
|
if decodeTimeZone != nil { |
||||
|
t = t.In(decodeTimeZone) |
||||
|
} else { |
||||
|
t = t.In(time.UTC) |
||||
|
} |
||||
|
tsb := []byte{} |
||||
|
tsb = append(tsb, '"') |
||||
|
tsb = t.AppendFormat(tsb, NanoTimeFieldFormat) |
||||
|
tsb = append(tsb, '"') |
||||
|
return tsb |
||||
|
} |
||||
|
panic(fmt.Errorf("TS format is neigther int nor float: %d", tsMajor)) |
||||
|
} |
||||
|
|
||||
|
func decodeSimpleFloat(src *bufio.Reader) []byte { |
||||
|
pb := readByte(src) |
||||
|
major := pb & maskOutAdditionalType |
||||
|
minor := pb & maskOutMajorType |
||||
|
if major != majorTypeSimpleAndFloat { |
||||
|
panic(fmt.Errorf("Major type is: %d in decodeSimpleFloat", major)) |
||||
|
} |
||||
|
switch minor { |
||||
|
case additionalTypeBoolTrue: |
||||
|
return []byte("true") |
||||
|
case additionalTypeBoolFalse: |
||||
|
return []byte("false") |
||||
|
case additionalTypeNull: |
||||
|
return []byte("null") |
||||
|
case additionalTypeFloat16: |
||||
|
fallthrough |
||||
|
case additionalTypeFloat32: |
||||
|
fallthrough |
||||
|
case additionalTypeFloat64: |
||||
|
src.UnreadByte() |
||||
|
v, bc := decodeFloat(src) |
||||
|
ba := []byte{} |
||||
|
switch { |
||||
|
case math.IsNaN(v): |
||||
|
return []byte("\"NaN\"") |
||||
|
case math.IsInf(v, 1): |
||||
|
return []byte("\"+Inf\"") |
||||
|
case math.IsInf(v, -1): |
||||
|
return []byte("\"-Inf\"") |
||||
|
} |
||||
|
if bc == isFloat32 { |
||||
|
ba = strconv.AppendFloat(ba, v, 'f', -1, 32) |
||||
|
} else if bc == isFloat64 { |
||||
|
ba = strconv.AppendFloat(ba, v, 'f', -1, 64) |
||||
|
} else { |
||||
|
panic(fmt.Errorf("Invalid Float precision from decodeFloat: %d", bc)) |
||||
|
} |
||||
|
return ba |
||||
|
default: |
||||
|
panic(fmt.Errorf("Invalid Additional Type: %d in decodeSimpleFloat", minor)) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
func cbor2JsonOneObject(src *bufio.Reader, dst io.Writer) { |
||||
|
pb, e := src.Peek(1) |
||||
|
if e != nil { |
||||
|
panic(e) |
||||
|
} |
||||
|
major := (pb[0] & maskOutAdditionalType) |
||||
|
|
||||
|
switch major { |
||||
|
case majorTypeUnsignedInt: |
||||
|
fallthrough |
||||
|
case majorTypeNegativeInt: |
||||
|
n := decodeInteger(src) |
||||
|
dst.Write([]byte(strconv.Itoa(int(n)))) |
||||
|
|
||||
|
case majorTypeByteString: |
||||
|
s := decodeString(src, false) |
||||
|
dst.Write(s) |
||||
|
|
||||
|
case majorTypeUtf8String: |
||||
|
s := decodeUTF8String(src) |
||||
|
dst.Write(s) |
||||
|
|
||||
|
case majorTypeArray: |
||||
|
array2Json(src, dst) |
||||
|
|
||||
|
case majorTypeMap: |
||||
|
map2Json(src, dst) |
||||
|
|
||||
|
case majorTypeTags: |
||||
|
s := decodeTagData(src) |
||||
|
dst.Write(s) |
||||
|
|
||||
|
case majorTypeSimpleAndFloat: |
||||
|
s := decodeSimpleFloat(src) |
||||
|
dst.Write(s) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
func moreBytesToRead(src *bufio.Reader) bool { |
||||
|
_, e := src.ReadByte() |
||||
|
if e == nil { |
||||
|
src.UnreadByte() |
||||
|
return true |
||||
|
} |
||||
|
return false |
||||
|
} |
||||
|
|
||||
|
// Cbor2JsonManyObjects decodes all the CBOR Objects read from src
|
||||
|
// reader. It keeps on decoding until reader returns EOF (error when reading).
|
||||
|
// Decoded string is written to the dst. At the end of every CBOR Object
|
||||
|
// newline is written to the output stream.
|
||||
|
//
|
||||
|
// Returns error (if any) that was encountered during decode.
|
||||
|
// The child functions will generate a panic when error is encountered and
|
||||
|
// this function will recover non-runtime Errors and return the reason as error.
|
||||
|
func Cbor2JsonManyObjects(src io.Reader, dst io.Writer) (err error) { |
||||
|
defer func() { |
||||
|
if r := recover(); r != nil { |
||||
|
if _, ok := r.(runtime.Error); ok { |
||||
|
panic(r) |
||||
|
} |
||||
|
err = r.(error) |
||||
|
} |
||||
|
}() |
||||
|
bufRdr := bufio.NewReader(src) |
||||
|
for moreBytesToRead(bufRdr) { |
||||
|
cbor2JsonOneObject(bufRdr, dst) |
||||
|
dst.Write([]byte("\n")) |
||||
|
} |
||||
|
return nil |
||||
|
} |
||||
|
|
||||
|
// Detect if the bytes to be printed is Binary or not.
|
||||
|
func binaryFmt(p []byte) bool { |
||||
|
if len(p) > 0 && p[0] > 0x7F { |
||||
|
return true |
||||
|
} |
||||
|
return false |
||||
|
} |
||||
|
|
||||
|
func getReader(str string) *bufio.Reader { |
||||
|
return bufio.NewReader(strings.NewReader(str)) |
||||
|
} |
||||
|
|
||||
|
// DecodeIfBinaryToString converts a binary formatted log msg to a
|
||||
|
// JSON formatted String Log message - suitable for printing to Console/Syslog.
|
||||
|
func DecodeIfBinaryToString(in []byte) string { |
||||
|
if binaryFmt(in) { |
||||
|
var b bytes.Buffer |
||||
|
Cbor2JsonManyObjects(strings.NewReader(string(in)), &b) |
||||
|
return b.String() |
||||
|
} |
||||
|
return string(in) |
||||
|
} |
||||
|
|
||||
|
// DecodeObjectToStr checks if the input is a binary format, if so,
|
||||
|
// it will decode a single Object and return the decoded string.
|
||||
|
func DecodeObjectToStr(in []byte) string { |
||||
|
if binaryFmt(in) { |
||||
|
var b bytes.Buffer |
||||
|
cbor2JsonOneObject(getReader(string(in)), &b) |
||||
|
return b.String() |
||||
|
} |
||||
|
return string(in) |
||||
|
} |
||||
|
|
||||
|
// DecodeIfBinaryToBytes checks if the input is a binary format, if so,
|
||||
|
// it will decode all Objects and return the decoded string as byte array.
|
||||
|
func DecodeIfBinaryToBytes(in []byte) []byte { |
||||
|
if binaryFmt(in) { |
||||
|
var b bytes.Buffer |
||||
|
Cbor2JsonManyObjects(bytes.NewReader(in), &b) |
||||
|
return b.Bytes() |
||||
|
} |
||||
|
return in |
||||
|
} |
@ -0,0 +1,68 @@ |
|||||
|
package cbor |
||||
|
|
||||
|
// AppendStrings encodes and adds an array of strings to the dst byte array.
|
||||
|
func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendString(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendString encodes and adds a string to the dst byte array.
|
||||
|
func (Encoder) AppendString(dst []byte, s string) []byte { |
||||
|
major := majorTypeUtf8String |
||||
|
|
||||
|
l := len(s) |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l)) |
||||
|
} |
||||
|
return append(dst, s...) |
||||
|
} |
||||
|
|
||||
|
// AppendBytes encodes and adds an array of bytes to the dst byte array.
|
||||
|
func (Encoder) AppendBytes(dst, s []byte) []byte { |
||||
|
major := majorTypeByteString |
||||
|
|
||||
|
l := len(s) |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
return append(dst, s...) |
||||
|
} |
||||
|
|
||||
|
// AppendEmbeddedJSON adds a tag and embeds input JSON as such.
|
||||
|
func AppendEmbeddedJSON(dst, s []byte) []byte { |
||||
|
major := majorTypeTags |
||||
|
minor := additionalTypeEmbeddedJSON |
||||
|
|
||||
|
// Append the TAG to indicate this is Embedded JSON.
|
||||
|
dst = append(dst, byte(major|additionalTypeIntUint16)) |
||||
|
dst = append(dst, byte(minor>>8)) |
||||
|
dst = append(dst, byte(minor&0xff)) |
||||
|
|
||||
|
// Append the JSON Object as Byte String.
|
||||
|
major = majorTypeByteString |
||||
|
|
||||
|
l := len(s) |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
return append(dst, s...) |
||||
|
} |
@ -0,0 +1,93 @@ |
|||||
|
package cbor |
||||
|
|
||||
|
import ( |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
func appendIntegerTimestamp(dst []byte, t time.Time) []byte { |
||||
|
major := majorTypeTags |
||||
|
minor := additionalTypeTimestamp |
||||
|
dst = append(dst, byte(major|minor)) |
||||
|
secs := t.Unix() |
||||
|
var val uint64 |
||||
|
if secs < 0 { |
||||
|
major = majorTypeNegativeInt |
||||
|
val = uint64(-secs - 1) |
||||
|
} else { |
||||
|
major = majorTypeUnsignedInt |
||||
|
val = uint64(secs) |
||||
|
} |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(val)) |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte { |
||||
|
major := majorTypeTags |
||||
|
minor := additionalTypeTimestamp |
||||
|
dst = append(dst, byte(major|minor)) |
||||
|
secs := t.Unix() |
||||
|
nanos := t.Nanosecond() |
||||
|
var val float64 |
||||
|
val = float64(secs)*1.0 + float64(nanos)*1E-9 |
||||
|
return e.AppendFloat64(dst, val) |
||||
|
} |
||||
|
|
||||
|
// AppendTime encodes and adds a timestamp to the dst byte array.
|
||||
|
func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte { |
||||
|
utc := t.UTC() |
||||
|
if utc.Nanosecond() == 0 { |
||||
|
return appendIntegerTimestamp(dst, utc) |
||||
|
} |
||||
|
return e.appendFloatTimestamp(dst, utc) |
||||
|
} |
||||
|
|
||||
|
// AppendTimes encodes and adds an array of timestamps to the dst byte array.
|
||||
|
func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
|
||||
|
for _, t := range vals { |
||||
|
dst = e.AppendTime(dst, t, unused) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendDuration encodes and adds a duration to the dst byte array.
|
||||
|
// useInt field indicates whether to store the duration as seconds (integer) or
|
||||
|
// as seconds+nanoseconds (float).
|
||||
|
func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { |
||||
|
if useInt { |
||||
|
return e.AppendInt64(dst, int64(d/unit)) |
||||
|
} |
||||
|
return e.AppendFloat64(dst, float64(d)/float64(unit)) |
||||
|
} |
||||
|
|
||||
|
// AppendDurations encodes and adds an array of durations to the dst byte array.
|
||||
|
// useInt field indicates whether to store the duration as seconds (integer) or
|
||||
|
// as seconds+nanoseconds (float).
|
||||
|
func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, d := range vals { |
||||
|
dst = e.AppendDuration(dst, d, unit, useInt) |
||||
|
} |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,478 @@ |
|||||
|
package cbor |
||||
|
|
||||
|
import ( |
||||
|
"encoding/json" |
||||
|
"fmt" |
||||
|
"math" |
||||
|
"net" |
||||
|
) |
||||
|
|
||||
|
// AppendNil inserts a 'Nil' object into the dst byte array.
|
||||
|
func (Encoder) AppendNil(dst []byte) []byte { |
||||
|
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeNull)) |
||||
|
} |
||||
|
|
||||
|
// AppendBeginMarker inserts a map start into the dst byte array.
|
||||
|
func (Encoder) AppendBeginMarker(dst []byte) []byte { |
||||
|
return append(dst, byte(majorTypeMap|additionalTypeInfiniteCount)) |
||||
|
} |
||||
|
|
||||
|
// AppendEndMarker inserts a map end into the dst byte array.
|
||||
|
func (Encoder) AppendEndMarker(dst []byte) []byte { |
||||
|
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak)) |
||||
|
} |
||||
|
|
||||
|
// AppendObjectData takes an object in form of a byte array and appends to dst.
|
||||
|
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { |
||||
|
// BeginMarker is present in the dst, which
|
||||
|
// should not be copied when appending to existing data.
|
||||
|
return append(dst, o[1:]...) |
||||
|
} |
||||
|
|
||||
|
// AppendArrayStart adds markers to indicate the start of an array.
|
||||
|
func (Encoder) AppendArrayStart(dst []byte) []byte { |
||||
|
return append(dst, byte(majorTypeArray|additionalTypeInfiniteCount)) |
||||
|
} |
||||
|
|
||||
|
// AppendArrayEnd adds markers to indicate the end of an array.
|
||||
|
func (Encoder) AppendArrayEnd(dst []byte) []byte { |
||||
|
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak)) |
||||
|
} |
||||
|
|
||||
|
// AppendArrayDelim adds markers to indicate end of a particular array element.
|
||||
|
func (Encoder) AppendArrayDelim(dst []byte) []byte { |
||||
|
//No delimiters needed in cbor
|
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendLineBreak is a noop that keep API compat with json encoder.
|
||||
|
func (Encoder) AppendLineBreak(dst []byte) []byte { |
||||
|
// No line breaks needed in binary format.
|
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendBool encodes and inserts a boolean value into the dst byte array.
|
||||
|
func (Encoder) AppendBool(dst []byte, val bool) []byte { |
||||
|
b := additionalTypeBoolFalse |
||||
|
if val { |
||||
|
b = additionalTypeBoolTrue |
||||
|
} |
||||
|
return append(dst, byte(majorTypeSimpleAndFloat|b)) |
||||
|
} |
||||
|
|
||||
|
// AppendBools encodes and inserts an array of boolean values into the dst byte array.
|
||||
|
func (e Encoder) AppendBools(dst []byte, vals []bool) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendBool(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt encodes and inserts an integer value into the dst byte array.
|
||||
|
func (Encoder) AppendInt(dst []byte, val int) []byte { |
||||
|
major := majorTypeUnsignedInt |
||||
|
contentVal := val |
||||
|
if val < 0 { |
||||
|
major = majorTypeNegativeInt |
||||
|
contentVal = -val - 1 |
||||
|
} |
||||
|
if contentVal <= additionalMax { |
||||
|
lb := byte(contentVal) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(contentVal)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInts encodes and inserts an array of integer values into the dst byte array.
|
||||
|
func (e Encoder) AppendInts(dst []byte, vals []int) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendInt(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt8 encodes and inserts an int8 value into the dst byte array.
|
||||
|
func (e Encoder) AppendInt8(dst []byte, val int8) []byte { |
||||
|
return e.AppendInt(dst, int(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendInts8 encodes and inserts an array of integer values into the dst byte array.
|
||||
|
func (e Encoder) AppendInts8(dst []byte, vals []int8) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendInt(dst, int(v)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt16 encodes and inserts a int16 value into the dst byte array.
|
||||
|
func (e Encoder) AppendInt16(dst []byte, val int16) []byte { |
||||
|
return e.AppendInt(dst, int(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendInts16 encodes and inserts an array of int16 values into the dst byte array.
|
||||
|
func (e Encoder) AppendInts16(dst []byte, vals []int16) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendInt(dst, int(v)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt32 encodes and inserts a int32 value into the dst byte array.
|
||||
|
func (e Encoder) AppendInt32(dst []byte, val int32) []byte { |
||||
|
return e.AppendInt(dst, int(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendInts32 encodes and inserts an array of int32 values into the dst byte array.
|
||||
|
func (e Encoder) AppendInts32(dst []byte, vals []int32) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendInt(dst, int(v)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt64 encodes and inserts a int64 value into the dst byte array.
|
||||
|
func (Encoder) AppendInt64(dst []byte, val int64) []byte { |
||||
|
major := majorTypeUnsignedInt |
||||
|
contentVal := val |
||||
|
if val < 0 { |
||||
|
major = majorTypeNegativeInt |
||||
|
contentVal = -val - 1 |
||||
|
} |
||||
|
if contentVal <= additionalMax { |
||||
|
lb := byte(contentVal) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(contentVal)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInts64 encodes and inserts an array of int64 values into the dst byte array.
|
||||
|
func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendInt64(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint encodes and inserts an unsigned integer value into the dst byte array.
|
||||
|
func (e Encoder) AppendUint(dst []byte, val uint) []byte { |
||||
|
return e.AppendInt64(dst, int64(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendUints encodes and inserts an array of unsigned integer values into the dst byte array.
|
||||
|
func (e Encoder) AppendUints(dst []byte, vals []uint) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendUint(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint8 encodes and inserts a unsigned int8 value into the dst byte array.
|
||||
|
func (e Encoder) AppendUint8(dst []byte, val uint8) []byte { |
||||
|
return e.AppendUint(dst, uint(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendUints8 encodes and inserts an array of uint8 values into the dst byte array.
|
||||
|
func (e Encoder) AppendUints8(dst []byte, vals []uint8) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendUint8(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint16 encodes and inserts a uint16 value into the dst byte array.
|
||||
|
func (e Encoder) AppendUint16(dst []byte, val uint16) []byte { |
||||
|
return e.AppendUint(dst, uint(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendUints16 encodes and inserts an array of uint16 values into the dst byte array.
|
||||
|
func (e Encoder) AppendUints16(dst []byte, vals []uint16) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendUint16(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint32 encodes and inserts a uint32 value into the dst byte array.
|
||||
|
func (e Encoder) AppendUint32(dst []byte, val uint32) []byte { |
||||
|
return e.AppendUint(dst, uint(val)) |
||||
|
} |
||||
|
|
||||
|
// AppendUints32 encodes and inserts an array of uint32 values into the dst byte array.
|
||||
|
func (e Encoder) AppendUints32(dst []byte, vals []uint32) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendUint32(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint64 encodes and inserts a uint64 value into the dst byte array.
|
||||
|
func (Encoder) AppendUint64(dst []byte, val uint64) []byte { |
||||
|
major := majorTypeUnsignedInt |
||||
|
contentVal := val |
||||
|
if contentVal <= additionalMax { |
||||
|
lb := byte(contentVal) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(contentVal)) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUints64 encodes and inserts an array of uint64 values into the dst byte array.
|
||||
|
func (e Encoder) AppendUints64(dst []byte, vals []uint64) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendUint64(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendFloat32 encodes and inserts a single precision float value into the dst byte array.
|
||||
|
func (Encoder) AppendFloat32(dst []byte, val float32) []byte { |
||||
|
switch { |
||||
|
case math.IsNaN(float64(val)): |
||||
|
return append(dst, "\xfa\x7f\xc0\x00\x00"...) |
||||
|
case math.IsInf(float64(val), 1): |
||||
|
return append(dst, "\xfa\x7f\x80\x00\x00"...) |
||||
|
case math.IsInf(float64(val), -1): |
||||
|
return append(dst, "\xfa\xff\x80\x00\x00"...) |
||||
|
} |
||||
|
major := majorTypeSimpleAndFloat |
||||
|
subType := additionalTypeFloat32 |
||||
|
n := math.Float32bits(val) |
||||
|
var buf [4]byte |
||||
|
for i := uint(0); i < 4; i++ { |
||||
|
buf[i] = byte(n >> ((3 - i) * 8)) |
||||
|
} |
||||
|
return append(append(dst, byte(major|subType)), buf[0], buf[1], buf[2], buf[3]) |
||||
|
} |
||||
|
|
||||
|
// AppendFloats32 encodes and inserts an array of single precision float value into the dst byte array.
|
||||
|
func (e Encoder) AppendFloats32(dst []byte, vals []float32) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendFloat32(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendFloat64 encodes and inserts a double precision float value into the dst byte array.
|
||||
|
func (Encoder) AppendFloat64(dst []byte, val float64) []byte { |
||||
|
switch { |
||||
|
case math.IsNaN(val): |
||||
|
return append(dst, "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00"...) |
||||
|
case math.IsInf(val, 1): |
||||
|
return append(dst, "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00"...) |
||||
|
case math.IsInf(val, -1): |
||||
|
return append(dst, "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00"...) |
||||
|
} |
||||
|
major := majorTypeSimpleAndFloat |
||||
|
subType := additionalTypeFloat64 |
||||
|
n := math.Float64bits(val) |
||||
|
dst = append(dst, byte(major|subType)) |
||||
|
for i := uint(1); i <= 8; i++ { |
||||
|
b := byte(n >> ((8 - i) * 8)) |
||||
|
dst = append(dst, b) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendFloats64 encodes and inserts an array of double precision float values into the dst byte array.
|
||||
|
func (e Encoder) AppendFloats64(dst []byte, vals []float64) []byte { |
||||
|
major := majorTypeArray |
||||
|
l := len(vals) |
||||
|
if l == 0 { |
||||
|
return e.AppendArrayEnd(e.AppendArrayStart(dst)) |
||||
|
} |
||||
|
if l <= additionalMax { |
||||
|
lb := byte(l) |
||||
|
dst = append(dst, byte(major|lb)) |
||||
|
} else { |
||||
|
dst = appendCborTypePrefix(dst, major, uint64(l)) |
||||
|
} |
||||
|
for _, v := range vals { |
||||
|
dst = e.AppendFloat64(dst, v) |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInterface takes an arbitrary object and converts it to JSON and embeds it dst.
|
||||
|
func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { |
||||
|
marshaled, err := json.Marshal(i) |
||||
|
if err != nil { |
||||
|
return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) |
||||
|
} |
||||
|
return AppendEmbeddedJSON(dst, marshaled) |
||||
|
} |
||||
|
|
||||
|
// AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6).
|
||||
|
func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { |
||||
|
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) |
||||
|
return e.AppendBytes(dst, ip) |
||||
|
} |
||||
|
|
||||
|
// AppendIPPrefix encodes and inserts an IP Address Prefix (Address + Mask Length).
|
||||
|
func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { |
||||
|
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkPrefix>>8)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkPrefix&0xff)) |
||||
|
|
||||
|
// Prefix is a tuple (aka MAP of 1 pair of elements) -
|
||||
|
// first element is prefix, second is mask length.
|
||||
|
dst = append(dst, byte(majorTypeMap|0x1)) |
||||
|
dst = e.AppendBytes(dst, pfx.IP) |
||||
|
maskLen, _ := pfx.Mask.Size() |
||||
|
return e.AppendUint8(dst, uint8(maskLen)) |
||||
|
} |
||||
|
|
||||
|
// AppendMACAddr encodes and inserts an Hardware (MAC) address.
|
||||
|
func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { |
||||
|
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) |
||||
|
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) |
||||
|
return e.AppendBytes(dst, ha) |
||||
|
} |
||||
|
|
||||
|
// AppendHex adds a TAG and inserts a hex bytes as a string.
|
||||
|
func (e Encoder) AppendHex(dst []byte, val []byte) []byte { |
||||
|
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16)) |
||||
|
dst = append(dst, byte(additionalTypeTagHexString>>8)) |
||||
|
dst = append(dst, byte(additionalTypeTagHexString&0xff)) |
||||
|
return e.AppendBytes(dst, val) |
||||
|
} |
@ -0,0 +1,12 @@ |
|||||
|
package json |
||||
|
|
||||
|
type Encoder struct{} |
||||
|
|
||||
|
// AppendKey appends a new key to the output JSON.
|
||||
|
func (e Encoder) AppendKey(dst []byte, key string) []byte { |
||||
|
if len(dst) > 1 && dst[len(dst)-1] != '{' { |
||||
|
dst = append(dst, ',') |
||||
|
} |
||||
|
dst = e.AppendString(dst, key) |
||||
|
return append(dst, ':') |
||||
|
} |
@ -0,0 +1,85 @@ |
|||||
|
package json |
||||
|
|
||||
|
import "unicode/utf8" |
||||
|
|
||||
|
// AppendBytes is a mirror of appendString with []byte arg
|
||||
|
func (Encoder) AppendBytes(dst, s []byte) []byte { |
||||
|
dst = append(dst, '"') |
||||
|
for i := 0; i < len(s); i++ { |
||||
|
if !noEscapeTable[s[i]] { |
||||
|
dst = appendBytesComplex(dst, s, i) |
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, s...) |
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
|
||||
|
// AppendHex encodes the input bytes to a hex string and appends
|
||||
|
// the encoded string to the input byte slice.
|
||||
|
//
|
||||
|
// The operation loops though each byte and encodes it as hex using
|
||||
|
// the hex lookup table.
|
||||
|
func (Encoder) AppendHex(dst, s []byte) []byte { |
||||
|
dst = append(dst, '"') |
||||
|
for _, v := range s { |
||||
|
dst = append(dst, hex[v>>4], hex[v&0x0f]) |
||||
|
} |
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
|
||||
|
// appendBytesComplex is a mirror of the appendStringComplex
|
||||
|
// with []byte arg
|
||||
|
func appendBytesComplex(dst, s []byte, i int) []byte { |
||||
|
start := 0 |
||||
|
for i < len(s) { |
||||
|
b := s[i] |
||||
|
if b >= utf8.RuneSelf { |
||||
|
r, size := utf8.DecodeRune(s[i:]) |
||||
|
if r == utf8.RuneError && size == 1 { |
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
dst = append(dst, `\ufffd`...) |
||||
|
i += size |
||||
|
start = i |
||||
|
continue |
||||
|
} |
||||
|
i += size |
||||
|
continue |
||||
|
} |
||||
|
if noEscapeTable[b] { |
||||
|
i++ |
||||
|
continue |
||||
|
} |
||||
|
// We encountered a character that needs to be encoded.
|
||||
|
// Let's append the previous simple characters to the byte slice
|
||||
|
// and switch our operation to read and encode the remainder
|
||||
|
// characters byte-by-byte.
|
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
switch b { |
||||
|
case '"', '\\': |
||||
|
dst = append(dst, '\\', b) |
||||
|
case '\b': |
||||
|
dst = append(dst, '\\', 'b') |
||||
|
case '\f': |
||||
|
dst = append(dst, '\\', 'f') |
||||
|
case '\n': |
||||
|
dst = append(dst, '\\', 'n') |
||||
|
case '\r': |
||||
|
dst = append(dst, '\\', 'r') |
||||
|
case '\t': |
||||
|
dst = append(dst, '\\', 't') |
||||
|
default: |
||||
|
dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) |
||||
|
} |
||||
|
i++ |
||||
|
start = i |
||||
|
} |
||||
|
if start < len(s) { |
||||
|
dst = append(dst, s[start:]...) |
||||
|
} |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,121 @@ |
|||||
|
package json |
||||
|
|
||||
|
import "unicode/utf8" |
||||
|
|
||||
|
const hex = "0123456789abcdef" |
||||
|
|
||||
|
var noEscapeTable = [256]bool{} |
||||
|
|
||||
|
func init() { |
||||
|
for i := 0; i <= 0x7e; i++ { |
||||
|
noEscapeTable[i] = i >= 0x20 && i != '\\' && i != '"' |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// AppendStrings encodes the input strings to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = e.AppendString(dst, vals[0]) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = e.AppendString(append(dst, ','), val) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendString encodes the input string to json and appends
|
||||
|
// the encoded string to the input byte slice.
|
||||
|
//
|
||||
|
// The operation loops though each byte in the string looking
|
||||
|
// for characters that need json or utf8 encoding. If the string
|
||||
|
// does not need encoding, then the string is appended in it's
|
||||
|
// entirety to the byte slice.
|
||||
|
// If we encounter a byte that does need encoding, switch up
|
||||
|
// the operation and perform a byte-by-byte read-encode-append.
|
||||
|
func (Encoder) AppendString(dst []byte, s string) []byte { |
||||
|
// Start with a double quote.
|
||||
|
dst = append(dst, '"') |
||||
|
// Loop through each character in the string.
|
||||
|
for i := 0; i < len(s); i++ { |
||||
|
// Check if the character needs encoding. Control characters, slashes,
|
||||
|
// and the double quote need json encoding. Bytes above the ascii
|
||||
|
// boundary needs utf8 encoding.
|
||||
|
if !noEscapeTable[s[i]] { |
||||
|
// We encountered a character that needs to be encoded. Switch
|
||||
|
// to complex version of the algorithm.
|
||||
|
dst = appendStringComplex(dst, s, i) |
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
} |
||||
|
// The string has no need for encoding an therefore is directly
|
||||
|
// appended to the byte slice.
|
||||
|
dst = append(dst, s...) |
||||
|
// End with a double quote
|
||||
|
return append(dst, '"') |
||||
|
} |
||||
|
|
||||
|
// appendStringComplex is used by appendString to take over an in
|
||||
|
// progress JSON string encoding that encountered a character that needs
|
||||
|
// to be encoded.
|
||||
|
func appendStringComplex(dst []byte, s string, i int) []byte { |
||||
|
start := 0 |
||||
|
for i < len(s) { |
||||
|
b := s[i] |
||||
|
if b >= utf8.RuneSelf { |
||||
|
r, size := utf8.DecodeRuneInString(s[i:]) |
||||
|
if r == utf8.RuneError && size == 1 { |
||||
|
// In case of error, first append previous simple characters to
|
||||
|
// the byte slice if any and append a remplacement character code
|
||||
|
// in place of the invalid sequence.
|
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
dst = append(dst, `\ufffd`...) |
||||
|
i += size |
||||
|
start = i |
||||
|
continue |
||||
|
} |
||||
|
i += size |
||||
|
continue |
||||
|
} |
||||
|
if noEscapeTable[b] { |
||||
|
i++ |
||||
|
continue |
||||
|
} |
||||
|
// We encountered a character that needs to be encoded.
|
||||
|
// Let's append the previous simple characters to the byte slice
|
||||
|
// and switch our operation to read and encode the remainder
|
||||
|
// characters byte-by-byte.
|
||||
|
if start < i { |
||||
|
dst = append(dst, s[start:i]...) |
||||
|
} |
||||
|
switch b { |
||||
|
case '"', '\\': |
||||
|
dst = append(dst, '\\', b) |
||||
|
case '\b': |
||||
|
dst = append(dst, '\\', 'b') |
||||
|
case '\f': |
||||
|
dst = append(dst, '\\', 'f') |
||||
|
case '\n': |
||||
|
dst = append(dst, '\\', 'n') |
||||
|
case '\r': |
||||
|
dst = append(dst, '\\', 'r') |
||||
|
case '\t': |
||||
|
dst = append(dst, '\\', 't') |
||||
|
default: |
||||
|
dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) |
||||
|
} |
||||
|
i++ |
||||
|
start = i |
||||
|
} |
||||
|
if start < len(s) { |
||||
|
dst = append(dst, s[start:]...) |
||||
|
} |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,76 @@ |
|||||
|
package json |
||||
|
|
||||
|
import ( |
||||
|
"strconv" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
// AppendTime formats the input time with the given format
|
||||
|
// and appends the encoded string to the input byte slice.
|
||||
|
func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte { |
||||
|
if format == "" { |
||||
|
return e.AppendInt64(dst, t.Unix()) |
||||
|
} |
||||
|
return append(t.AppendFormat(append(dst, '"'), format), '"') |
||||
|
} |
||||
|
|
||||
|
// AppendTimes converts the input times with the given format
|
||||
|
// and appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte { |
||||
|
if format == "" { |
||||
|
return appendUnixTimes(dst, vals) |
||||
|
} |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = append(vals[0].AppendFormat(append(dst, '"'), format), '"') |
||||
|
if len(vals) > 1 { |
||||
|
for _, t := range vals[1:] { |
||||
|
dst = append(t.AppendFormat(append(dst, ',', '"'), format), '"') |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
func appendUnixTimes(dst []byte, vals []time.Time) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, vals[0].Unix(), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, t := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendDuration formats the input duration with the given unit & format
|
||||
|
// and appends the encoded string to the input byte slice.
|
||||
|
func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte { |
||||
|
if useInt { |
||||
|
return strconv.AppendInt(dst, int64(d/unit), 10) |
||||
|
} |
||||
|
return e.AppendFloat64(dst, float64(d)/float64(unit)) |
||||
|
} |
||||
|
|
||||
|
// AppendDurations formats the input durations with the given unit & format
|
||||
|
// and appends the encoded string list to the input byte slice.
|
||||
|
func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = e.AppendDuration(dst, vals[0], unit, useInt) |
||||
|
if len(vals) > 1 { |
||||
|
for _, d := range vals[1:] { |
||||
|
dst = e.AppendDuration(append(dst, ','), d, unit, useInt) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
@ -0,0 +1,402 @@ |
|||||
|
package json |
||||
|
|
||||
|
import ( |
||||
|
"encoding/json" |
||||
|
"fmt" |
||||
|
"math" |
||||
|
"net" |
||||
|
"strconv" |
||||
|
) |
||||
|
|
||||
|
// AppendNil inserts a 'Nil' object into the dst byte array.
|
||||
|
func (Encoder) AppendNil(dst []byte) []byte { |
||||
|
return append(dst, "null"...) |
||||
|
} |
||||
|
|
||||
|
// AppendBeginMarker inserts a map start into the dst byte array.
|
||||
|
func (Encoder) AppendBeginMarker(dst []byte) []byte { |
||||
|
return append(dst, '{') |
||||
|
} |
||||
|
|
||||
|
// AppendEndMarker inserts a map end into the dst byte array.
|
||||
|
func (Encoder) AppendEndMarker(dst []byte) []byte { |
||||
|
return append(dst, '}') |
||||
|
} |
||||
|
|
||||
|
// AppendLineBreak appends a line break.
|
||||
|
func (Encoder) AppendLineBreak(dst []byte) []byte { |
||||
|
return append(dst, '\n') |
||||
|
} |
||||
|
|
||||
|
// AppendArrayStart adds markers to indicate the start of an array.
|
||||
|
func (Encoder) AppendArrayStart(dst []byte) []byte { |
||||
|
return append(dst, '[') |
||||
|
} |
||||
|
|
||||
|
// AppendArrayEnd adds markers to indicate the end of an array.
|
||||
|
func (Encoder) AppendArrayEnd(dst []byte) []byte { |
||||
|
return append(dst, ']') |
||||
|
} |
||||
|
|
||||
|
// AppendArrayDelim adds markers to indicate end of a particular array element.
|
||||
|
func (Encoder) AppendArrayDelim(dst []byte) []byte { |
||||
|
if len(dst) > 0 { |
||||
|
return append(dst, ',') |
||||
|
} |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendBool converts the input bool to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendBool(dst []byte, val bool) []byte { |
||||
|
return strconv.AppendBool(dst, val) |
||||
|
} |
||||
|
|
||||
|
// AppendBools encodes the input bools to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendBools(dst []byte, vals []bool) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendBool(dst, vals[0]) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendBool(append(dst, ','), val) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt converts the input int to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendInt(dst []byte, val int) []byte { |
||||
|
return strconv.AppendInt(dst, int64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendInts encodes the input ints to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendInts(dst []byte, vals []int) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, int64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), int64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt8 converts the input []int8 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendInt8(dst []byte, val int8) []byte { |
||||
|
return strconv.AppendInt(dst, int64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendInts8 encodes the input int8s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendInts8(dst []byte, vals []int8) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, int64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), int64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt16 converts the input int16 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendInt16(dst []byte, val int16) []byte { |
||||
|
return strconv.AppendInt(dst, int64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendInts16 encodes the input int16s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendInts16(dst []byte, vals []int16) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, int64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), int64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt32 converts the input int32 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendInt32(dst []byte, val int32) []byte { |
||||
|
return strconv.AppendInt(dst, int64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendInts32 encodes the input int32s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendInts32(dst []byte, vals []int32) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, int64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), int64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInt64 converts the input int64 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendInt64(dst []byte, val int64) []byte { |
||||
|
return strconv.AppendInt(dst, val, 10) |
||||
|
} |
||||
|
|
||||
|
// AppendInts64 encodes the input int64s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendInts64(dst []byte, vals []int64) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendInt(dst, vals[0], 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendInt(append(dst, ','), val, 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint converts the input uint to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendUint(dst []byte, val uint) []byte { |
||||
|
return strconv.AppendUint(dst, uint64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendUints encodes the input uints to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendUints(dst []byte, vals []uint) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendUint(dst, uint64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint8 converts the input uint8 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendUint8(dst []byte, val uint8) []byte { |
||||
|
return strconv.AppendUint(dst, uint64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendUints8 encodes the input uint8s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendUints8(dst []byte, vals []uint8) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendUint(dst, uint64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint16 converts the input uint16 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendUint16(dst []byte, val uint16) []byte { |
||||
|
return strconv.AppendUint(dst, uint64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendUints16 encodes the input uint16s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendUints16(dst []byte, vals []uint16) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendUint(dst, uint64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint32 converts the input uint32 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendUint32(dst []byte, val uint32) []byte { |
||||
|
return strconv.AppendUint(dst, uint64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendUints32 encodes the input uint32s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendUints32(dst []byte, vals []uint32) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendUint(dst, uint64(vals[0]), 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendUint64 converts the input uint64 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendUint64(dst []byte, val uint64) []byte { |
||||
|
return strconv.AppendUint(dst, uint64(val), 10) |
||||
|
} |
||||
|
|
||||
|
// AppendUints64 encodes the input uint64s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendUints64(dst []byte, vals []uint64) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = strconv.AppendUint(dst, vals[0], 10) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = strconv.AppendUint(append(dst, ','), val, 10) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
func appendFloat(dst []byte, val float64, bitSize int) []byte { |
||||
|
// JSON does not permit NaN or Infinity. A typical JSON encoder would fail
|
||||
|
// with an error, but a logging library wants the data to get thru so we
|
||||
|
// make a tradeoff and store those types as string.
|
||||
|
switch { |
||||
|
case math.IsNaN(val): |
||||
|
return append(dst, `"NaN"`...) |
||||
|
case math.IsInf(val, 1): |
||||
|
return append(dst, `"+Inf"`...) |
||||
|
case math.IsInf(val, -1): |
||||
|
return append(dst, `"-Inf"`...) |
||||
|
} |
||||
|
return strconv.AppendFloat(dst, val, 'f', -1, bitSize) |
||||
|
} |
||||
|
|
||||
|
// AppendFloat32 converts the input float32 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendFloat32(dst []byte, val float32) []byte { |
||||
|
return appendFloat(dst, float64(val), 32) |
||||
|
} |
||||
|
|
||||
|
// AppendFloats32 encodes the input float32s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendFloats32(dst []byte, vals []float32) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = appendFloat(dst, float64(vals[0]), 32) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = appendFloat(append(dst, ','), float64(val), 32) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendFloat64 converts the input float64 to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (Encoder) AppendFloat64(dst []byte, val float64) []byte { |
||||
|
return appendFloat(dst, val, 64) |
||||
|
} |
||||
|
|
||||
|
// AppendFloats64 encodes the input float64s to json and
|
||||
|
// appends the encoded string list to the input byte slice.
|
||||
|
func (Encoder) AppendFloats64(dst []byte, vals []float64) []byte { |
||||
|
if len(vals) == 0 { |
||||
|
return append(dst, '[', ']') |
||||
|
} |
||||
|
dst = append(dst, '[') |
||||
|
dst = appendFloat(dst, vals[0], 32) |
||||
|
if len(vals) > 1 { |
||||
|
for _, val := range vals[1:] { |
||||
|
dst = appendFloat(append(dst, ','), val, 64) |
||||
|
} |
||||
|
} |
||||
|
dst = append(dst, ']') |
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// AppendInterface marshals the input interface to a string and
|
||||
|
// appends the encoded string to the input byte slice.
|
||||
|
func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { |
||||
|
marshaled, err := json.Marshal(i) |
||||
|
if err != nil { |
||||
|
return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) |
||||
|
} |
||||
|
return append(dst, marshaled...) |
||||
|
} |
||||
|
|
||||
|
// AppendObjectData takes in an object that is already in a byte array
|
||||
|
// and adds it to the dst.
|
||||
|
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { |
||||
|
// Two conditions we want to put a ',' between existing content and
|
||||
|
// new content:
|
||||
|
// 1. new content starts with '{' - which shd be dropped OR
|
||||
|
// 2. existing content has already other fields
|
||||
|
if o[0] == '{' { |
||||
|
o[0] = ',' |
||||
|
} else if len(dst) > 1 { |
||||
|
dst = append(dst, ',') |
||||
|
} |
||||
|
return append(dst, o...) |
||||
|
} |
||||
|
|
||||
|
// AppendIPAddr adds IPv4 or IPv6 address to dst.
|
||||
|
func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { |
||||
|
return e.AppendString(dst, ip.String()) |
||||
|
} |
||||
|
|
||||
|
// AppendIPPrefix adds IPv4 or IPv6 Prefix (address & mask) to dst.
|
||||
|
func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { |
||||
|
return e.AppendString(dst, pfx.String()) |
||||
|
|
||||
|
} |
||||
|
|
||||
|
// AppendMACAddr adds MAC address to dst.
|
||||
|
func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { |
||||
|
return e.AppendString(dst, ha.String()) |
||||
|
} |
@ -0,0 +1,400 @@ |
|||||
|
// Package zerolog provides a lightweight logging library dedicated to JSON logging.
|
||||
|
//
|
||||
|
// A global Logger can be use for simple logging:
|
||||
|
//
|
||||
|
// import "github.com/rs/zerolog/log"
|
||||
|
//
|
||||
|
// log.Info().Msg("hello world")
|
||||
|
// // Output: {"time":1494567715,"level":"info","message":"hello world"}
|
||||
|
//
|
||||
|
// NOTE: To import the global logger, import the "log" subpackage "github.com/rs/zerolog/log".
|
||||
|
//
|
||||
|
// Fields can be added to log messages:
|
||||
|
//
|
||||
|
// log.Info().Str("foo", "bar").Msg("hello world")
|
||||
|
// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"}
|
||||
|
//
|
||||
|
// Create logger instance to manage different outputs:
|
||||
|
//
|
||||
|
// logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
|
||||
|
// logger.Info().
|
||||
|
// Str("foo", "bar").
|
||||
|
// Msg("hello world")
|
||||
|
// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"}
|
||||
|
//
|
||||
|
// Sub-loggers let you chain loggers with additional context:
|
||||
|
//
|
||||
|
// sublogger := log.With().Str("component": "foo").Logger()
|
||||
|
// sublogger.Info().Msg("hello world")
|
||||
|
// // Output: {"time":1494567715,"level":"info","message":"hello world","component":"foo"}
|
||||
|
//
|
||||
|
// Level logging
|
||||
|
//
|
||||
|
// zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
|
//
|
||||
|
// log.Debug().Msg("filtered out message")
|
||||
|
// log.Info().Msg("routed message")
|
||||
|
//
|
||||
|
// if e := log.Debug(); e.Enabled() {
|
||||
|
// // Compute log output only if enabled.
|
||||
|
// value := compute()
|
||||
|
// e.Str("foo": value).Msg("some debug message")
|
||||
|
// }
|
||||
|
// // Output: {"level":"info","time":1494567715,"routed message"}
|
||||
|
//
|
||||
|
// Customize automatic field names:
|
||||
|
//
|
||||
|
// log.TimestampFieldName = "t"
|
||||
|
// log.LevelFieldName = "p"
|
||||
|
// log.MessageFieldName = "m"
|
||||
|
//
|
||||
|
// log.Info().Msg("hello world")
|
||||
|
// // Output: {"t":1494567715,"p":"info","m":"hello world"}
|
||||
|
//
|
||||
|
// Log with no level and message:
|
||||
|
//
|
||||
|
// log.Log().Str("foo","bar").Msg("")
|
||||
|
// // Output: {"time":1494567715,"foo":"bar"}
|
||||
|
//
|
||||
|
// Add contextual fields to global Logger:
|
||||
|
//
|
||||
|
// log.Logger = log.With().Str("foo", "bar").Logger()
|
||||
|
//
|
||||
|
// Sample logs:
|
||||
|
//
|
||||
|
// sampled := log.Sample(&zerolog.BasicSampler{N: 10})
|
||||
|
// sampled.Info().Msg("will be logged every 10 messages")
|
||||
|
//
|
||||
|
// Log with contextual hooks:
|
||||
|
//
|
||||
|
// // Create the hook:
|
||||
|
// type SeverityHook struct{}
|
||||
|
//
|
||||
|
// func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
|
||||
|
// if level != zerolog.NoLevel {
|
||||
|
// e.Str("severity", level.String())
|
||||
|
// }
|
||||
|
// }
|
||||
|
//
|
||||
|
// // And use it:
|
||||
|
// var h SeverityHook
|
||||
|
// log := zerolog.New(os.Stdout).Hook(h)
|
||||
|
// log.Warn().Msg("")
|
||||
|
// // Output: {"level":"warn","severity":"warn"}
|
||||
|
//
|
||||
|
//
|
||||
|
// Caveats
|
||||
|
//
|
||||
|
// There is no fields deduplication out-of-the-box.
|
||||
|
// Using the same key multiple times creates new key in final JSON each time.
|
||||
|
//
|
||||
|
// logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
|
||||
|
// logger.Info().
|
||||
|
// Timestamp().
|
||||
|
// Msg("dup")
|
||||
|
// // Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"}
|
||||
|
//
|
||||
|
// However, it’s not a big deal though as JSON accepts dup keys,
|
||||
|
// the last one prevails.
|
||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"fmt" |
||||
|
"io" |
||||
|
"io/ioutil" |
||||
|
"os" |
||||
|
"strconv" |
||||
|
) |
||||
|
|
||||
|
// Level defines log levels.
|
||||
|
type Level uint8 |
||||
|
|
||||
|
const ( |
||||
|
// DebugLevel defines debug log level.
|
||||
|
DebugLevel Level = iota |
||||
|
// InfoLevel defines info log level.
|
||||
|
InfoLevel |
||||
|
// WarnLevel defines warn log level.
|
||||
|
WarnLevel |
||||
|
// ErrorLevel defines error log level.
|
||||
|
ErrorLevel |
||||
|
// FatalLevel defines fatal log level.
|
||||
|
FatalLevel |
||||
|
// PanicLevel defines panic log level.
|
||||
|
PanicLevel |
||||
|
// NoLevel defines an absent log level.
|
||||
|
NoLevel |
||||
|
// Disabled disables the logger.
|
||||
|
Disabled |
||||
|
) |
||||
|
|
||||
|
func (l Level) String() string { |
||||
|
switch l { |
||||
|
case DebugLevel: |
||||
|
return "debug" |
||||
|
case InfoLevel: |
||||
|
return "info" |
||||
|
case WarnLevel: |
||||
|
return "warn" |
||||
|
case ErrorLevel: |
||||
|
return "error" |
||||
|
case FatalLevel: |
||||
|
return "fatal" |
||||
|
case PanicLevel: |
||||
|
return "panic" |
||||
|
case NoLevel: |
||||
|
return "" |
||||
|
} |
||||
|
return "" |
||||
|
} |
||||
|
|
||||
|
// ParseLevel converts a level string into a zerolog Level value.
|
||||
|
// returns an error if the input string does not match known values.
|
||||
|
func ParseLevel(levelStr string) (Level, error) { |
||||
|
switch levelStr { |
||||
|
case DebugLevel.String(): |
||||
|
return DebugLevel, nil |
||||
|
case InfoLevel.String(): |
||||
|
return InfoLevel, nil |
||||
|
case WarnLevel.String(): |
||||
|
return WarnLevel, nil |
||||
|
case ErrorLevel.String(): |
||||
|
return ErrorLevel, nil |
||||
|
case FatalLevel.String(): |
||||
|
return FatalLevel, nil |
||||
|
case PanicLevel.String(): |
||||
|
return PanicLevel, nil |
||||
|
case NoLevel.String(): |
||||
|
return NoLevel, nil |
||||
|
} |
||||
|
return NoLevel, fmt.Errorf("Unknown Level String: '%s', defaulting to NoLevel", levelStr) |
||||
|
} |
||||
|
|
||||
|
// A Logger represents an active logging object that generates lines
|
||||
|
// of JSON output to an io.Writer. Each logging operation makes a single
|
||||
|
// call to the Writer's Write method. There is no guaranty on access
|
||||
|
// serialization to the Writer. If your Writer is not thread safe,
|
||||
|
// you may consider a sync wrapper.
|
||||
|
type Logger struct { |
||||
|
w LevelWriter |
||||
|
level Level |
||||
|
sampler Sampler |
||||
|
context []byte |
||||
|
hooks []Hook |
||||
|
} |
||||
|
|
||||
|
// New creates a root logger with given output writer. If the output writer implements
|
||||
|
// the LevelWriter interface, the WriteLevel method will be called instead of the Write
|
||||
|
// one.
|
||||
|
//
|
||||
|
// Each logging operation makes a single call to the Writer's Write method. There is no
|
||||
|
// guaranty on access serialization to the Writer. If your Writer is not thread safe,
|
||||
|
// you may consider using sync wrapper.
|
||||
|
func New(w io.Writer) Logger { |
||||
|
if w == nil { |
||||
|
w = ioutil.Discard |
||||
|
} |
||||
|
lw, ok := w.(LevelWriter) |
||||
|
if !ok { |
||||
|
lw = levelWriterAdapter{w} |
||||
|
} |
||||
|
return Logger{w: lw} |
||||
|
} |
||||
|
|
||||
|
// Nop returns a disabled logger for which all operation are no-op.
|
||||
|
func Nop() Logger { |
||||
|
return New(nil).Level(Disabled) |
||||
|
} |
||||
|
|
||||
|
// Output duplicates the current logger and sets w as its output.
|
||||
|
func (l Logger) Output(w io.Writer) Logger { |
||||
|
l2 := New(w) |
||||
|
l2.level = l.level |
||||
|
l2.sampler = l.sampler |
||||
|
if len(l.hooks) > 0 { |
||||
|
l2.hooks = append(l2.hooks, l.hooks...) |
||||
|
} |
||||
|
if l.context != nil { |
||||
|
l2.context = make([]byte, len(l.context), cap(l.context)) |
||||
|
copy(l2.context, l.context) |
||||
|
} |
||||
|
return l2 |
||||
|
} |
||||
|
|
||||
|
// With creates a child logger with the field added to its context.
|
||||
|
func (l Logger) With() Context { |
||||
|
context := l.context |
||||
|
l.context = make([]byte, 0, 500) |
||||
|
if context != nil { |
||||
|
l.context = append(l.context, context...) |
||||
|
} |
||||
|
return Context{l} |
||||
|
} |
||||
|
|
||||
|
// UpdateContext updates the internal logger's context.
|
||||
|
//
|
||||
|
// Use this method with caution. If unsure, prefer the With method.
|
||||
|
func (l *Logger) UpdateContext(update func(c Context) Context) { |
||||
|
if l == disabledLogger { |
||||
|
return |
||||
|
} |
||||
|
if cap(l.context) == 0 { |
||||
|
l.context = make([]byte, 0, 500) |
||||
|
} |
||||
|
c := update(Context{*l}) |
||||
|
l.context = c.l.context |
||||
|
} |
||||
|
|
||||
|
// Level creates a child logger with the minimum accepted level set to level.
|
||||
|
func (l Logger) Level(lvl Level) Logger { |
||||
|
l.level = lvl |
||||
|
return l |
||||
|
} |
||||
|
|
||||
|
// Sample returns a logger with the s sampler.
|
||||
|
func (l Logger) Sample(s Sampler) Logger { |
||||
|
l.sampler = s |
||||
|
return l |
||||
|
} |
||||
|
|
||||
|
// Hook returns a logger with the h Hook.
|
||||
|
func (l Logger) Hook(h Hook) Logger { |
||||
|
l.hooks = append(l.hooks, h) |
||||
|
return l |
||||
|
} |
||||
|
|
||||
|
// Debug starts a new message with debug level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Debug() *Event { |
||||
|
return l.newEvent(DebugLevel, nil) |
||||
|
} |
||||
|
|
||||
|
// Info starts a new message with info level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Info() *Event { |
||||
|
return l.newEvent(InfoLevel, nil) |
||||
|
} |
||||
|
|
||||
|
// Warn starts a new message with warn level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Warn() *Event { |
||||
|
return l.newEvent(WarnLevel, nil) |
||||
|
} |
||||
|
|
||||
|
// Error starts a new message with error level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Error() *Event { |
||||
|
return l.newEvent(ErrorLevel, nil) |
||||
|
} |
||||
|
|
||||
|
// Fatal starts a new message with fatal level. The os.Exit(1) function
|
||||
|
// is called by the Msg method, which terminates the program immediately.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Fatal() *Event { |
||||
|
return l.newEvent(FatalLevel, func(msg string) { os.Exit(1) }) |
||||
|
} |
||||
|
|
||||
|
// Panic starts a new message with panic level. The panic() function
|
||||
|
// is called by the Msg method, which stops the ordinary flow of a goroutine.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Panic() *Event { |
||||
|
return l.newEvent(PanicLevel, func(msg string) { panic(msg) }) |
||||
|
} |
||||
|
|
||||
|
// WithLevel starts a new message with level. Unlike Fatal and Panic
|
||||
|
// methods, WithLevel does not terminate the program or stop the ordinary
|
||||
|
// flow of a gourotine when used with their respective levels.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) WithLevel(level Level) *Event { |
||||
|
switch level { |
||||
|
case DebugLevel: |
||||
|
return l.Debug() |
||||
|
case InfoLevel: |
||||
|
return l.Info() |
||||
|
case WarnLevel: |
||||
|
return l.Warn() |
||||
|
case ErrorLevel: |
||||
|
return l.Error() |
||||
|
case FatalLevel: |
||||
|
return l.newEvent(FatalLevel, nil) |
||||
|
case PanicLevel: |
||||
|
return l.newEvent(PanicLevel, nil) |
||||
|
case NoLevel: |
||||
|
return l.Log() |
||||
|
case Disabled: |
||||
|
return nil |
||||
|
default: |
||||
|
panic("zerolog: WithLevel(): invalid level: " + strconv.Itoa(int(level))) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Log starts a new message with no level. Setting GlobalLevel to Disabled
|
||||
|
// will still disable events produced by this method.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func (l *Logger) Log() *Event { |
||||
|
return l.newEvent(NoLevel, nil) |
||||
|
} |
||||
|
|
||||
|
// Print sends a log event using debug level and no extra field.
|
||||
|
// Arguments are handled in the manner of fmt.Print.
|
||||
|
func (l *Logger) Print(v ...interface{}) { |
||||
|
if e := l.Debug(); e.Enabled() { |
||||
|
e.Msg(fmt.Sprint(v...)) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Printf sends a log event using debug level and no extra field.
|
||||
|
// Arguments are handled in the manner of fmt.Printf.
|
||||
|
func (l *Logger) Printf(format string, v ...interface{}) { |
||||
|
if e := l.Debug(); e.Enabled() { |
||||
|
e.Msg(fmt.Sprintf(format, v...)) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Write implements the io.Writer interface. This is useful to set as a writer
|
||||
|
// for the standard library log.
|
||||
|
func (l Logger) Write(p []byte) (n int, err error) { |
||||
|
n = len(p) |
||||
|
if n > 0 && p[n-1] == '\n' { |
||||
|
// Trim CR added by stdlog.
|
||||
|
p = p[0 : n-1] |
||||
|
} |
||||
|
l.Log().Msg(string(p)) |
||||
|
return |
||||
|
} |
||||
|
|
||||
|
func (l *Logger) newEvent(level Level, done func(string)) *Event { |
||||
|
enabled := l.should(level) |
||||
|
if !enabled { |
||||
|
return nil |
||||
|
} |
||||
|
e := newEvent(l.w, level) |
||||
|
e.done = done |
||||
|
e.ch = l.hooks |
||||
|
if level != NoLevel { |
||||
|
e.Str(LevelFieldName, level.String()) |
||||
|
} |
||||
|
if l.context != nil && len(l.context) > 0 { |
||||
|
e.buf = enc.AppendObjectData(e.buf, l.context) |
||||
|
} |
||||
|
return e |
||||
|
} |
||||
|
|
||||
|
// should returns true if the log event should be logged.
|
||||
|
func (l *Logger) should(lvl Level) bool { |
||||
|
if lvl < l.level || lvl < GlobalLevel() { |
||||
|
return false |
||||
|
} |
||||
|
if l.sampler != nil && !samplingDisabled() { |
||||
|
return l.sampler.Sample(lvl) |
||||
|
} |
||||
|
return true |
||||
|
} |
@ -0,0 +1,115 @@ |
|||||
|
// Package log provides a global logger for zerolog.
|
||||
|
package log |
||||
|
|
||||
|
import ( |
||||
|
"context" |
||||
|
"io" |
||||
|
"os" |
||||
|
|
||||
|
"github.com/rs/zerolog" |
||||
|
) |
||||
|
|
||||
|
// Logger is the global logger.
|
||||
|
var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger() |
||||
|
|
||||
|
// Output duplicates the global logger and sets w as its output.
|
||||
|
func Output(w io.Writer) zerolog.Logger { |
||||
|
return Logger.Output(w) |
||||
|
} |
||||
|
|
||||
|
// With creates a child logger with the field added to its context.
|
||||
|
func With() zerolog.Context { |
||||
|
return Logger.With() |
||||
|
} |
||||
|
|
||||
|
// Level creates a child logger with the minimum accepted level set to level.
|
||||
|
func Level(level zerolog.Level) zerolog.Logger { |
||||
|
return Logger.Level(level) |
||||
|
} |
||||
|
|
||||
|
// Sample returns a logger with the s sampler.
|
||||
|
func Sample(s zerolog.Sampler) zerolog.Logger { |
||||
|
return Logger.Sample(s) |
||||
|
} |
||||
|
|
||||
|
// Hook returns a logger with the h Hook.
|
||||
|
func Hook(h zerolog.Hook) zerolog.Logger { |
||||
|
return Logger.Hook(h) |
||||
|
} |
||||
|
|
||||
|
// Debug starts a new message with debug level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Debug() *zerolog.Event { |
||||
|
return Logger.Debug() |
||||
|
} |
||||
|
|
||||
|
// Info starts a new message with info level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Info() *zerolog.Event { |
||||
|
return Logger.Info() |
||||
|
} |
||||
|
|
||||
|
// Warn starts a new message with warn level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Warn() *zerolog.Event { |
||||
|
return Logger.Warn() |
||||
|
} |
||||
|
|
||||
|
// Error starts a new message with error level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Error() *zerolog.Event { |
||||
|
return Logger.Error() |
||||
|
} |
||||
|
|
||||
|
// Fatal starts a new message with fatal level. The os.Exit(1) function
|
||||
|
// is called by the Msg method.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Fatal() *zerolog.Event { |
||||
|
return Logger.Fatal() |
||||
|
} |
||||
|
|
||||
|
// Panic starts a new message with panic level. The message is also sent
|
||||
|
// to the panic function.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Panic() *zerolog.Event { |
||||
|
return Logger.Panic() |
||||
|
} |
||||
|
|
||||
|
// WithLevel starts a new message with level.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func WithLevel(level zerolog.Level) *zerolog.Event { |
||||
|
return Logger.WithLevel(level) |
||||
|
} |
||||
|
|
||||
|
// Log starts a new message with no level. Setting zerolog.GlobalLevel to
|
||||
|
// zerolog.Disabled will still disable events produced by this method.
|
||||
|
//
|
||||
|
// You must call Msg on the returned event in order to send the event.
|
||||
|
func Log() *zerolog.Event { |
||||
|
return Logger.Log() |
||||
|
} |
||||
|
|
||||
|
// Print sends a log event using debug level and no extra field.
|
||||
|
// Arguments are handled in the manner of fmt.Print.
|
||||
|
func Print(v ...interface{}) { |
||||
|
Logger.Print(v...) |
||||
|
} |
||||
|
|
||||
|
// Printf sends a log event using debug level and no extra field.
|
||||
|
// Arguments are handled in the manner of fmt.Printf.
|
||||
|
func Printf(format string, v ...interface{}) { |
||||
|
Logger.Printf(format, v...) |
||||
|
} |
||||
|
|
||||
|
// Ctx returns the Logger associated with the ctx. If no logger
|
||||
|
// is associated, a disabled logger is returned.
|
||||
|
func Ctx(ctx context.Context) *zerolog.Logger { |
||||
|
return zerolog.Ctx(ctx) |
||||
|
} |
After Width: | Height: | Size: 377 KiB |
@ -0,0 +1,126 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"math/rand" |
||||
|
"sync/atomic" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
var ( |
||||
|
// Often samples log every ~ 10 events.
|
||||
|
Often = RandomSampler(10) |
||||
|
// Sometimes samples log every ~ 100 events.
|
||||
|
Sometimes = RandomSampler(100) |
||||
|
// Rarely samples log every ~ 1000 events.
|
||||
|
Rarely = RandomSampler(1000) |
||||
|
) |
||||
|
|
||||
|
// Sampler defines an interface to a log sampler.
|
||||
|
type Sampler interface { |
||||
|
// Sample returns true if the event should be part of the sample, false if
|
||||
|
// the event should be dropped.
|
||||
|
Sample(lvl Level) bool |
||||
|
} |
||||
|
|
||||
|
// RandomSampler use a PRNG to randomly sample an event out of N events,
|
||||
|
// regardless of their level.
|
||||
|
type RandomSampler uint32 |
||||
|
|
||||
|
// Sample implements the Sampler interface.
|
||||
|
func (s RandomSampler) Sample(lvl Level) bool { |
||||
|
if s <= 0 { |
||||
|
return false |
||||
|
} |
||||
|
if rand.Intn(int(s)) != 0 { |
||||
|
return false |
||||
|
} |
||||
|
return true |
||||
|
} |
||||
|
|
||||
|
// BasicSampler is a sampler that will send every Nth events, regardless of
|
||||
|
// there level.
|
||||
|
type BasicSampler struct { |
||||
|
N uint32 |
||||
|
counter uint32 |
||||
|
} |
||||
|
|
||||
|
// Sample implements the Sampler interface.
|
||||
|
func (s *BasicSampler) Sample(lvl Level) bool { |
||||
|
c := atomic.AddUint32(&s.counter, 1) |
||||
|
return c%s.N == s.N-1 |
||||
|
} |
||||
|
|
||||
|
// BurstSampler lets Burst events pass per Period then pass the decision to
|
||||
|
// NextSampler. If Sampler is not set, all subsequent events are rejected.
|
||||
|
type BurstSampler struct { |
||||
|
// Burst is the maximum number of event per period allowed before calling
|
||||
|
// NextSampler.
|
||||
|
Burst uint32 |
||||
|
// Period defines the burst period. If 0, NextSampler is always called.
|
||||
|
Period time.Duration |
||||
|
// NextSampler is the sampler used after the burst is reached. If nil,
|
||||
|
// events are always rejected after the burst.
|
||||
|
NextSampler Sampler |
||||
|
|
||||
|
counter uint32 |
||||
|
resetAt int64 |
||||
|
} |
||||
|
|
||||
|
// Sample implements the Sampler interface.
|
||||
|
func (s *BurstSampler) Sample(lvl Level) bool { |
||||
|
if s.Burst > 0 && s.Period > 0 { |
||||
|
if s.inc() <= s.Burst { |
||||
|
return true |
||||
|
} |
||||
|
} |
||||
|
if s.NextSampler == nil { |
||||
|
return false |
||||
|
} |
||||
|
return s.NextSampler.Sample(lvl) |
||||
|
} |
||||
|
|
||||
|
func (s *BurstSampler) inc() uint32 { |
||||
|
now := time.Now().UnixNano() |
||||
|
resetAt := atomic.LoadInt64(&s.resetAt) |
||||
|
var c uint32 |
||||
|
if now > resetAt { |
||||
|
c = 1 |
||||
|
atomic.StoreUint32(&s.counter, c) |
||||
|
newResetAt := now + s.Period.Nanoseconds() |
||||
|
reset := atomic.CompareAndSwapInt64(&s.resetAt, resetAt, newResetAt) |
||||
|
if !reset { |
||||
|
// Lost the race with another goroutine trying to reset.
|
||||
|
c = atomic.AddUint32(&s.counter, 1) |
||||
|
} |
||||
|
} else { |
||||
|
c = atomic.AddUint32(&s.counter, 1) |
||||
|
} |
||||
|
return c |
||||
|
} |
||||
|
|
||||
|
// LevelSampler applies a different sampler for each level.
|
||||
|
type LevelSampler struct { |
||||
|
DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler |
||||
|
} |
||||
|
|
||||
|
func (s LevelSampler) Sample(lvl Level) bool { |
||||
|
switch lvl { |
||||
|
case DebugLevel: |
||||
|
if s.DebugSampler != nil { |
||||
|
return s.DebugSampler.Sample(lvl) |
||||
|
} |
||||
|
case InfoLevel: |
||||
|
if s.InfoSampler != nil { |
||||
|
return s.InfoSampler.Sample(lvl) |
||||
|
} |
||||
|
case WarnLevel: |
||||
|
if s.WarnSampler != nil { |
||||
|
return s.WarnSampler.Sample(lvl) |
||||
|
} |
||||
|
case ErrorLevel: |
||||
|
if s.ErrorSampler != nil { |
||||
|
return s.ErrorSampler.Sample(lvl) |
||||
|
} |
||||
|
} |
||||
|
return true |
||||
|
} |
@ -0,0 +1,57 @@ |
|||||
|
// +build !windows
|
||||
|
// +build !binary_log
|
||||
|
|
||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"io" |
||||
|
) |
||||
|
|
||||
|
// SyslogWriter is an interface matching a syslog.Writer struct.
|
||||
|
type SyslogWriter interface { |
||||
|
io.Writer |
||||
|
Debug(m string) error |
||||
|
Info(m string) error |
||||
|
Warning(m string) error |
||||
|
Err(m string) error |
||||
|
Emerg(m string) error |
||||
|
Crit(m string) error |
||||
|
} |
||||
|
|
||||
|
type syslogWriter struct { |
||||
|
w SyslogWriter |
||||
|
} |
||||
|
|
||||
|
// SyslogLevelWriter wraps a SyslogWriter and call the right syslog level
|
||||
|
// method matching the zerolog level.
|
||||
|
func SyslogLevelWriter(w SyslogWriter) LevelWriter { |
||||
|
return syslogWriter{w} |
||||
|
} |
||||
|
|
||||
|
func (sw syslogWriter) Write(p []byte) (n int, err error) { |
||||
|
return sw.w.Write(p) |
||||
|
} |
||||
|
|
||||
|
// WriteLevel implements LevelWriter interface.
|
||||
|
func (sw syslogWriter) WriteLevel(level Level, p []byte) (n int, err error) { |
||||
|
switch level { |
||||
|
case DebugLevel: |
||||
|
err = sw.w.Debug(string(p)) |
||||
|
case InfoLevel: |
||||
|
err = sw.w.Info(string(p)) |
||||
|
case WarnLevel: |
||||
|
err = sw.w.Warning(string(p)) |
||||
|
case ErrorLevel: |
||||
|
err = sw.w.Err(string(p)) |
||||
|
case FatalLevel: |
||||
|
err = sw.w.Emerg(string(p)) |
||||
|
case PanicLevel: |
||||
|
err = sw.w.Crit(string(p)) |
||||
|
case NoLevel: |
||||
|
err = sw.w.Info(string(p)) |
||||
|
default: |
||||
|
panic("invalid level") |
||||
|
} |
||||
|
n = len(p) |
||||
|
return |
||||
|
} |
@ -0,0 +1,100 @@ |
|||||
|
package zerolog |
||||
|
|
||||
|
import ( |
||||
|
"io" |
||||
|
"sync" |
||||
|
) |
||||
|
|
||||
|
// LevelWriter defines as interface a writer may implement in order
|
||||
|
// to receive level information with payload.
|
||||
|
type LevelWriter interface { |
||||
|
io.Writer |
||||
|
WriteLevel(level Level, p []byte) (n int, err error) |
||||
|
} |
||||
|
|
||||
|
type levelWriterAdapter struct { |
||||
|
io.Writer |
||||
|
} |
||||
|
|
||||
|
func (lw levelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) { |
||||
|
return lw.Write(p) |
||||
|
} |
||||
|
|
||||
|
type syncWriter struct { |
||||
|
mu sync.Mutex |
||||
|
lw LevelWriter |
||||
|
} |
||||
|
|
||||
|
// SyncWriter wraps w so that each call to Write is synchronized with a mutex.
|
||||
|
// This syncer can be the call to writer's Write method is not thread safe.
|
||||
|
// Note that os.File Write operation is using write() syscall which is supposed
|
||||
|
// to be thread-safe on POSIX systems. So there is no need to use this with
|
||||
|
// os.File on such systems as zerolog guaranties to issue a single Write call
|
||||
|
// per log event.
|
||||
|
func SyncWriter(w io.Writer) io.Writer { |
||||
|
if lw, ok := w.(LevelWriter); ok { |
||||
|
return &syncWriter{lw: lw} |
||||
|
} |
||||
|
return &syncWriter{lw: levelWriterAdapter{w}} |
||||
|
} |
||||
|
|
||||
|
// Write implements the io.Writer interface.
|
||||
|
func (s *syncWriter) Write(p []byte) (n int, err error) { |
||||
|
s.mu.Lock() |
||||
|
defer s.mu.Unlock() |
||||
|
return s.lw.Write(p) |
||||
|
} |
||||
|
|
||||
|
// WriteLevel implements the LevelWriter interface.
|
||||
|
func (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) { |
||||
|
s.mu.Lock() |
||||
|
defer s.mu.Unlock() |
||||
|
return s.lw.WriteLevel(l, p) |
||||
|
} |
||||
|
|
||||
|
type multiLevelWriter struct { |
||||
|
writers []LevelWriter |
||||
|
} |
||||
|
|
||||
|
func (t multiLevelWriter) Write(p []byte) (n int, err error) { |
||||
|
for _, w := range t.writers { |
||||
|
n, err = w.Write(p) |
||||
|
if err != nil { |
||||
|
return |
||||
|
} |
||||
|
if n != len(p) { |
||||
|
err = io.ErrShortWrite |
||||
|
return |
||||
|
} |
||||
|
} |
||||
|
return len(p), nil |
||||
|
} |
||||
|
|
||||
|
func (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) { |
||||
|
for _, w := range t.writers { |
||||
|
n, err = w.WriteLevel(l, p) |
||||
|
if err != nil { |
||||
|
return |
||||
|
} |
||||
|
if n != len(p) { |
||||
|
err = io.ErrShortWrite |
||||
|
return |
||||
|
} |
||||
|
} |
||||
|
return len(p), nil |
||||
|
} |
||||
|
|
||||
|
// MultiLevelWriter creates a writer that duplicates its writes to all the
|
||||
|
// provided writers, similar to the Unix tee(1) command. If some writers
|
||||
|
// implement LevelWriter, their WriteLevel method will be used instead of Write.
|
||||
|
func MultiLevelWriter(writers ...io.Writer) LevelWriter { |
||||
|
lwriters := make([]LevelWriter, 0, len(writers)) |
||||
|
for _, w := range writers { |
||||
|
if lw, ok := w.(LevelWriter); ok { |
||||
|
lwriters = append(lwriters, lw) |
||||
|
} else { |
||||
|
lwriters = append(lwriters, levelWriterAdapter{w}) |
||||
|
} |
||||
|
} |
||||
|
return multiLevelWriter{lwriters} |
||||
|
} |
@ -1,123 +0,0 @@ |
|||||
# 1.0.5 |
|
||||
|
|
||||
* Fix hooks race (#707) |
|
||||
* Fix panic deadlock (#695) |
|
||||
|
|
||||
# 1.0.4 |
|
||||
|
|
||||
* Fix race when adding hooks (#612) |
|
||||
* Fix terminal check in AppEngine (#635) |
|
||||
|
|
||||
# 1.0.3 |
|
||||
|
|
||||
* Replace example files with testable examples |
|
||||
|
|
||||
# 1.0.2 |
|
||||
|
|
||||
* bug: quote non-string values in text formatter (#583) |
|
||||
* Make (*Logger) SetLevel a public method |
|
||||
|
|
||||
# 1.0.1 |
|
||||
|
|
||||
* bug: fix escaping in text formatter (#575) |
|
||||
|
|
||||
# 1.0.0 |
|
||||
|
|
||||
* Officially changed name to lower-case |
|
||||
* bug: colors on Windows 10 (#541) |
|
||||
* bug: fix race in accessing level (#512) |
|
||||
|
|
||||
# 0.11.5 |
|
||||
|
|
||||
* feature: add writer and writerlevel to entry (#372) |
|
||||
|
|
||||
# 0.11.4 |
|
||||
|
|
||||
* bug: fix undefined variable on solaris (#493) |
|
||||
|
|
||||
# 0.11.3 |
|
||||
|
|
||||
* formatter: configure quoting of empty values (#484) |
|
||||
* formatter: configure quoting character (default is `"`) (#484) |
|
||||
* bug: fix not importing io correctly in non-linux environments (#481) |
|
||||
|
|
||||
# 0.11.2 |
|
||||
|
|
||||
* bug: fix windows terminal detection (#476) |
|
||||
|
|
||||
# 0.11.1 |
|
||||
|
|
||||
* bug: fix tty detection with custom out (#471) |
|
||||
|
|
||||
# 0.11.0 |
|
||||
|
|
||||
* performance: Use bufferpool to allocate (#370) |
|
||||
* terminal: terminal detection for app-engine (#343) |
|
||||
* feature: exit handler (#375) |
|
||||
|
|
||||
# 0.10.0 |
|
||||
|
|
||||
* feature: Add a test hook (#180) |
|
||||
* feature: `ParseLevel` is now case-insensitive (#326) |
|
||||
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) |
|
||||
* performance: avoid re-allocations on `WithFields` (#335) |
|
||||
|
|
||||
# 0.9.0 |
|
||||
|
|
||||
* logrus/text_formatter: don't emit empty msg |
|
||||
* logrus/hooks/airbrake: move out of main repository |
|
||||
* logrus/hooks/sentry: move out of main repository |
|
||||
* logrus/hooks/papertrail: move out of main repository |
|
||||
* logrus/hooks/bugsnag: move out of main repository |
|
||||
* logrus/core: run tests with `-race` |
|
||||
* logrus/core: detect TTY based on `stderr` |
|
||||
* logrus/core: support `WithError` on logger |
|
||||
* logrus/core: Solaris support |
|
||||
|
|
||||
# 0.8.7 |
|
||||
|
|
||||
* logrus/core: fix possible race (#216) |
|
||||
* logrus/doc: small typo fixes and doc improvements |
|
||||
|
|
||||
|
|
||||
# 0.8.6 |
|
||||
|
|
||||
* hooks/raven: allow passing an initialized client |
|
||||
|
|
||||
# 0.8.5 |
|
||||
|
|
||||
* logrus/core: revert #208 |
|
||||
|
|
||||
# 0.8.4 |
|
||||
|
|
||||
* formatter/text: fix data race (#218) |
|
||||
|
|
||||
# 0.8.3 |
|
||||
|
|
||||
* logrus/core: fix entry log level (#208) |
|
||||
* logrus/core: improve performance of text formatter by 40% |
|
||||
* logrus/core: expose `LevelHooks` type |
|
||||
* logrus/core: add support for DragonflyBSD and NetBSD |
|
||||
* formatter/text: print structs more verbosely |
|
||||
|
|
||||
# 0.8.2 |
|
||||
|
|
||||
* logrus: fix more Fatal family functions |
|
||||
|
|
||||
# 0.8.1 |
|
||||
|
|
||||
* logrus: fix not exiting on `Fatalf` and `Fatalln` |
|
||||
|
|
||||
# 0.8.0 |
|
||||
|
|
||||
* logrus: defaults to stderr instead of stdout |
|
||||
* hooks/sentry: add special field for `*http.Request` |
|
||||
* formatter/text: ignore Windows for colors |
|
||||
|
|
||||
# 0.7.3 |
|
||||
|
|
||||
* formatter/\*: allow configuration of timestamp layout |
|
||||
|
|
||||
# 0.7.2 |
|
||||
|
|
||||
* formatter/text: Add configuration option for time format (#158) |
|
@ -1,461 +0,0 @@ |
|||||
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) |
|
||||
|
|
||||
Logrus is a structured logger for Go (golang), completely API compatible with |
|
||||
the standard library logger. |
|
||||
|
|
||||
**Seeing weird case-sensitive problems?** It's in the past been possible to |
|
||||
import Logrus as both upper- and lower-case. Due to the Go package environment, |
|
||||
this caused issues in the community and we needed a standard. Some environments |
|
||||
experienced problems with the upper-case variant, so the lower-case was decided. |
|
||||
Everything using `logrus` will need to use the lower-case: |
|
||||
`github.com/sirupsen/logrus`. Any package that isn't, should be changed. |
|
||||
|
|
||||
To fix Glide, see [these |
|
||||
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). |
|
||||
For an in-depth explanation of the casing issue, see [this |
|
||||
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). |
|
||||
|
|
||||
**Are you interested in assisting in maintaining Logrus?** Currently I have a |
|
||||
lot of obligations, and I am unable to provide Logrus with the maintainership it |
|
||||
needs. If you'd like to help, please reach out to me at `simon at author's |
|
||||
username dot com`. |
|
||||
|
|
||||
Nicely color-coded in development (when a TTY is attached, otherwise just |
|
||||
plain text): |
|
||||
|
|
||||
![Colored](http://i.imgur.com/PY7qMwd.png) |
|
||||
|
|
||||
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash |
|
||||
or Splunk: |
|
||||
|
|
||||
```json |
|
||||
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the |
|
||||
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} |
|
||||
|
|
||||
{"level":"warning","msg":"The group's number increased tremendously!", |
|
||||
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} |
|
||||
|
|
||||
{"animal":"walrus","level":"info","msg":"A giant walrus appears!", |
|
||||
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} |
|
||||
|
|
||||
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", |
|
||||
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} |
|
||||
|
|
||||
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, |
|
||||
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} |
|
||||
``` |
|
||||
|
|
||||
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not |
|
||||
attached, the output is compatible with the |
|
||||
[logfmt](http://godoc.org/github.com/kr/logfmt) format: |
|
||||
|
|
||||
```text |
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 |
|
||||
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 |
|
||||
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true |
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 |
|
||||
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 |
|
||||
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true |
|
||||
exit status 1 |
|
||||
``` |
|
||||
|
|
||||
#### Case-sensitivity |
|
||||
|
|
||||
The organization's name was changed to lower-case--and this will not be changed |
|
||||
back. If you are getting import conflicts due to case sensitivity, please use |
|
||||
the lower-case import: `github.com/sirupsen/logrus`. |
|
||||
|
|
||||
#### Example |
|
||||
|
|
||||
The simplest way to use Logrus is simply the package-level exported logger: |
|
||||
|
|
||||
```go |
|
||||
package main |
|
||||
|
|
||||
import ( |
|
||||
log "github.com/sirupsen/logrus" |
|
||||
) |
|
||||
|
|
||||
func main() { |
|
||||
log.WithFields(log.Fields{ |
|
||||
"animal": "walrus", |
|
||||
}).Info("A walrus appears") |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
Note that it's completely api-compatible with the stdlib logger, so you can |
|
||||
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` |
|
||||
and you'll now have the flexibility of Logrus. You can customize it all you |
|
||||
want: |
|
||||
|
|
||||
```go |
|
||||
package main |
|
||||
|
|
||||
import ( |
|
||||
"os" |
|
||||
log "github.com/sirupsen/logrus" |
|
||||
) |
|
||||
|
|
||||
func init() { |
|
||||
// Log as JSON instead of the default ASCII formatter. |
|
||||
log.SetFormatter(&log.JSONFormatter{}) |
|
||||
|
|
||||
// Output to stdout instead of the default stderr |
|
||||
// Can be any io.Writer, see below for File example |
|
||||
log.SetOutput(os.Stdout) |
|
||||
|
|
||||
// Only log the warning severity or above. |
|
||||
log.SetLevel(log.WarnLevel) |
|
||||
} |
|
||||
|
|
||||
func main() { |
|
||||
log.WithFields(log.Fields{ |
|
||||
"animal": "walrus", |
|
||||
"size": 10, |
|
||||
}).Info("A group of walrus emerges from the ocean") |
|
||||
|
|
||||
log.WithFields(log.Fields{ |
|
||||
"omg": true, |
|
||||
"number": 122, |
|
||||
}).Warn("The group's number increased tremendously!") |
|
||||
|
|
||||
log.WithFields(log.Fields{ |
|
||||
"omg": true, |
|
||||
"number": 100, |
|
||||
}).Fatal("The ice breaks!") |
|
||||
|
|
||||
// A common pattern is to re-use fields between logging statements by re-using |
|
||||
// the logrus.Entry returned from WithFields() |
|
||||
contextLogger := log.WithFields(log.Fields{ |
|
||||
"common": "this is a common field", |
|
||||
"other": "I also should be logged always", |
|
||||
}) |
|
||||
|
|
||||
contextLogger.Info("I'll be logged with common and other field") |
|
||||
contextLogger.Info("Me too") |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
For more advanced usage such as logging to multiple locations from the same |
|
||||
application, you can also create an instance of the `logrus` Logger: |
|
||||
|
|
||||
```go |
|
||||
package main |
|
||||
|
|
||||
import ( |
|
||||
"os" |
|
||||
"github.com/sirupsen/logrus" |
|
||||
) |
|
||||
|
|
||||
// Create a new instance of the logger. You can have any number of instances. |
|
||||
var log = logrus.New() |
|
||||
|
|
||||
func main() { |
|
||||
// The API for setting attributes is a little different than the package level |
|
||||
// exported logger. See Godoc. |
|
||||
log.Out = os.Stdout |
|
||||
|
|
||||
// You could set this to any `io.Writer` such as a file |
|
||||
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) |
|
||||
// if err == nil { |
|
||||
// log.Out = file |
|
||||
// } else { |
|
||||
// log.Info("Failed to log to file, using default stderr") |
|
||||
// } |
|
||||
|
|
||||
log.WithFields(logrus.Fields{ |
|
||||
"animal": "walrus", |
|
||||
"size": 10, |
|
||||
}).Info("A group of walrus emerges from the ocean") |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
#### Fields |
|
||||
|
|
||||
Logrus encourages careful, structured logging through logging fields instead of |
|
||||
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed |
|
||||
to send event %s to topic %s with key %d")`, you should log the much more |
|
||||
discoverable: |
|
||||
|
|
||||
```go |
|
||||
log.WithFields(log.Fields{ |
|
||||
"event": event, |
|
||||
"topic": topic, |
|
||||
"key": key, |
|
||||
}).Fatal("Failed to send event") |
|
||||
``` |
|
||||
|
|
||||
We've found this API forces you to think about logging in a way that produces |
|
||||
much more useful logging messages. We've been in countless situations where just |
|
||||
a single added field to a log statement that was already there would've saved us |
|
||||
hours. The `WithFields` call is optional. |
|
||||
|
|
||||
In general, with Logrus using any of the `printf`-family functions should be |
|
||||
seen as a hint you should add a field, however, you can still use the |
|
||||
`printf`-family functions with Logrus. |
|
||||
|
|
||||
#### Default Fields |
|
||||
|
|
||||
Often it's helpful to have fields _always_ attached to log statements in an |
|
||||
application or parts of one. For example, you may want to always log the |
|
||||
`request_id` and `user_ip` in the context of a request. Instead of writing |
|
||||
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on |
|
||||
every line, you can create a `logrus.Entry` to pass around instead: |
|
||||
|
|
||||
```go |
|
||||
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) |
|
||||
requestLogger.Info("something happened on that request") # will log request_id and user_ip |
|
||||
requestLogger.Warn("something not great happened") |
|
||||
``` |
|
||||
|
|
||||
#### Hooks |
|
||||
|
|
||||
You can add hooks for logging levels. For example to send errors to an exception |
|
||||
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to |
|
||||
multiple places simultaneously, e.g. syslog. |
|
||||
|
|
||||
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in |
|
||||
`init`: |
|
||||
|
|
||||
```go |
|
||||
import ( |
|
||||
log "github.com/sirupsen/logrus" |
|
||||
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" |
|
||||
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" |
|
||||
"log/syslog" |
|
||||
) |
|
||||
|
|
||||
func init() { |
|
||||
|
|
||||
// Use the Airbrake hook to report errors that have Error severity or above to |
|
||||
// an exception tracker. You can create custom hooks, see the Hooks section. |
|
||||
log.AddHook(airbrake.NewHook(123, "xyz", "production")) |
|
||||
|
|
||||
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") |
|
||||
if err != nil { |
|
||||
log.Error("Unable to connect to local syslog daemon") |
|
||||
} else { |
|
||||
log.AddHook(hook) |
|
||||
} |
|
||||
} |
|
||||
``` |
|
||||
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). |
|
||||
|
|
||||
A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) |
|
||||
|
|
||||
|
|
||||
#### Level logging |
|
||||
|
|
||||
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. |
|
||||
|
|
||||
```go |
|
||||
log.Debug("Useful debugging information.") |
|
||||
log.Info("Something noteworthy happened!") |
|
||||
log.Warn("You should probably take a look at this.") |
|
||||
log.Error("Something failed but I'm not quitting.") |
|
||||
// Calls os.Exit(1) after logging |
|
||||
log.Fatal("Bye.") |
|
||||
// Calls panic() after logging |
|
||||
log.Panic("I'm bailing.") |
|
||||
``` |
|
||||
|
|
||||
You can set the logging level on a `Logger`, then it will only log entries with |
|
||||
that severity or anything above it: |
|
||||
|
|
||||
```go |
|
||||
// Will log anything that is info or above (warn, error, fatal, panic). Default. |
|
||||
log.SetLevel(log.InfoLevel) |
|
||||
``` |
|
||||
|
|
||||
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose |
|
||||
environment if your application has that. |
|
||||
|
|
||||
#### Entries |
|
||||
|
|
||||
Besides the fields added with `WithField` or `WithFields` some fields are |
|
||||
automatically added to all logging events: |
|
||||
|
|
||||
1. `time`. The timestamp when the entry was created. |
|
||||
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after |
|
||||
the `AddFields` call. E.g. `Failed to send event.` |
|
||||
3. `level`. The logging level. E.g. `info`. |
|
||||
|
|
||||
#### Environments |
|
||||
|
|
||||
Logrus has no notion of environment. |
|
||||
|
|
||||
If you wish for hooks and formatters to only be used in specific environments, |
|
||||
you should handle that yourself. For example, if your application has a global |
|
||||
variable `Environment`, which is a string representation of the environment you |
|
||||
could do: |
|
||||
|
|
||||
```go |
|
||||
import ( |
|
||||
log "github.com/sirupsen/logrus" |
|
||||
) |
|
||||
|
|
||||
init() { |
|
||||
// do something here to set environment depending on an environment variable |
|
||||
// or command-line flag |
|
||||
if Environment == "production" { |
|
||||
log.SetFormatter(&log.JSONFormatter{}) |
|
||||
} else { |
|
||||
// The TextFormatter is default, you don't actually have to do this. |
|
||||
log.SetFormatter(&log.TextFormatter{}) |
|
||||
} |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
This configuration is how `logrus` was intended to be used, but JSON in |
|
||||
production is mostly only useful if you do log aggregation with tools like |
|
||||
Splunk or Logstash. |
|
||||
|
|
||||
#### Formatters |
|
||||
|
|
||||
The built-in logging formatters are: |
|
||||
|
|
||||
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise |
|
||||
without colors. |
|
||||
* *Note:* to force colored output when there is no TTY, set the `ForceColors` |
|
||||
field to `true`. To force no colored output even if there is a TTY set the |
|
||||
`DisableColors` field to `true`. For Windows, see |
|
||||
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). |
|
||||
* When colors are enabled, levels are truncated to 4 characters by default. To disable |
|
||||
truncation set the `DisableLevelTruncation` field to `true`. |
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). |
|
||||
* `logrus.JSONFormatter`. Logs fields as JSON. |
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). |
|
||||
|
|
||||
Third party logging formatters: |
|
||||
|
|
||||
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. |
|
||||
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. |
|
||||
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. |
|
||||
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. |
|
||||
|
|
||||
You can define your formatter by implementing the `Formatter` interface, |
|
||||
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a |
|
||||
`Fields` type (`map[string]interface{}`) with all your fields as well as the |
|
||||
default ones (see Entries section above): |
|
||||
|
|
||||
```go |
|
||||
type MyJSONFormatter struct { |
|
||||
} |
|
||||
|
|
||||
log.SetFormatter(new(MyJSONFormatter)) |
|
||||
|
|
||||
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { |
|
||||
// Note this doesn't include Time, Level and Message which are available on |
|
||||
// the Entry. Consult `godoc` on information about those fields or read the |
|
||||
// source of the official loggers. |
|
||||
serialized, err := json.Marshal(entry.Data) |
|
||||
if err != nil { |
|
||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) |
|
||||
} |
|
||||
return append(serialized, '\n'), nil |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
#### Logger as an `io.Writer` |
|
||||
|
|
||||
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. |
|
||||
|
|
||||
```go |
|
||||
w := logger.Writer() |
|
||||
defer w.Close() |
|
||||
|
|
||||
srv := http.Server{ |
|
||||
// create a stdlib log.Logger that writes to |
|
||||
// logrus.Logger. |
|
||||
ErrorLog: log.New(w, "", 0), |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
Each line written to that writer will be printed the usual way, using formatters |
|
||||
and hooks. The level for those entries is `info`. |
|
||||
|
|
||||
This means that we can override the standard library logger easily: |
|
||||
|
|
||||
```go |
|
||||
logger := logrus.New() |
|
||||
logger.Formatter = &logrus.JSONFormatter{} |
|
||||
|
|
||||
// Use logrus for standard log output |
|
||||
// Note that `log` here references stdlib's log |
|
||||
// Not logrus imported under the name `log`. |
|
||||
log.SetOutput(logger.Writer()) |
|
||||
``` |
|
||||
|
|
||||
#### Rotation |
|
||||
|
|
||||
Log rotation is not provided with Logrus. Log rotation should be done by an |
|
||||
external program (like `logrotate(8)`) that can compress and delete old log |
|
||||
entries. It should not be a feature of the application-level logger. |
|
||||
|
|
||||
#### Tools |
|
||||
|
|
||||
| Tool | Description | |
|
||||
| ---- | ----------- | |
|
||||
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| |
|
||||
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | |
|
||||
|
|
||||
#### Testing |
|
||||
|
|
||||
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: |
|
||||
|
|
||||
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook |
|
||||
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): |
|
||||
|
|
||||
```go |
|
||||
import( |
|
||||
"github.com/sirupsen/logrus" |
|
||||
"github.com/sirupsen/logrus/hooks/test" |
|
||||
"github.com/stretchr/testify/assert" |
|
||||
"testing" |
|
||||
) |
|
||||
|
|
||||
func TestSomething(t*testing.T){ |
|
||||
logger, hook := test.NewNullLogger() |
|
||||
logger.Error("Helloerror") |
|
||||
|
|
||||
assert.Equal(t, 1, len(hook.Entries)) |
|
||||
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) |
|
||||
assert.Equal(t, "Helloerror", hook.LastEntry().Message) |
|
||||
|
|
||||
hook.Reset() |
|
||||
assert.Nil(t, hook.LastEntry()) |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
#### Fatal handlers |
|
||||
|
|
||||
Logrus can register one or more functions that will be called when any `fatal` |
|
||||
level message is logged. The registered handlers will be executed before |
|
||||
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need |
|
||||
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. |
|
||||
|
|
||||
``` |
|
||||
... |
|
||||
handler := func() { |
|
||||
// gracefully shutdown something... |
|
||||
} |
|
||||
logrus.RegisterExitHandler(handler) |
|
||||
... |
|
||||
``` |
|
||||
|
|
||||
#### Thread safety |
|
||||
|
|
||||
By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. |
|
||||
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. |
|
||||
|
|
||||
Situation when locking is not needed includes: |
|
||||
|
|
||||
* You have no hooks registered, or hooks calling is already thread-safe. |
|
||||
|
|
||||
* Writing to logger.Out is already thread-safe, for example: |
|
||||
|
|
||||
1) logger.Out is protected by locks. |
|
||||
|
|
||||
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) |
|
||||
|
|
||||
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) |
|
@ -1,64 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
// The following code was sourced and modified from the
|
|
||||
// https://github.com/tebeka/atexit package governed by the following license:
|
|
||||
//
|
|
||||
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
|
|
||||
//
|
|
||||
// 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.
|
|
||||
|
|
||||
import ( |
|
||||
"fmt" |
|
||||
"os" |
|
||||
) |
|
||||
|
|
||||
var handlers = []func(){} |
|
||||
|
|
||||
func runHandler(handler func()) { |
|
||||
defer func() { |
|
||||
if err := recover(); err != nil { |
|
||||
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) |
|
||||
} |
|
||||
}() |
|
||||
|
|
||||
handler() |
|
||||
} |
|
||||
|
|
||||
func runHandlers() { |
|
||||
for _, handler := range handlers { |
|
||||
runHandler(handler) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
|
||||
func Exit(code int) { |
|
||||
runHandlers() |
|
||||
os.Exit(code) |
|
||||
} |
|
||||
|
|
||||
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
|
|
||||
// all handlers. The handlers will also be invoked when any Fatal log entry is
|
|
||||
// made.
|
|
||||
//
|
|
||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
|
||||
// message but also needs to gracefully shutdown. An example usecase could be
|
|
||||
// closing database connections, or sending a alert that the application is
|
|
||||
// closing.
|
|
||||
func RegisterExitHandler(handler func()) { |
|
||||
handlers = append(handlers, handler) |
|
||||
} |
|
@ -1,14 +0,0 @@ |
|||||
version: "{build}" |
|
||||
platform: x64 |
|
||||
clone_folder: c:\gopath\src\github.com\sirupsen\logrus |
|
||||
environment: |
|
||||
GOPATH: c:\gopath |
|
||||
branches: |
|
||||
only: |
|
||||
- master |
|
||||
install: |
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH% |
|
||||
- go version |
|
||||
build_script: |
|
||||
- go get -t |
|
||||
- go test |
|
@ -1,26 +0,0 @@ |
|||||
/* |
|
||||
Package logrus is a structured logger for Go, completely API compatible with the standard library logger. |
|
||||
|
|
||||
|
|
||||
The simplest way to use Logrus is simply the package-level exported logger: |
|
||||
|
|
||||
package main |
|
||||
|
|
||||
import ( |
|
||||
log "github.com/sirupsen/logrus" |
|
||||
) |
|
||||
|
|
||||
func main() { |
|
||||
log.WithFields(log.Fields{ |
|
||||
"animal": "walrus", |
|
||||
"number": 1, |
|
||||
"size": 10, |
|
||||
}).Info("A walrus appears") |
|
||||
} |
|
||||
|
|
||||
Output: |
|
||||
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 |
|
||||
|
|
||||
For a full guide visit https://github.com/sirupsen/logrus
|
|
||||
*/ |
|
||||
package logrus |
|
@ -1,300 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"bytes" |
|
||||
"fmt" |
|
||||
"os" |
|
||||
"sync" |
|
||||
"time" |
|
||||
) |
|
||||
|
|
||||
var bufferPool *sync.Pool |
|
||||
|
|
||||
func init() { |
|
||||
bufferPool = &sync.Pool{ |
|
||||
New: func() interface{} { |
|
||||
return new(bytes.Buffer) |
|
||||
}, |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Defines the key when adding errors using WithError.
|
|
||||
var ErrorKey = "error" |
|
||||
|
|
||||
// An entry is the final or intermediate Logrus logging entry. It contains all
|
|
||||
// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
|
|
||||
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
|
|
||||
// passed around as much as you wish to avoid field duplication.
|
|
||||
type Entry struct { |
|
||||
Logger *Logger |
|
||||
|
|
||||
// Contains all the fields set by the user.
|
|
||||
Data Fields |
|
||||
|
|
||||
// Time at which the log entry was created
|
|
||||
Time time.Time |
|
||||
|
|
||||
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
|
|
||||
// This field will be set on entry firing and the value will be equal to the one in Logger struct field.
|
|
||||
Level Level |
|
||||
|
|
||||
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
|
|
||||
Message string |
|
||||
|
|
||||
// When formatter is called in entry.log(), an Buffer may be set to entry
|
|
||||
Buffer *bytes.Buffer |
|
||||
} |
|
||||
|
|
||||
func NewEntry(logger *Logger) *Entry { |
|
||||
return &Entry{ |
|
||||
Logger: logger, |
|
||||
// Default is five fields, give a little extra room
|
|
||||
Data: make(Fields, 5), |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Returns the string representation from the reader and ultimately the
|
|
||||
// formatter.
|
|
||||
func (entry *Entry) String() (string, error) { |
|
||||
serialized, err := entry.Logger.Formatter.Format(entry) |
|
||||
if err != nil { |
|
||||
return "", err |
|
||||
} |
|
||||
str := string(serialized) |
|
||||
return str, nil |
|
||||
} |
|
||||
|
|
||||
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
|
|
||||
func (entry *Entry) WithError(err error) *Entry { |
|
||||
return entry.WithField(ErrorKey, err) |
|
||||
} |
|
||||
|
|
||||
// Add a single field to the Entry.
|
|
||||
func (entry *Entry) WithField(key string, value interface{}) *Entry { |
|
||||
return entry.WithFields(Fields{key: value}) |
|
||||
} |
|
||||
|
|
||||
// Add a map of fields to the Entry.
|
|
||||
func (entry *Entry) WithFields(fields Fields) *Entry { |
|
||||
data := make(Fields, len(entry.Data)+len(fields)) |
|
||||
for k, v := range entry.Data { |
|
||||
data[k] = v |
|
||||
} |
|
||||
for k, v := range fields { |
|
||||
data[k] = v |
|
||||
} |
|
||||
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time} |
|
||||
} |
|
||||
|
|
||||
// Overrides the time of the Entry.
|
|
||||
func (entry *Entry) WithTime(t time.Time) *Entry { |
|
||||
return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t} |
|
||||
} |
|
||||
|
|
||||
// This function is not declared with a pointer value because otherwise
|
|
||||
// race conditions will occur when using multiple goroutines
|
|
||||
func (entry Entry) log(level Level, msg string) { |
|
||||
var buffer *bytes.Buffer |
|
||||
|
|
||||
// Default to now, but allow users to override if they want.
|
|
||||
//
|
|
||||
// We don't have to worry about polluting future calls to Entry#log()
|
|
||||
// with this assignment because this function is declared with a
|
|
||||
// non-pointer receiver.
|
|
||||
if entry.Time.IsZero() { |
|
||||
entry.Time = time.Now() |
|
||||
} |
|
||||
|
|
||||
entry.Level = level |
|
||||
entry.Message = msg |
|
||||
|
|
||||
entry.fireHooks() |
|
||||
|
|
||||
buffer = bufferPool.Get().(*bytes.Buffer) |
|
||||
buffer.Reset() |
|
||||
defer bufferPool.Put(buffer) |
|
||||
entry.Buffer = buffer |
|
||||
|
|
||||
entry.write() |
|
||||
|
|
||||
entry.Buffer = nil |
|
||||
|
|
||||
// To avoid Entry#log() returning a value that only would make sense for
|
|
||||
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
|
||||
// directly here.
|
|
||||
if level <= PanicLevel { |
|
||||
panic(&entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) fireHooks() { |
|
||||
entry.Logger.mu.Lock() |
|
||||
defer entry.Logger.mu.Unlock() |
|
||||
err := entry.Logger.Hooks.Fire(entry.Level, entry) |
|
||||
if err != nil { |
|
||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) write() { |
|
||||
entry.Logger.mu.Lock() |
|
||||
defer entry.Logger.mu.Unlock() |
|
||||
serialized, err := entry.Logger.Formatter.Format(entry) |
|
||||
if err != nil { |
|
||||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) |
|
||||
} else { |
|
||||
_, err = entry.Logger.Out.Write(serialized) |
|
||||
if err != nil { |
|
||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Debug(args ...interface{}) { |
|
||||
if entry.Logger.level() >= DebugLevel { |
|
||||
entry.log(DebugLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Print(args ...interface{}) { |
|
||||
entry.Info(args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Info(args ...interface{}) { |
|
||||
if entry.Logger.level() >= InfoLevel { |
|
||||
entry.log(InfoLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warn(args ...interface{}) { |
|
||||
if entry.Logger.level() >= WarnLevel { |
|
||||
entry.log(WarnLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warning(args ...interface{}) { |
|
||||
entry.Warn(args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Error(args ...interface{}) { |
|
||||
if entry.Logger.level() >= ErrorLevel { |
|
||||
entry.log(ErrorLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Fatal(args ...interface{}) { |
|
||||
if entry.Logger.level() >= FatalLevel { |
|
||||
entry.log(FatalLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Panic(args ...interface{}) { |
|
||||
if entry.Logger.level() >= PanicLevel { |
|
||||
entry.log(PanicLevel, fmt.Sprint(args...)) |
|
||||
} |
|
||||
panic(fmt.Sprint(args...)) |
|
||||
} |
|
||||
|
|
||||
// Entry Printf family functions
|
|
||||
|
|
||||
func (entry *Entry) Debugf(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= DebugLevel { |
|
||||
entry.Debug(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Infof(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= InfoLevel { |
|
||||
entry.Info(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Printf(format string, args ...interface{}) { |
|
||||
entry.Infof(format, args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warnf(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= WarnLevel { |
|
||||
entry.Warn(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warningf(format string, args ...interface{}) { |
|
||||
entry.Warnf(format, args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Errorf(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= ErrorLevel { |
|
||||
entry.Error(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Fatalf(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= FatalLevel { |
|
||||
entry.Fatal(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Panicf(format string, args ...interface{}) { |
|
||||
if entry.Logger.level() >= PanicLevel { |
|
||||
entry.Panic(fmt.Sprintf(format, args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Entry Println family functions
|
|
||||
|
|
||||
func (entry *Entry) Debugln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= DebugLevel { |
|
||||
entry.Debug(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Infoln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= InfoLevel { |
|
||||
entry.Info(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Println(args ...interface{}) { |
|
||||
entry.Infoln(args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warnln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= WarnLevel { |
|
||||
entry.Warn(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Warningln(args ...interface{}) { |
|
||||
entry.Warnln(args...) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Errorln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= ErrorLevel { |
|
||||
entry.Error(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Fatalln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= FatalLevel { |
|
||||
entry.Fatal(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Panicln(args ...interface{}) { |
|
||||
if entry.Logger.level() >= PanicLevel { |
|
||||
entry.Panic(entry.sprintlnn(args...)) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Sprintlnn => Sprint no newline. This is to get the behavior of how
|
|
||||
// fmt.Sprintln where spaces are always added between operands, regardless of
|
|
||||
// their type. Instead of vendoring the Sprintln implementation to spare a
|
|
||||
// string allocation, we do the simplest thing.
|
|
||||
func (entry *Entry) sprintlnn(args ...interface{}) string { |
|
||||
msg := fmt.Sprintln(args...) |
|
||||
return msg[:len(msg)-1] |
|
||||
} |
|
@ -1,201 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"io" |
|
||||
"time" |
|
||||
) |
|
||||
|
|
||||
var ( |
|
||||
// std is the name of the standard logger in stdlib `log`
|
|
||||
std = New() |
|
||||
) |
|
||||
|
|
||||
func StandardLogger() *Logger { |
|
||||
return std |
|
||||
} |
|
||||
|
|
||||
// SetOutput sets the standard logger output.
|
|
||||
func SetOutput(out io.Writer) { |
|
||||
std.SetOutput(out) |
|
||||
} |
|
||||
|
|
||||
// SetFormatter sets the standard logger formatter.
|
|
||||
func SetFormatter(formatter Formatter) { |
|
||||
std.mu.Lock() |
|
||||
defer std.mu.Unlock() |
|
||||
std.Formatter = formatter |
|
||||
} |
|
||||
|
|
||||
// SetLevel sets the standard logger level.
|
|
||||
func SetLevel(level Level) { |
|
||||
std.mu.Lock() |
|
||||
defer std.mu.Unlock() |
|
||||
std.SetLevel(level) |
|
||||
} |
|
||||
|
|
||||
// GetLevel returns the standard logger level.
|
|
||||
func GetLevel() Level { |
|
||||
std.mu.Lock() |
|
||||
defer std.mu.Unlock() |
|
||||
return std.level() |
|
||||
} |
|
||||
|
|
||||
// AddHook adds a hook to the standard logger hooks.
|
|
||||
func AddHook(hook Hook) { |
|
||||
std.mu.Lock() |
|
||||
defer std.mu.Unlock() |
|
||||
std.Hooks.Add(hook) |
|
||||
} |
|
||||
|
|
||||
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
|
|
||||
func WithError(err error) *Entry { |
|
||||
return std.WithField(ErrorKey, err) |
|
||||
} |
|
||||
|
|
||||
// WithField creates an entry from the standard logger and adds a field to
|
|
||||
// it. If you want multiple fields, use `WithFields`.
|
|
||||
//
|
|
||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
|
||||
// or Panic on the Entry it returns.
|
|
||||
func WithField(key string, value interface{}) *Entry { |
|
||||
return std.WithField(key, value) |
|
||||
} |
|
||||
|
|
||||
// WithFields creates an entry from the standard logger and adds multiple
|
|
||||
// fields to it. This is simply a helper for `WithField`, invoking it
|
|
||||
// once for each field.
|
|
||||
//
|
|
||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
|
||||
// or Panic on the Entry it returns.
|
|
||||
func WithFields(fields Fields) *Entry { |
|
||||
return std.WithFields(fields) |
|
||||
} |
|
||||
|
|
||||
// WithTime creats an entry from the standard logger and overrides the time of
|
|
||||
// logs generated with it.
|
|
||||
//
|
|
||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
|
||||
// or Panic on the Entry it returns.
|
|
||||
func WithTime(t time.Time) *Entry { |
|
||||
return std.WithTime(t) |
|
||||
} |
|
||||
|
|
||||
// Debug logs a message at level Debug on the standard logger.
|
|
||||
func Debug(args ...interface{}) { |
|
||||
std.Debug(args...) |
|
||||
} |
|
||||
|
|
||||
// Print logs a message at level Info on the standard logger.
|
|
||||
func Print(args ...interface{}) { |
|
||||
std.Print(args...) |
|
||||
} |
|
||||
|
|
||||
// Info logs a message at level Info on the standard logger.
|
|
||||
func Info(args ...interface{}) { |
|
||||
std.Info(args...) |
|
||||
} |
|
||||
|
|
||||
// Warn logs a message at level Warn on the standard logger.
|
|
||||
func Warn(args ...interface{}) { |
|
||||
std.Warn(args...) |
|
||||
} |
|
||||
|
|
||||
// Warning logs a message at level Warn on the standard logger.
|
|
||||
func Warning(args ...interface{}) { |
|
||||
std.Warning(args...) |
|
||||
} |
|
||||
|
|
||||
// Error logs a message at level Error on the standard logger.
|
|
||||
func Error(args ...interface{}) { |
|
||||
std.Error(args...) |
|
||||
} |
|
||||
|
|
||||
// Panic logs a message at level Panic on the standard logger.
|
|
||||
func Panic(args ...interface{}) { |
|
||||
std.Panic(args...) |
|
||||
} |
|
||||
|
|
||||
// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
|
|
||||
func Fatal(args ...interface{}) { |
|
||||
std.Fatal(args...) |
|
||||
} |
|
||||
|
|
||||
// Debugf logs a message at level Debug on the standard logger.
|
|
||||
func Debugf(format string, args ...interface{}) { |
|
||||
std.Debugf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Printf logs a message at level Info on the standard logger.
|
|
||||
func Printf(format string, args ...interface{}) { |
|
||||
std.Printf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Infof logs a message at level Info on the standard logger.
|
|
||||
func Infof(format string, args ...interface{}) { |
|
||||
std.Infof(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Warnf logs a message at level Warn on the standard logger.
|
|
||||
func Warnf(format string, args ...interface{}) { |
|
||||
std.Warnf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Warningf logs a message at level Warn on the standard logger.
|
|
||||
func Warningf(format string, args ...interface{}) { |
|
||||
std.Warningf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Errorf logs a message at level Error on the standard logger.
|
|
||||
func Errorf(format string, args ...interface{}) { |
|
||||
std.Errorf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Panicf logs a message at level Panic on the standard logger.
|
|
||||
func Panicf(format string, args ...interface{}) { |
|
||||
std.Panicf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
|
|
||||
func Fatalf(format string, args ...interface{}) { |
|
||||
std.Fatalf(format, args...) |
|
||||
} |
|
||||
|
|
||||
// Debugln logs a message at level Debug on the standard logger.
|
|
||||
func Debugln(args ...interface{}) { |
|
||||
std.Debugln(args...) |
|
||||
} |
|
||||
|
|
||||
// Println logs a message at level Info on the standard logger.
|
|
||||
func Println(args ...interface{}) { |
|
||||
std.Println(args...) |
|
||||
} |
|
||||
|
|
||||
// Infoln logs a message at level Info on the standard logger.
|
|
||||
func Infoln(args ...interface{}) { |
|
||||
std.Infoln(args...) |
|
||||
} |
|
||||
|
|
||||
// Warnln logs a message at level Warn on the standard logger.
|
|
||||
func Warnln(args ...interface{}) { |
|
||||
std.Warnln(args...) |
|
||||
} |
|
||||
|
|
||||
// Warningln logs a message at level Warn on the standard logger.
|
|
||||
func Warningln(args ...interface{}) { |
|
||||
std.Warningln(args...) |
|
||||
} |
|
||||
|
|
||||
// Errorln logs a message at level Error on the standard logger.
|
|
||||
func Errorln(args ...interface{}) { |
|
||||
std.Errorln(args...) |
|
||||
} |
|
||||
|
|
||||
// Panicln logs a message at level Panic on the standard logger.
|
|
||||
func Panicln(args ...interface{}) { |
|
||||
std.Panicln(args...) |
|
||||
} |
|
||||
|
|
||||
// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
|
|
||||
func Fatalln(args ...interface{}) { |
|
||||
std.Fatalln(args...) |
|
||||
} |
|
@ -1,51 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import "time" |
|
||||
|
|
||||
const defaultTimestampFormat = time.RFC3339 |
|
||||
|
|
||||
// The Formatter interface is used to implement a custom Formatter. It takes an
|
|
||||
// `Entry`. It exposes all the fields, including the default ones:
|
|
||||
//
|
|
||||
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
|
|
||||
// * `entry.Data["time"]`. The timestamp.
|
|
||||
// * `entry.Data["level"]. The level the entry was logged at.
|
|
||||
//
|
|
||||
// Any additional fields added with `WithField` or `WithFields` are also in
|
|
||||
// `entry.Data`. Format is expected to return an array of bytes which are then
|
|
||||
// logged to `logger.Out`.
|
|
||||
type Formatter interface { |
|
||||
Format(*Entry) ([]byte, error) |
|
||||
} |
|
||||
|
|
||||
// This is to not silently overwrite `time`, `msg` and `level` fields when
|
|
||||
// dumping it. If this code wasn't there doing:
|
|
||||
//
|
|
||||
// logrus.WithField("level", 1).Info("hello")
|
|
||||
//
|
|
||||
// Would just silently drop the user provided level. Instead with this code
|
|
||||
// it'll logged as:
|
|
||||
//
|
|
||||
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
|
|
||||
//
|
|
||||
// It's not exported because it's still using Data in an opinionated way. It's to
|
|
||||
// avoid code duplication between the two default formatters.
|
|
||||
func prefixFieldClashes(data Fields, fieldMap FieldMap) { |
|
||||
timeKey := fieldMap.resolve(FieldKeyTime) |
|
||||
if t, ok := data[timeKey]; ok { |
|
||||
data["fields."+timeKey] = t |
|
||||
delete(data, timeKey) |
|
||||
} |
|
||||
|
|
||||
msgKey := fieldMap.resolve(FieldKeyMsg) |
|
||||
if m, ok := data[msgKey]; ok { |
|
||||
data["fields."+msgKey] = m |
|
||||
delete(data, msgKey) |
|
||||
} |
|
||||
|
|
||||
levelKey := fieldMap.resolve(FieldKeyLevel) |
|
||||
if l, ok := data[levelKey]; ok { |
|
||||
data["fields."+levelKey] = l |
|
||||
delete(data, levelKey) |
|
||||
} |
|
||||
} |
|
@ -1,34 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
// A hook to be fired when logging on the logging levels returned from
|
|
||||
// `Levels()` on your implementation of the interface. Note that this is not
|
|
||||
// fired in a goroutine or a channel with workers, you should handle such
|
|
||||
// functionality yourself if your call is non-blocking and you don't wish for
|
|
||||
// the logging calls for levels returned from `Levels()` to block.
|
|
||||
type Hook interface { |
|
||||
Levels() []Level |
|
||||
Fire(*Entry) error |
|
||||
} |
|
||||
|
|
||||
// Internal type for storing the hooks on a logger instance.
|
|
||||
type LevelHooks map[Level][]Hook |
|
||||
|
|
||||
// Add a hook to an instance of logger. This is called with
|
|
||||
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
|
|
||||
func (hooks LevelHooks) Add(hook Hook) { |
|
||||
for _, level := range hook.Levels() { |
|
||||
hooks[level] = append(hooks[level], hook) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Fire all the hooks for the passed level. Used by `entry.log` to fire
|
|
||||
// appropriate hooks for a log entry.
|
|
||||
func (hooks LevelHooks) Fire(level Level, entry *Entry) error { |
|
||||
for _, hook := range hooks[level] { |
|
||||
if err := hook.Fire(entry); err != nil { |
|
||||
return err |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
return nil |
|
||||
} |
|
@ -1,89 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"encoding/json" |
|
||||
"fmt" |
|
||||
) |
|
||||
|
|
||||
type fieldKey string |
|
||||
|
|
||||
// FieldMap allows customization of the key names for default fields.
|
|
||||
type FieldMap map[fieldKey]string |
|
||||
|
|
||||
// Default key names for the default fields
|
|
||||
const ( |
|
||||
FieldKeyMsg = "msg" |
|
||||
FieldKeyLevel = "level" |
|
||||
FieldKeyTime = "time" |
|
||||
) |
|
||||
|
|
||||
func (f FieldMap) resolve(key fieldKey) string { |
|
||||
if k, ok := f[key]; ok { |
|
||||
return k |
|
||||
} |
|
||||
|
|
||||
return string(key) |
|
||||
} |
|
||||
|
|
||||
// JSONFormatter formats logs into parsable json
|
|
||||
type JSONFormatter struct { |
|
||||
// TimestampFormat sets the format used for marshaling timestamps.
|
|
||||
TimestampFormat string |
|
||||
|
|
||||
// DisableTimestamp allows disabling automatic timestamps in output
|
|
||||
DisableTimestamp bool |
|
||||
|
|
||||
// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
|
|
||||
DataKey string |
|
||||
|
|
||||
// FieldMap allows users to customize the names of keys for default fields.
|
|
||||
// As an example:
|
|
||||
// formatter := &JSONFormatter{
|
|
||||
// FieldMap: FieldMap{
|
|
||||
// FieldKeyTime: "@timestamp",
|
|
||||
// FieldKeyLevel: "@level",
|
|
||||
// FieldKeyMsg: "@message",
|
|
||||
// },
|
|
||||
// }
|
|
||||
FieldMap FieldMap |
|
||||
} |
|
||||
|
|
||||
// Format renders a single log entry
|
|
||||
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { |
|
||||
data := make(Fields, len(entry.Data)+3) |
|
||||
for k, v := range entry.Data { |
|
||||
switch v := v.(type) { |
|
||||
case error: |
|
||||
// Otherwise errors are ignored by `encoding/json`
|
|
||||
// https://github.com/sirupsen/logrus/issues/137
|
|
||||
data[k] = v.Error() |
|
||||
default: |
|
||||
data[k] = v |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
if f.DataKey != "" { |
|
||||
newData := make(Fields, 4) |
|
||||
newData[f.DataKey] = data |
|
||||
data = newData |
|
||||
} |
|
||||
|
|
||||
prefixFieldClashes(data, f.FieldMap) |
|
||||
|
|
||||
timestampFormat := f.TimestampFormat |
|
||||
if timestampFormat == "" { |
|
||||
timestampFormat = defaultTimestampFormat |
|
||||
} |
|
||||
|
|
||||
if !f.DisableTimestamp { |
|
||||
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) |
|
||||
} |
|
||||
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message |
|
||||
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() |
|
||||
|
|
||||
serialized, err := json.Marshal(data) |
|
||||
if err != nil { |
|
||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) |
|
||||
} |
|
||||
return append(serialized, '\n'), nil |
|
||||
} |
|
@ -1,337 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"io" |
|
||||
"os" |
|
||||
"sync" |
|
||||
"sync/atomic" |
|
||||
"time" |
|
||||
) |
|
||||
|
|
||||
type Logger struct { |
|
||||
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
|
||||
// file, or leave it default which is `os.Stderr`. You can also set this to
|
|
||||
// something more adventorous, such as logging to Kafka.
|
|
||||
Out io.Writer |
|
||||
// Hooks for the logger instance. These allow firing events based on logging
|
|
||||
// levels and log entries. For example, to send errors to an error tracking
|
|
||||
// service, log to StatsD or dump the core on fatal errors.
|
|
||||
Hooks LevelHooks |
|
||||
// All log entries pass through the formatter before logged to Out. The
|
|
||||
// included formatters are `TextFormatter` and `JSONFormatter` for which
|
|
||||
// TextFormatter is the default. In development (when a TTY is attached) it
|
|
||||
// logs with colors, but to a file it wouldn't. You can easily implement your
|
|
||||
// own that implements the `Formatter` interface, see the `README` or included
|
|
||||
// formatters for examples.
|
|
||||
Formatter Formatter |
|
||||
// The logging level the logger should log at. This is typically (and defaults
|
|
||||
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
|
|
||||
// logged.
|
|
||||
Level Level |
|
||||
// Used to sync writing to the log. Locking is enabled by Default
|
|
||||
mu MutexWrap |
|
||||
// Reusable empty entry
|
|
||||
entryPool sync.Pool |
|
||||
} |
|
||||
|
|
||||
type MutexWrap struct { |
|
||||
lock sync.Mutex |
|
||||
disabled bool |
|
||||
} |
|
||||
|
|
||||
func (mw *MutexWrap) Lock() { |
|
||||
if !mw.disabled { |
|
||||
mw.lock.Lock() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (mw *MutexWrap) Unlock() { |
|
||||
if !mw.disabled { |
|
||||
mw.lock.Unlock() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (mw *MutexWrap) Disable() { |
|
||||
mw.disabled = true |
|
||||
} |
|
||||
|
|
||||
// Creates a new logger. Configuration should be set by changing `Formatter`,
|
|
||||
// `Out` and `Hooks` directly on the default logger instance. You can also just
|
|
||||
// instantiate your own:
|
|
||||
//
|
|
||||
// var log = &Logger{
|
|
||||
// Out: os.Stderr,
|
|
||||
// Formatter: new(JSONFormatter),
|
|
||||
// Hooks: make(LevelHooks),
|
|
||||
// Level: logrus.DebugLevel,
|
|
||||
// }
|
|
||||
//
|
|
||||
// It's recommended to make this a global instance called `log`.
|
|
||||
func New() *Logger { |
|
||||
return &Logger{ |
|
||||
Out: os.Stderr, |
|
||||
Formatter: new(TextFormatter), |
|
||||
Hooks: make(LevelHooks), |
|
||||
Level: InfoLevel, |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) newEntry() *Entry { |
|
||||
entry, ok := logger.entryPool.Get().(*Entry) |
|
||||
if ok { |
|
||||
return entry |
|
||||
} |
|
||||
return NewEntry(logger) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) releaseEntry(entry *Entry) { |
|
||||
logger.entryPool.Put(entry) |
|
||||
} |
|
||||
|
|
||||
// Adds a field to the log entry, note that it doesn't log until you call
|
|
||||
// Debug, Print, Info, Warn, Error, Fatal or Panic. It only creates a log entry.
|
|
||||
// If you want multiple fields, use `WithFields`.
|
|
||||
func (logger *Logger) WithField(key string, value interface{}) *Entry { |
|
||||
entry := logger.newEntry() |
|
||||
defer logger.releaseEntry(entry) |
|
||||
return entry.WithField(key, value) |
|
||||
} |
|
||||
|
|
||||
// Adds a struct of fields to the log entry. All it does is call `WithField` for
|
|
||||
// each `Field`.
|
|
||||
func (logger *Logger) WithFields(fields Fields) *Entry { |
|
||||
entry := logger.newEntry() |
|
||||
defer logger.releaseEntry(entry) |
|
||||
return entry.WithFields(fields) |
|
||||
} |
|
||||
|
|
||||
// Add an error as single field to the log entry. All it does is call
|
|
||||
// `WithError` for the given `error`.
|
|
||||
func (logger *Logger) WithError(err error) *Entry { |
|
||||
entry := logger.newEntry() |
|
||||
defer logger.releaseEntry(entry) |
|
||||
return entry.WithError(err) |
|
||||
} |
|
||||
|
|
||||
// Overrides the time of the log entry.
|
|
||||
func (logger *Logger) WithTime(t time.Time) *Entry { |
|
||||
entry := logger.newEntry() |
|
||||
defer logger.releaseEntry(entry) |
|
||||
return entry.WithTime(t) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Debugf(format string, args ...interface{}) { |
|
||||
if logger.level() >= DebugLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Debugf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Infof(format string, args ...interface{}) { |
|
||||
if logger.level() >= InfoLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Infof(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Printf(format string, args ...interface{}) { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Printf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warnf(format string, args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warnf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warningf(format string, args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warnf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Errorf(format string, args ...interface{}) { |
|
||||
if logger.level() >= ErrorLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Errorf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Fatalf(format string, args ...interface{}) { |
|
||||
if logger.level() >= FatalLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Fatalf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Panicf(format string, args ...interface{}) { |
|
||||
if logger.level() >= PanicLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Panicf(format, args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Debug(args ...interface{}) { |
|
||||
if logger.level() >= DebugLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Debug(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Info(args ...interface{}) { |
|
||||
if logger.level() >= InfoLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Info(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Print(args ...interface{}) { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Info(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warn(args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warn(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warning(args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warn(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Error(args ...interface{}) { |
|
||||
if logger.level() >= ErrorLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Error(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Fatal(args ...interface{}) { |
|
||||
if logger.level() >= FatalLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Fatal(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Panic(args ...interface{}) { |
|
||||
if logger.level() >= PanicLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Panic(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Debugln(args ...interface{}) { |
|
||||
if logger.level() >= DebugLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Debugln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Infoln(args ...interface{}) { |
|
||||
if logger.level() >= InfoLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Infoln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Println(args ...interface{}) { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Println(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warnln(args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warnln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Warningln(args ...interface{}) { |
|
||||
if logger.level() >= WarnLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Warnln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Errorln(args ...interface{}) { |
|
||||
if logger.level() >= ErrorLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Errorln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Fatalln(args ...interface{}) { |
|
||||
if logger.level() >= FatalLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Fatalln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
Exit(1) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) Panicln(args ...interface{}) { |
|
||||
if logger.level() >= PanicLevel { |
|
||||
entry := logger.newEntry() |
|
||||
entry.Panicln(args...) |
|
||||
logger.releaseEntry(entry) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
//When file is opened with appending mode, it's safe to
|
|
||||
//write concurrently to a file (within 4k message on Linux).
|
|
||||
//In these cases user can choose to disable the lock.
|
|
||||
func (logger *Logger) SetNoLock() { |
|
||||
logger.mu.Disable() |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) level() Level { |
|
||||
return Level(atomic.LoadUint32((*uint32)(&logger.Level))) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) SetLevel(level Level) { |
|
||||
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) SetOutput(out io.Writer) { |
|
||||
logger.mu.Lock() |
|
||||
defer logger.mu.Unlock() |
|
||||
logger.Out = out |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) AddHook(hook Hook) { |
|
||||
logger.mu.Lock() |
|
||||
defer logger.mu.Unlock() |
|
||||
logger.Hooks.Add(hook) |
|
||||
} |
|
@ -1,143 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"fmt" |
|
||||
"log" |
|
||||
"strings" |
|
||||
) |
|
||||
|
|
||||
// Fields type, used to pass to `WithFields`.
|
|
||||
type Fields map[string]interface{} |
|
||||
|
|
||||
// Level type
|
|
||||
type Level uint32 |
|
||||
|
|
||||
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
|
|
||||
func (level Level) String() string { |
|
||||
switch level { |
|
||||
case DebugLevel: |
|
||||
return "debug" |
|
||||
case InfoLevel: |
|
||||
return "info" |
|
||||
case WarnLevel: |
|
||||
return "warning" |
|
||||
case ErrorLevel: |
|
||||
return "error" |
|
||||
case FatalLevel: |
|
||||
return "fatal" |
|
||||
case PanicLevel: |
|
||||
return "panic" |
|
||||
} |
|
||||
|
|
||||
return "unknown" |
|
||||
} |
|
||||
|
|
||||
// ParseLevel takes a string level and returns the Logrus log level constant.
|
|
||||
func ParseLevel(lvl string) (Level, error) { |
|
||||
switch strings.ToLower(lvl) { |
|
||||
case "panic": |
|
||||
return PanicLevel, nil |
|
||||
case "fatal": |
|
||||
return FatalLevel, nil |
|
||||
case "error": |
|
||||
return ErrorLevel, nil |
|
||||
case "warn", "warning": |
|
||||
return WarnLevel, nil |
|
||||
case "info": |
|
||||
return InfoLevel, nil |
|
||||
case "debug": |
|
||||
return DebugLevel, nil |
|
||||
} |
|
||||
|
|
||||
var l Level |
|
||||
return l, fmt.Errorf("not a valid logrus Level: %q", lvl) |
|
||||
} |
|
||||
|
|
||||
// A constant exposing all logging levels
|
|
||||
var AllLevels = []Level{ |
|
||||
PanicLevel, |
|
||||
FatalLevel, |
|
||||
ErrorLevel, |
|
||||
WarnLevel, |
|
||||
InfoLevel, |
|
||||
DebugLevel, |
|
||||
} |
|
||||
|
|
||||
// These are the different logging levels. You can set the logging level to log
|
|
||||
// on your instance of logger, obtained with `logrus.New()`.
|
|
||||
const ( |
|
||||
// PanicLevel level, highest level of severity. Logs and then calls panic with the
|
|
||||
// message passed to Debug, Info, ...
|
|
||||
PanicLevel Level = iota |
|
||||
// FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
|
|
||||
// logging level is set to Panic.
|
|
||||
FatalLevel |
|
||||
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
|
|
||||
// Commonly used for hooks to send errors to an error tracking service.
|
|
||||
ErrorLevel |
|
||||
// WarnLevel level. Non-critical entries that deserve eyes.
|
|
||||
WarnLevel |
|
||||
// InfoLevel level. General operational entries about what's going on inside the
|
|
||||
// application.
|
|
||||
InfoLevel |
|
||||
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
|
|
||||
DebugLevel |
|
||||
) |
|
||||
|
|
||||
// Won't compile if StdLogger can't be realized by a log.Logger
|
|
||||
var ( |
|
||||
_ StdLogger = &log.Logger{} |
|
||||
_ StdLogger = &Entry{} |
|
||||
_ StdLogger = &Logger{} |
|
||||
) |
|
||||
|
|
||||
// StdLogger is what your logrus-enabled library should take, that way
|
|
||||
// it'll accept a stdlib logger and a logrus logger. There's no standard
|
|
||||
// interface, this is the closest we get, unfortunately.
|
|
||||
type StdLogger interface { |
|
||||
Print(...interface{}) |
|
||||
Printf(string, ...interface{}) |
|
||||
Println(...interface{}) |
|
||||
|
|
||||
Fatal(...interface{}) |
|
||||
Fatalf(string, ...interface{}) |
|
||||
Fatalln(...interface{}) |
|
||||
|
|
||||
Panic(...interface{}) |
|
||||
Panicf(string, ...interface{}) |
|
||||
Panicln(...interface{}) |
|
||||
} |
|
||||
|
|
||||
// The FieldLogger interface generalizes the Entry and Logger types
|
|
||||
type FieldLogger interface { |
|
||||
WithField(key string, value interface{}) *Entry |
|
||||
WithFields(fields Fields) *Entry |
|
||||
WithError(err error) *Entry |
|
||||
|
|
||||
Debugf(format string, args ...interface{}) |
|
||||
Infof(format string, args ...interface{}) |
|
||||
Printf(format string, args ...interface{}) |
|
||||
Warnf(format string, args ...interface{}) |
|
||||
Warningf(format string, args ...interface{}) |
|
||||
Errorf(format string, args ...interface{}) |
|
||||
Fatalf(format string, args ...interface{}) |
|
||||
Panicf(format string, args ...interface{}) |
|
||||
|
|
||||
Debug(args ...interface{}) |
|
||||
Info(args ...interface{}) |
|
||||
Print(args ...interface{}) |
|
||||
Warn(args ...interface{}) |
|
||||
Warning(args ...interface{}) |
|
||||
Error(args ...interface{}) |
|
||||
Fatal(args ...interface{}) |
|
||||
Panic(args ...interface{}) |
|
||||
|
|
||||
Debugln(args ...interface{}) |
|
||||
Infoln(args ...interface{}) |
|
||||
Println(args ...interface{}) |
|
||||
Warnln(args ...interface{}) |
|
||||
Warningln(args ...interface{}) |
|
||||
Errorln(args ...interface{}) |
|
||||
Fatalln(args ...interface{}) |
|
||||
Panicln(args ...interface{}) |
|
||||
} |
|
@ -1,10 +0,0 @@ |
|||||
// +build darwin freebsd openbsd netbsd dragonfly
|
|
||||
// +build !appengine,!gopherjs
|
|
||||
|
|
||||
package logrus |
|
||||
|
|
||||
import "golang.org/x/sys/unix" |
|
||||
|
|
||||
const ioctlReadTermios = unix.TIOCGETA |
|
||||
|
|
||||
type Termios unix.Termios |
|
@ -1,11 +0,0 @@ |
|||||
// +build appengine gopherjs
|
|
||||
|
|
||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"io" |
|
||||
) |
|
||||
|
|
||||
func checkIfTerminal(w io.Writer) bool { |
|
||||
return true |
|
||||
} |
|
@ -1,19 +0,0 @@ |
|||||
// +build !appengine,!gopherjs
|
|
||||
|
|
||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"io" |
|
||||
"os" |
|
||||
|
|
||||
"golang.org/x/crypto/ssh/terminal" |
|
||||
) |
|
||||
|
|
||||
func checkIfTerminal(w io.Writer) bool { |
|
||||
switch v := w.(type) { |
|
||||
case *os.File: |
|
||||
return terminal.IsTerminal(int(v.Fd())) |
|
||||
default: |
|
||||
return false |
|
||||
} |
|
||||
} |
|
@ -1,14 +0,0 @@ |
|||||
// Based on ssh/terminal:
|
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
|
||||
// Use of this source code is governed by a BSD-style
|
|
||||
// license that can be found in the LICENSE file.
|
|
||||
|
|
||||
// +build !appengine,!gopherjs
|
|
||||
|
|
||||
package logrus |
|
||||
|
|
||||
import "golang.org/x/sys/unix" |
|
||||
|
|
||||
const ioctlReadTermios = unix.TCGETS |
|
||||
|
|
||||
type Termios unix.Termios |
|
@ -1,195 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"bytes" |
|
||||
"fmt" |
|
||||
"sort" |
|
||||
"strings" |
|
||||
"sync" |
|
||||
"time" |
|
||||
) |
|
||||
|
|
||||
const ( |
|
||||
nocolor = 0 |
|
||||
red = 31 |
|
||||
green = 32 |
|
||||
yellow = 33 |
|
||||
blue = 36 |
|
||||
gray = 37 |
|
||||
) |
|
||||
|
|
||||
var ( |
|
||||
baseTimestamp time.Time |
|
||||
emptyFieldMap FieldMap |
|
||||
) |
|
||||
|
|
||||
func init() { |
|
||||
baseTimestamp = time.Now() |
|
||||
} |
|
||||
|
|
||||
// TextFormatter formats logs into text
|
|
||||
type TextFormatter struct { |
|
||||
// Set to true to bypass checking for a TTY before outputting colors.
|
|
||||
ForceColors bool |
|
||||
|
|
||||
// Force disabling colors.
|
|
||||
DisableColors bool |
|
||||
|
|
||||
// Disable timestamp logging. useful when output is redirected to logging
|
|
||||
// system that already adds timestamps.
|
|
||||
DisableTimestamp bool |
|
||||
|
|
||||
// Enable logging the full timestamp when a TTY is attached instead of just
|
|
||||
// the time passed since beginning of execution.
|
|
||||
FullTimestamp bool |
|
||||
|
|
||||
// TimestampFormat to use for display when a full timestamp is printed
|
|
||||
TimestampFormat string |
|
||||
|
|
||||
// The fields are sorted by default for a consistent output. For applications
|
|
||||
// that log extremely frequently and don't use the JSON formatter this may not
|
|
||||
// be desired.
|
|
||||
DisableSorting bool |
|
||||
|
|
||||
// Disables the truncation of the level text to 4 characters.
|
|
||||
DisableLevelTruncation bool |
|
||||
|
|
||||
// QuoteEmptyFields will wrap empty fields in quotes if true
|
|
||||
QuoteEmptyFields bool |
|
||||
|
|
||||
// Whether the logger's out is to a terminal
|
|
||||
isTerminal bool |
|
||||
|
|
||||
// FieldMap allows users to customize the names of keys for default fields.
|
|
||||
// As an example:
|
|
||||
// formatter := &TextFormatter{
|
|
||||
// FieldMap: FieldMap{
|
|
||||
// FieldKeyTime: "@timestamp",
|
|
||||
// FieldKeyLevel: "@level",
|
|
||||
// FieldKeyMsg: "@message"}}
|
|
||||
FieldMap FieldMap |
|
||||
|
|
||||
sync.Once |
|
||||
} |
|
||||
|
|
||||
func (f *TextFormatter) init(entry *Entry) { |
|
||||
if entry.Logger != nil { |
|
||||
f.isTerminal = checkIfTerminal(entry.Logger.Out) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// Format renders a single log entry
|
|
||||
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { |
|
||||
prefixFieldClashes(entry.Data, f.FieldMap) |
|
||||
|
|
||||
keys := make([]string, 0, len(entry.Data)) |
|
||||
for k := range entry.Data { |
|
||||
keys = append(keys, k) |
|
||||
} |
|
||||
|
|
||||
if !f.DisableSorting { |
|
||||
sort.Strings(keys) |
|
||||
} |
|
||||
|
|
||||
var b *bytes.Buffer |
|
||||
if entry.Buffer != nil { |
|
||||
b = entry.Buffer |
|
||||
} else { |
|
||||
b = &bytes.Buffer{} |
|
||||
} |
|
||||
|
|
||||
f.Do(func() { f.init(entry) }) |
|
||||
|
|
||||
isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors |
|
||||
|
|
||||
timestampFormat := f.TimestampFormat |
|
||||
if timestampFormat == "" { |
|
||||
timestampFormat = defaultTimestampFormat |
|
||||
} |
|
||||
if isColored { |
|
||||
f.printColored(b, entry, keys, timestampFormat) |
|
||||
} else { |
|
||||
if !f.DisableTimestamp { |
|
||||
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyTime), entry.Time.Format(timestampFormat)) |
|
||||
} |
|
||||
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyLevel), entry.Level.String()) |
|
||||
if entry.Message != "" { |
|
||||
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyMsg), entry.Message) |
|
||||
} |
|
||||
for _, key := range keys { |
|
||||
f.appendKeyValue(b, key, entry.Data[key]) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
b.WriteByte('\n') |
|
||||
return b.Bytes(), nil |
|
||||
} |
|
||||
|
|
||||
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { |
|
||||
var levelColor int |
|
||||
switch entry.Level { |
|
||||
case DebugLevel: |
|
||||
levelColor = gray |
|
||||
case WarnLevel: |
|
||||
levelColor = yellow |
|
||||
case ErrorLevel, FatalLevel, PanicLevel: |
|
||||
levelColor = red |
|
||||
default: |
|
||||
levelColor = blue |
|
||||
} |
|
||||
|
|
||||
levelText := strings.ToUpper(entry.Level.String()) |
|
||||
if !f.DisableLevelTruncation { |
|
||||
levelText = levelText[0:4] |
|
||||
} |
|
||||
|
|
||||
if f.DisableTimestamp { |
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) |
|
||||
} else if !f.FullTimestamp { |
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message) |
|
||||
} else { |
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) |
|
||||
} |
|
||||
for _, k := range keys { |
|
||||
v := entry.Data[k] |
|
||||
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) |
|
||||
f.appendValue(b, v) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
func (f *TextFormatter) needsQuoting(text string) bool { |
|
||||
if f.QuoteEmptyFields && len(text) == 0 { |
|
||||
return true |
|
||||
} |
|
||||
for _, ch := range text { |
|
||||
if !((ch >= 'a' && ch <= 'z') || |
|
||||
(ch >= 'A' && ch <= 'Z') || |
|
||||
(ch >= '0' && ch <= '9') || |
|
||||
ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { |
|
||||
return true |
|
||||
} |
|
||||
} |
|
||||
return false |
|
||||
} |
|
||||
|
|
||||
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { |
|
||||
if b.Len() > 0 { |
|
||||
b.WriteByte(' ') |
|
||||
} |
|
||||
b.WriteString(key) |
|
||||
b.WriteByte('=') |
|
||||
f.appendValue(b, value) |
|
||||
} |
|
||||
|
|
||||
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { |
|
||||
stringVal, ok := value.(string) |
|
||||
if !ok { |
|
||||
stringVal = fmt.Sprint(value) |
|
||||
} |
|
||||
|
|
||||
if !f.needsQuoting(stringVal) { |
|
||||
b.WriteString(stringVal) |
|
||||
} else { |
|
||||
b.WriteString(fmt.Sprintf("%q", stringVal)) |
|
||||
} |
|
||||
} |
|
@ -1,62 +0,0 @@ |
|||||
package logrus |
|
||||
|
|
||||
import ( |
|
||||
"bufio" |
|
||||
"io" |
|
||||
"runtime" |
|
||||
) |
|
||||
|
|
||||
func (logger *Logger) Writer() *io.PipeWriter { |
|
||||
return logger.WriterLevel(InfoLevel) |
|
||||
} |
|
||||
|
|
||||
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { |
|
||||
return NewEntry(logger).WriterLevel(level) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) Writer() *io.PipeWriter { |
|
||||
return entry.WriterLevel(InfoLevel) |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { |
|
||||
reader, writer := io.Pipe() |
|
||||
|
|
||||
var printFunc func(args ...interface{}) |
|
||||
|
|
||||
switch level { |
|
||||
case DebugLevel: |
|
||||
printFunc = entry.Debug |
|
||||
case InfoLevel: |
|
||||
printFunc = entry.Info |
|
||||
case WarnLevel: |
|
||||
printFunc = entry.Warn |
|
||||
case ErrorLevel: |
|
||||
printFunc = entry.Error |
|
||||
case FatalLevel: |
|
||||
printFunc = entry.Fatal |
|
||||
case PanicLevel: |
|
||||
printFunc = entry.Panic |
|
||||
default: |
|
||||
printFunc = entry.Print |
|
||||
} |
|
||||
|
|
||||
go entry.writerScanner(reader, printFunc) |
|
||||
runtime.SetFinalizer(writer, writerFinalizer) |
|
||||
|
|
||||
return writer |
|
||||
} |
|
||||
|
|
||||
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { |
|
||||
scanner := bufio.NewScanner(reader) |
|
||||
for scanner.Scan() { |
|
||||
printFunc(scanner.Text()) |
|
||||
} |
|
||||
if err := scanner.Err(); err != nil { |
|
||||
entry.Errorf("Error while reading from Writer: %s", err) |
|
||||
} |
|
||||
reader.Close() |
|
||||
} |
|
||||
|
|
||||
func writerFinalizer(writer *io.PipeWriter) { |
|
||||
writer.Close() |
|
||||
} |
|
Loading…
Reference in new issue