Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix caller in logs #1176

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions cmd/image-builder/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type ctxKey int
const (
requestIdCtx ctxKey = iota
insightsRequestIdCtx ctxKey = iota
requestDataCtx ctxKey = iota
)

// Use request id from the standard context and add it to the message as a field.
Expand All @@ -36,6 +37,10 @@ func (h *ctxHook) Fire(e *logrus.Entry) error {
if e.Context != nil {
e.Data["request_id"] = e.Context.Value(requestIdCtx)
e.Data["insights_id"] = e.Context.Value(insightsRequestIdCtx)
rd := e.Context.Value(requestDataCtx).(logrus.Fields)
for k, v := range rd {
e.Data[k] = v
}
}

return nil
Expand All @@ -59,27 +64,34 @@ func requestIdExtractMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
iid = random.String(12)
}

// create fields stored with every log statement
rd := logrus.Fields{
"method": c.Request().Method,
"path": c.Path(),
}
for _, key := range c.ParamNames() {
// protect existing and the most important fields
if _, ok := rd[key]; !(ok || key == "msg" || key == "level") {
rd[key] = c.Param(key)
}
}

// store it in a standard context
ctx := c.Request().Context()
ctx = context.WithValue(ctx, requestIdCtx, rid)
ctx = context.WithValue(ctx, insightsRequestIdCtx, iid)
ctx = context.WithValue(ctx, requestDataCtx, rd)
c.SetRequest(c.Request().WithContext(ctx))

f := logrus.Fields{"method": c.Request().Method, "path": c.Path()}
for _, key := range c.ParamNames() {
f[key] = c.Param(key)
}

// and set echo logger to be context logger
ctxLogger := logrus.StandardLogger()
c.SetLogger(&common.EchoLogrusLogger{
Logger: ctxLogger,
Ctx: ctx,
Fields: f,
})

if !SkipPath(c.Path()) {
c.Logger().Debugf("Started request")
ctxLogger.WithContext(ctx).WithFields(rd).Debugf("Started request")
}

return next(c)
Expand Down
3 changes: 2 additions & 1 deletion cmd/image-builder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ func main() {
if values.Error != nil {
fields["error"] = values.Error
}
logrus.WithFields(fields).Infof("Processed request %s %s", values.Method, values.URI)
logrus.WithContext(c.Request().Context()).
WithFields(fields).Infof("Processed request %s %s", values.Method, values.URI)

return nil
},
Expand Down
95 changes: 71 additions & 24 deletions internal/common/echo_logrus.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,27 @@ import (
"context"
"encoding/json"
"io"
"runtime"

"github.com/labstack/gommon/log"
"github.com/sirupsen/logrus"
)

type ctxKey int

const (
LoggingFrameCtx ctxKey = iota
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a good practice not to export context key types and values so other packages cannot modify the values. Here it is a mix - you export the value but not the type.


// EchoLogrusLogger extend logrus.Logger
type EchoLogrusLogger struct {
*logrus.Logger
Ctx context.Context
Fields logrus.Fields
Ctx context.Context
}

var commonLogger = &EchoLogrusLogger{
Logger: logrus.StandardLogger(),
Ctx: context.Background(),
Fields: logrus.Fields{},
}

func Logger() *EchoLogrusLogger {
Expand All @@ -41,6 +46,48 @@ func toEchoLevel(level logrus.Level) log.Lvl {
return log.OFF
}

// add the context and caller to the fields
// as logrus will report "echo_logrus.go" otherwise
func (l *EchoLogrusLogger) fixCaller() *logrus.Entry {
rpc := make([]uintptr, 1)
// fixCaller is always 3 frames below the calling context
n := runtime.Callers(3, rpc[:])
if n < 1 {
return l.Logger.WithContext(l.Ctx)
}
frame, _ := runtime.CallersFrames(rpc).Next()
frameOverride := context.WithValue(l.Ctx, LoggingFrameCtx, frame)
return l.Logger.WithContext(frameOverride)
}

type ctxHook struct {
}

func (h *ctxHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.DebugLevel,
logrus.InfoLevel,
logrus.WarnLevel,
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}

func (h *ctxHook) Fire(e *logrus.Entry) error {
if e.Context != nil {
if e.Context.Value(LoggingFrameCtx) != nil {
frame := e.Context.Value(LoggingFrameCtx).(runtime.Frame)
e.Caller = &frame
}
}
return nil
}

func init() {
commonLogger.Logger.AddHook(&ctxHook{})
}

func (l *EchoLogrusLogger) Output() io.Writer {
return l.Out
}
Expand Down Expand Up @@ -68,113 +115,113 @@ func (l *EchoLogrusLogger) SetPrefix(p string) {
}

func (l *EchoLogrusLogger) Print(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Print(i...)
l.fixCaller().Print(i...)
}

func (l *EchoLogrusLogger) Printf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Printf(format, args...)
l.fixCaller().Printf(format, args...)
}

func (l *EchoLogrusLogger) Printj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Println(string(b))
l.fixCaller().Println(string(b))
}

func (l *EchoLogrusLogger) Debug(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Debug(i...)
l.fixCaller().Debug(i...)
}

func (l *EchoLogrusLogger) Debugf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Debugf(format, args...)
l.fixCaller().Debugf(format, args...)
}

func (l *EchoLogrusLogger) Debugj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Debugln(string(b))
l.fixCaller().Debugln(string(b))
}

func (l *EchoLogrusLogger) Info(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Info(i...)
l.fixCaller().Info(i...)
}

func (l *EchoLogrusLogger) Infof(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Infof(format, args...)
l.fixCaller().Infof(format, args...)
}

func (l *EchoLogrusLogger) Infoj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Infoln(string(b))
l.fixCaller().Infoln(string(b))
}

func (l *EchoLogrusLogger) Warn(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Warn(i...)
l.fixCaller().Warn(i...)
}

func (l *EchoLogrusLogger) Warnf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Warnf(format, args...)
l.fixCaller().Warnf(format, args...)
}

func (l *EchoLogrusLogger) Warnj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Warnln(string(b))
l.fixCaller().Warnln(string(b))
}

func (l *EchoLogrusLogger) Error(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Error(i...)
l.fixCaller().Error(i...)
}

func (l *EchoLogrusLogger) Errorf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Errorf(format, args...)
l.fixCaller().Errorf(format, args...)
}

func (l *EchoLogrusLogger) Errorj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Errorln(string(b))
l.fixCaller().Errorln(string(b))
}

func (l *EchoLogrusLogger) Fatal(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Fatal(i...)
l.fixCaller().Fatal(i...)
}

func (l *EchoLogrusLogger) Fatalf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Fatalf(format, args...)
l.fixCaller().Fatalf(format, args...)
}

func (l *EchoLogrusLogger) Fatalj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Fatalln(string(b))
l.fixCaller().Fatalln(string(b))
}

func (l *EchoLogrusLogger) Panic(i ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Panic(i...)
l.fixCaller().Panic(i...)
}

func (l *EchoLogrusLogger) Panicf(format string, args ...interface{}) {
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Panicf(format, args...)
l.fixCaller().Panicf(format, args...)
}

func (l *EchoLogrusLogger) Panicj(j log.JSON) {
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
l.Logger.WithContext(l.Ctx).WithFields(l.Fields).Panicln(string(b))
l.fixCaller().Panicln(string(b))
}
Loading