apex / log

Structured logging package for Go.
MIT License
1.36k stars 110 forks source link

Support nil *log.Entry #96

Closed titpetric closed 3 years ago

titpetric commented 3 years ago

I'd like if Entry functions would support a nil, currently they panic (case 2 below).

package main

import (
    "errors"
    "github.com/apex/log"
)

func main() {
    defer func() {
        recover()
    }()

    var err = errors.New("Hello world")

    var logctx *log.Entry
    logctx = log.WithError(err)
    logctx.Error("*Testing nil log.Entry 1 OK")

    logctx = nil
    logctx.WithError(err).Error("*Testing nil log.Entry 2 OK")
}

This would support lazy log. Entry instances, where an utility log function could take the log context as parameter, but the caller wouldn't need to provide one. A cut down example would look like this:

func errorResponse(ctx context.Context, w http.ResponseWriter, code int, err error, message string, logctx *log.Entry) {
        if err != nil {
                apm.CaptureError(ctx, err).Send()
                w.WriteHeader(code)
                logctx.WithError(err).Error(message)
        }
}

The logctx could bind basic http request variables, or depending on context (non-http request), it could be omitted entirely.

titpetric commented 3 years ago

I'm closing this, as the work-around is too trivial to warrant an open issue.