Skip to content
Snippets Groups Projects
Commit 508b37b7 authored by Johan de Klerk's avatar Johan de Klerk
Browse files

Set custom logger

parent 72916187
No related branches found
No related tags found
No related merge requests found
package logs package logs
import ( import (
"bytes"
"encoding/json"
"fmt" "fmt"
"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/errors" "gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/errors"
"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/string_utils" "gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/string_utils"
...@@ -100,11 +102,7 @@ func InitLogs(requestID *string, isDebugBuild bool, buildVersion string, request ...@@ -100,11 +102,7 @@ func InitLogs(requestID *string, isDebugBuild bool, buildVersion string, request
}) })
} else { } else {
log.SetReportCaller(true) log.SetReportCaller(true)
log.SetFormatter(&log.JSONFormatter{ log.SetFormatter(&CustomLogFormatter{})
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
// Exclude the caller, will rather be added as a field
return "", ""
}})
} }
log.SetLevel(LogLevel()) log.SetLevel(LogLevel())
...@@ -313,3 +311,38 @@ func fakeHttpRequest() *http.Request { ...@@ -313,3 +311,38 @@ func fakeHttpRequest() *http.Request {
} }
return &request return &request
} }
type CustomLogFormatter struct {
}
func (f *CustomLogFormatter) Format(entry *log.Entry) ([]byte, error) {
data := map[string]any{}
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 entry.Message != "" {
data["msg"] = entry.Message
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
encoder := json.NewEncoder(b)
encoder.SetEscapeHTML(true)
if err := encoder.Encode(entry.Data); err != nil {
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
}
return b.Bytes(), nil
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment