Skip to content

Commit

Permalink
Merge pull request #2 from Windscribe/sync-v1.33.0
Browse files Browse the repository at this point in the history
Sync v1.33.0
  • Loading branch information
cuonglm authored Dec 6, 2024
2 parents e6aa153 + 68850d2 commit cc6e8ef
Show file tree
Hide file tree
Showing 46 changed files with 1,980 additions and 241 deletions.
19 changes: 14 additions & 5 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ jobs:
test:
strategy:
matrix:
go-version: [1.18.x, 1.19.x]
go-version: [1.18.x, 1.21.x]
os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v3
- uses: actions/cache@v3
uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
Expand All @@ -24,4 +24,13 @@ jobs:
run: go test -race -bench . -benchmem ./...
- name: Test CBOR
run: go test -tags binary_log ./...

coverage:
runs-on: ubuntu-latest
steps:
- name: Update coverage report
uses: ncruces/go-coverage-report@main
with:
report: 'true'
chart: 'true'
amend: 'true'
continue-on-error: true
96 changes: 69 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 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)
[![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://github.com/rs/zerolog/actions/workflows/test.yml/badge.svg)](https://github.com/rs/zerolog/actions/workflows/test.yml) [![Go Coverage](https://github.com/rs/zerolog/wiki/coverage.svg)](https://raw.githack.com/wiki/rs/zerolog/coverage.html)

The zerolog package provides a fast and simple logger dedicated to JSON output.

Expand Down Expand Up @@ -60,7 +60,7 @@ func main() {
// 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*
> Note: The default log level for `log.Print` is *trace*
### Contextual Logging

Expand Down Expand Up @@ -412,15 +412,7 @@ Equivalent of `Lshortfile`:

```go
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
return filepath.Base(file) + ":" + strconv.Itoa(line)
}
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
Expand Down Expand Up @@ -513,25 +505,53 @@ stdlog.Print("hello world")

### context.Context integration

The `Logger` instance could be attached to `context.Context` values with `logger.WithContext(ctx)`
and extracted from it using `zerolog.Ctx(ctx)`.
Go contexts are commonly passed throughout Go code, and this can help you pass
your Logger into places it might otherwise be hard to inject. The `Logger`
instance may be attached to Go context (`context.Context`) using
`Logger.WithContext(ctx)` and extracted from it using `zerolog.Ctx(ctx)`.
For example:

Example to add logger to context:
```go
// this code attach logger instance to context fields
ctx := context.Background()
logger := zerolog.New(os.Stdout)
ctx = logger.WithContext(ctx)
someFunc(ctx)
func f() {
logger := zerolog.New(os.Stdout)
ctx := context.Background()

// Attach the Logger to the context.Context
ctx = logger.WithContext(ctx)
someFunc(ctx)
}

func someFunc(ctx context.Context) {
// Get Logger from the go Context. if it's nil, then
// `zerolog.DefaultContextLogger` is returned, if
// `DefaultContextLogger` is nil, then a disabled logger is returned.
logger := zerolog.Ctx(ctx)
logger.Info().Msg("Hello")
}
```

Extracting logger from context:
A second form of `context.Context` integration allows you to pass the current
context.Context into the logged event, and retrieve it from hooks. This can be
useful to log trace and span IDs or other information stored in the go context,
and facilitates the unification of logging and tracing in some systems:

```go
func someFunc(ctx context.Context) {
// get logger from context. if it's nill, then `zerolog.DefaultContextLogger` is returned,
// if `DefaultContextLogger` is nil, then disabled logger returned.
logger := zerolog.Ctx(ctx)
logger.Info().Msg("Hello")
type TracingHook struct{}

func (h TracingHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
ctx := e.GetCtx()
spanId := getSpanIdFromContext(ctx) // as per your tracing framework
e.Str("span-id", spanId)
}

func f() {
// Setup the logger
logger := zerolog.New(os.Stdout)
logger = logger.Hook(TracingHook{})

ctx := context.Background()
// Use the Ctx function to make the context available to the hook
logger.Info().Ctx(ctx).Msg("Hello")
}
```

Expand Down Expand Up @@ -618,10 +638,14 @@ Some settings can be changed and will be applied to all loggers:
* `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 `zerolog.TimeFormatUnix`, `zerolog.TimeFormatUnixMs` or `zerolog.TimeFormatUnixMicro`, times are formated as UNIX timestamp.
* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zerolog.TimeFormatUnix`, `zerolog.TimeFormatUnixMs` or `zerolog.TimeFormatUnixMicro`, times are formatted as UNIX timestamp.
* `zerolog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`).
* `zerolog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`).
* `zerolog.ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.
* `zerolog.FloatingPointPrecision`: If set to a value other than -1, controls the number
of digits when formatting float numbers in JSON. See
[strconv.FormatFloat](https://pkg.go.dev/strconv#FormatFloat)
for more details.

## Field Types

Expand Down Expand Up @@ -666,7 +690,7 @@ with zerolog library is [CSD](https://github.com/toravir/csd/).

## Benchmarks

See [logbench](http://hackemist.com/logbench/) for more comprehensive and up-to-date benchmarks.
See [logbench](http://bench.zerolog.io/) for more comprehensive and up-to-date benchmarks.

All operations are allocation free (those numbers *include* JSON encoding):

Expand Down Expand Up @@ -727,6 +751,8 @@ Log a static string, without any context or `printf`-style templating:

## Caveats

### Field duplication

Note that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:

```go
Expand All @@ -738,3 +764,19 @@ logger.Info().
```

In this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt.

### Concurrency safety

Be careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger:

```go
func handler(w http.ResponseWriter, r *http.Request) {
// Create a child logger for concurrency safety
logger := log.Logger.With().Logger()

// Add context fields, for example User-Agent from HTTP headers
logger.UpdateContext(func(c zerolog.Context) zerolog.Context {
...
})
}
```
6 changes: 3 additions & 3 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,13 @@ func (a *Array) Uint64(i uint64) *Array {

// Float32 appends f as a float32 to the array.
func (a *Array) Float32(f float32) *Array {
a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f)
a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f, FloatingPointPrecision)
return a
}

// Float64 appends f as a float64 to the array.
func (a *Array) Float64(f float64) *Array {
a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f)
a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f, FloatingPointPrecision)
return a
}

Expand All @@ -201,7 +201,7 @@ func (a *Array) Time(t time.Time) *Array {

// Dur appends d to the array.
func (a *Array) Dur(d time.Duration) *Array {
a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger)
a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision)
return a
}

Expand Down
29 changes: 19 additions & 10 deletions benchmark_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package zerolog

import (
"context"
"errors"
"io/ioutil"
"io"
"net"
"testing"
"time"
Expand All @@ -14,7 +15,7 @@ var (
)

func BenchmarkLogEmpty(b *testing.B) {
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Expand All @@ -24,7 +25,7 @@ func BenchmarkLogEmpty(b *testing.B) {
}

func BenchmarkDisabled(b *testing.B) {
logger := New(ioutil.Discard).Level(Disabled)
logger := New(io.Discard).Level(Disabled)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Expand All @@ -34,7 +35,7 @@ func BenchmarkDisabled(b *testing.B) {
}

func BenchmarkInfo(b *testing.B) {
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Expand All @@ -44,7 +45,7 @@ func BenchmarkInfo(b *testing.B) {
}

func BenchmarkContextFields(b *testing.B) {
logger := New(ioutil.Discard).With().
logger := New(io.Discard).With().
Str("string", "four!").
Time("time", time.Time{}).
Int("int", 123).
Expand All @@ -59,7 +60,7 @@ func BenchmarkContextFields(b *testing.B) {
}

func BenchmarkContextAppend(b *testing.B) {
logger := New(ioutil.Discard).With().
logger := New(io.Discard).With().
Str("foo", "bar").
Logger()
b.ResetTimer()
Expand All @@ -71,7 +72,7 @@ func BenchmarkContextAppend(b *testing.B) {
}

func BenchmarkLogFields(b *testing.B) {
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Expand Down Expand Up @@ -101,7 +102,7 @@ func BenchmarkLogArrayObject(b *testing.B) {
obj1 := obj{"a", "b", 2}
obj2 := obj{"c", "d", 3}
obj3 := obj{"e", "f", 4}
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Expand Down Expand Up @@ -160,6 +161,7 @@ func BenchmarkLogFieldType(b *testing.B) {
{"a", "a", 0},
}
errs := []error{errors.New("a"), errors.New("b"), errors.New("c"), errors.New("d"), errors.New("e")}
ctx := context.Background()
types := map[string]func(e *Event) *Event{
"Bool": func(e *Event) *Event {
return e.Bool("k", bools[0])
Expand Down Expand Up @@ -191,6 +193,9 @@ func BenchmarkLogFieldType(b *testing.B) {
"Errs": func(e *Event) *Event {
return e.Errs("k", errs)
},
"Ctx": func(e *Event) *Event {
return e.Ctx(ctx)
},
"Time": func(e *Event) *Event {
return e.Time("k", times[0])
},
Expand Down Expand Up @@ -219,7 +224,7 @@ func BenchmarkLogFieldType(b *testing.B) {
return e.Object("k", objects[0])
},
}
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
for name := range types {
f := types[name]
Expand Down Expand Up @@ -284,6 +289,7 @@ func BenchmarkContextFieldType(b *testing.B) {
{"a", "a", 0},
}
errs := []error{errors.New("a"), errors.New("b"), errors.New("c"), errors.New("d"), errors.New("e")}
ctx := context.Background()
types := map[string]func(c Context) Context{
"Bool": func(c Context) Context {
return c.Bool("k", bools[0])
Expand Down Expand Up @@ -318,6 +324,9 @@ func BenchmarkContextFieldType(b *testing.B) {
"Errs": func(c Context) Context {
return c.Errs("k", errs)
},
"Ctx": func(c Context) Context {
return c.Ctx(ctx)
},
"Time": func(c Context) Context {
return c.Time("k", times[0])
},
Expand Down Expand Up @@ -349,7 +358,7 @@ func BenchmarkContextFieldType(b *testing.B) {
return c.Timestamp()
},
}
logger := New(ioutil.Discard)
logger := New(io.Discard)
b.ResetTimer()
for name := range types {
f := types[name]
Expand Down
1 change: 0 additions & 1 deletion binary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"errors"
"fmt"

// "io/ioutil"
stdlog "log"
"time"
)
Expand Down
2 changes: 2 additions & 0 deletions cmd/lint/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Zerolog Lint

**DEPRECATED: In favor of https://github.com/ykadowak/zerologlint which is integrated with `go vet` and [golangci-lint](https://golangci-lint.run/).**

This is a basic linter that checks for missing log event finishers. Finds errors like: `log.Error().Int64("userID": 5)` - missing the `Msg`/`Msgf` finishers.

## Problem
Expand Down
Loading

0 comments on commit cc6e8ef

Please sign in to comment.