Skip to content

Commit

Permalink
feat(logger): Adding error field
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Boutour <[email protected]>
  • Loading branch information
ViBiOh committed Dec 8, 2023
1 parent 4223f46 commit 32896b6
Show file tree
Hide file tree
Showing 27 changed files with 70 additions and 49 deletions.
2 changes: 0 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,5 @@ HTTP_TELEMETRY_URL=
HTTP_REDIS_ADDRESS=
HTTP_LOGGER_JSON=true

HTTP_GRACE_DURATION=5s

# Tests
TEST_CACHE_ADDRESS=127.0.0.1:6379
2 changes: 1 addition & 1 deletion cmd/alcotest/alcotest.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func main() {
alcotestConfig := alcotest.Flags(fs, "")

if err := fs.Parse(os.Args[1:]); err != nil {
slog.Error("parse flag", "err", err)
slog.Error("parse flag", "error", err)
os.Exit(1)
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/http/background.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
func startBackground(ctx context.Context, config configuration, client client, adapter adapter) {
go redis.SubscribeFor(ctx, client.redis, "httputils:tasks", func(content time.Time, err error) {
if err != nil {
slog.ErrorContext(ctx, "consume on pubsub", "err", err)
slog.ErrorContext(ctx, "consume on pubsub", "error", err)

return
}
Expand All @@ -25,14 +25,14 @@ func startBackground(ctx context.Context, config configuration, client client, a
})

speakingClock := cron.New().Each(15 * time.Second).OnSignal(syscall.SIGUSR1).OnError(func(ctx context.Context, err error) {
slog.ErrorContext(ctx, "run cron", "err", err)
slog.ErrorContext(ctx, "run cron", "error", err)
}).Now()

go speakingClock.Start(ctx, func(_ context.Context) error {
slog.InfoContext(ctx, "Clock is ticking")

if err := client.redis.PublishJSON(ctx, "httputils:tasks", time.Now()); err != nil {
slog.ErrorContext(ctx, "publish on pubsub", "err", err)
slog.ErrorContext(ctx, "publish on pubsub", "error", err)
}

return nil
Expand Down
6 changes: 3 additions & 3 deletions cmd/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func main() {

config, err := newConfig()
if err != nil {
slog.ErrorContext(ctx, "config", "err", err)
slog.ErrorContext(ctx, "config", "error", err)
os.Exit(1)
}

Expand All @@ -39,7 +39,7 @@ func main() {

client, err := newClient(ctx, config)
if err != nil {
slog.ErrorContext(ctx, "client", "err", err)
slog.ErrorContext(ctx, "client", "error", err)
os.Exit(1)
}

Expand All @@ -49,7 +49,7 @@ func main() {

adapter, err := newAdapter(ctxEnd, config, client)
if err != nil {
slog.ErrorContext(ctx, "adapter", "err", err)
slog.ErrorContext(ctx, "adapter", "error", err)
os.Exit(1)
}

Expand Down
5 changes: 3 additions & 2 deletions cmd/http/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"log/slog"
"net/http"
"time"
Expand Down Expand Up @@ -46,12 +47,12 @@ func newPort(ctx context.Context, config configuration, client client, adapter a
go func() {
time.Sleep(time.Millisecond * 100)
if err = adapter.hello.EvictOnSuccess(cntxt.WithoutDeadline(ctx), r.URL.Path, nil); err != nil {
slog.ErrorContext(r.Context(), "evict on success", "err", err)
slog.ErrorContext(r.Context(), "evict on success", "error", err)
}
}()
}

slog.InfoContext(r.Context(), "coucou")
slog.InfoContext(r.Context(), "Hello World", "error", errors.New("coucou"))

return renderer.NewPage("public", http.StatusOK, nil), nil
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ require (
github.com/golang/protobuf v1.5.3 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 h1:6UKoz5ujsI55KNpsJH3UwCq3T8k
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1/go.mod h1:YvJ2f6MplWDhfxiUC3KpyTy76kYUZA4W3pTv/wdKQ9Y=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA=
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.5.0 h1:NxstgwndsTRy7eq9/kqYc/BZh5w2hHJV86wjvO+1xPw=
github.com/jackc/pgx/v5 v5.5.0/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
Expand Down
8 changes: 4 additions & 4 deletions pkg/amqp/close.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ func (c *Client) Close() {
var err error

if err = c.cancelListeners(); err != nil {
slog.Error("cancel listeners", "err", err)
slog.Error("cancel listeners", "error", err)
}

if err = c.closeListeners(); err != nil {
slog.Error("close listeners", "err", err)
slog.Error("close listeners", "error", err)
}

c.closeChannel()
Expand Down Expand Up @@ -76,7 +76,7 @@ func (c *Client) reconnectListeners() {
defer c.mutex.Unlock()

if err := listener.createChannel(c.connection); err != nil {
slog.Error("recreate channel", "err", err, "name", listener.name)
slog.Error("recreate channel", "error", err, "name", listener.name)
}

listener.reconnect <- true
Expand Down Expand Up @@ -114,6 +114,6 @@ func (c *Client) closeConnection() {

func loggedClose(closer io.Closer) {
if err := closer.Close(); err != nil {
slog.Error("close", "err", err)
slog.Error("close", "error", err)
}
}
2 changes: 1 addition & 1 deletion pkg/amqp/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (c *Client) onDisconnect() {
}

if err := c.reconnect(); err != nil {
slog.Error("reconnect", "err", err)
slog.Error("reconnect", "error", err)

slog.Info("Waiting one minute before attempting to reconnect again...")
time.Sleep(time.Minute)
Expand Down
4 changes: 2 additions & 2 deletions pkg/amqp/listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ reconnect:
log := slog.With("name", listener.name)

if queueName, err := queueResolver(); err != nil {
log.Error("get queue name on reopen", "err", err)
log.Error("get queue name on reopen", "error", err)
} else if messages, err := c.listen(listener, queueName); err != nil {
log.Error("reopen listener", "err", err)
log.Error("reopen listener", "error", err)
} else {
log.Info("Listen restarted")
input = messages
Expand Down
14 changes: 7 additions & 7 deletions pkg/amqphandler/amqphandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (s *Service) Start(ctx context.Context) {
return queueName, err
}, s.exchange, s.routingKey)
if err != nil {
log.ErrorContext(ctx, "listen", "err", err)
log.ErrorContext(ctx, "listen", "error", err)

return
}
Expand All @@ -140,7 +140,7 @@ func (s *Service) Start(ctx context.Context) {
s.handleMessage(ctx, log, message)
}, func() {
if err := s.amqpClient.StopListener(consumerName); err != nil {
log.ErrorContext(ctx, "stopping listener", "err", err)
log.ErrorContext(ctx, "stopping listener", "error", err)
}
})
}
Expand All @@ -162,13 +162,13 @@ func (s *Service) handleMessage(ctx context.Context, log *slog.Logger, message a
attribute.String("routingKey", s.routingKey),
))
if err = message.Ack(false); err != nil {
log.ErrorContext(ctx, "ack message", "err", err)
log.ErrorContext(ctx, "ack message", "error", err)
}

return
}

log.ErrorContext(ctx, "handle message", "err", err, "body", string(message.Body))
log.ErrorContext(ctx, "handle message", "error", err, "body", string(message.Body))

if s.retryInterval > 0 && s.maxRetry > 0 {
s.counter.Add(ctx, 1, metric.WithAttributes(
Expand All @@ -181,7 +181,7 @@ func (s *Service) handleMessage(ctx context.Context, log *slog.Logger, message a
return
}

log.ErrorContext(ctx, "retry message", "err", err)
log.ErrorContext(ctx, "retry message", "error", err)
}

if err = message.Ack(false); err != nil {
Expand All @@ -191,7 +191,7 @@ func (s *Service) handleMessage(ctx context.Context, log *slog.Logger, message a
attribute.String("routingKey", s.routingKey),
))

log.ErrorContext(ctx, "ack message to trash it", "err", err)
log.ErrorContext(ctx, "ack message to trash it", "error", err)
}
}

Expand All @@ -215,7 +215,7 @@ func (s *Service) configure(init bool) (string, error) {
func generateIdentityName() string {
raw := make([]byte, 4)
if _, err := rand.Read(raw); err != nil {
slog.Error("generate identity name", "err", err)
slog.Error("generate identity name", "error", err)

return "error"
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cache/background.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ func doInBackground(ctx context.Context, callback func(ctx context.Context) erro
defer cancel()

if err := callback(ctx); err != nil {
slog.ErrorContext(ctx, "background callback", "err", err)
slog.ErrorContext(ctx, "background callback", "error", err)
}
}
6 changes: 3 additions & 3 deletions pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ func (c *Cache[K, V]) Get(ctx context.Context, id K) (V, error) {

if content, err := c.read.Load(loadCtx, key); err != nil {
if errors.Is(err, context.Canceled) {
slog.WarnContext(ctx, "load from cache", "err", err, "key", key)
slog.WarnContext(ctx, "load from cache", "error", err, "key", key)
} else {
slog.ErrorContext(ctx, "load from cache", "err", err, "key", key)
slog.ErrorContext(ctx, "load from cache", "error", err, "key", key)
}
} else if value, ok, err := c.decode([]byte(content)); err != nil {
logUnmarshalError(ctx, key, err)
Expand Down Expand Up @@ -209,5 +209,5 @@ func (c *Cache[K, V]) extendTTL(ctx context.Context, keys ...string) {
}

func logUnmarshalError(ctx context.Context, key string, err error) {
slog.ErrorContext(ctx, "unmarshal from cache", "err", err, "key", key)
slog.ErrorContext(ctx, "unmarshal from cache", "error", err, "key", key)
}
2 changes: 1 addition & 1 deletion pkg/cache/extender.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,6 @@ func (te *TTLExtender) flush(ctx context.Context) {
te.mutex.Unlock()

if err := te.redis.Expire(ctx, te.ttl, keys...); err != nil {
slog.ErrorContext(ctx, "extend keys", "err", err)
slog.ErrorContext(ctx, "extend keys", "error", err)
}
}
6 changes: 3 additions & 3 deletions pkg/cache/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (c *Cache[K, V]) fetchAll(ctx context.Context, ids []K) ([]V, error) {
wg.Go(func() {
value, err := c.fetch(ctx, id)
if err != nil {
slog.ErrorContext(ctx, "fetch id", "err", err, "id", id)
slog.ErrorContext(ctx, "fetch id", "error", err, "id", id)
}

output[index] = value
Expand Down Expand Up @@ -164,9 +164,9 @@ func (c *Cache[K, V]) redisValues(ctx context.Context, ids []K) ([]string, []str
values, err := c.read.LoadMany(loadCtx, keys...)
if err != nil {
if errors.Is(err, context.Canceled) {
slog.WarnContext(ctx, "load many from cache", "err", err, "key", strconv.Itoa(len(keys)))
slog.WarnContext(ctx, "load many from cache", "error", err, "key", strconv.Itoa(len(keys)))
} else {
slog.ErrorContext(ctx, "load many from cache", "err", err, "key", strconv.Itoa(len(keys)))
slog.ErrorContext(ctx, "load many from cache", "error", err, "key", strconv.Itoa(len(keys)))
}

values = make([]string, len(ids))
Expand Down
2 changes: 1 addition & 1 deletion pkg/cache/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (c *Cache[K, V]) storeMany(ctx context.Context, ids []K, values []V, indexe

payload, err := c.serializer.Encode(values[index])
if err != nil {
slog.ErrorContext(ctx, "encoding", "err", err, "key", key)
slog.ErrorContext(ctx, "encoding", "error", err, "key", key)

continue
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cron/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func New() *Cron {
now: make(chan time.Time, 1),
clock: time.Now,
onError: func(ctx context.Context, err error) {
slog.ErrorContext(ctx, "cron error", "err", err)
slog.ErrorContext(ctx, "cron error", "error", err)
},
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/health/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (s *Service) waitForDone(done <-chan struct{}, signals ...os.Signal) {
func (s *Service) isReady(ctx context.Context) bool {
for _, pinger := range s.pingers {
if err := pinger(ctx); err != nil {
slog.ErrorContext(ctx, "ping", "err", err)
slog.ErrorContext(ctx, "ping", "error", err)

return false
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/httputils/httputils.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func versionHandler() http.Handler {
}

if _, err := w.Write(version); err != nil {
slog.ErrorContext(r.Context(), "write", "err", err)
slog.ErrorContext(r.Context(), "write", "error", err)
}
})
}
17 changes: 17 additions & 0 deletions pkg/logger/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package logger

import (
"reflect"
)

type errorField struct {
Kind string `json:"kind"`
Message string `json:"message"`
}

func ErrorField(err error) errorField {
return errorField{
Kind: reflect.TypeOf(err).String(),
Message: err.Error(),
}
}
5 changes: 5 additions & 0 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ func configureLogger(writer io.Writer, level slog.Level, json bool, timeKey, lev
a.Key = timeKey
}

switch obj := a.Value.Any().(type) {
case error:
a.Value = slog.AnyValue(ErrorField(obj))
}

return a
},
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/redis/pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ func (s Service) Subscribe(ctx context.Context, channel string) (<-chan *redis.M

return pubsub.Channel(), func(ctx context.Context) {
if err := pubsub.Unsubscribe(ctx, channel); err != nil {
slog.ErrorContext(ctx, "unsubscribe pubsub", "err", err, "channel", channel)
slog.ErrorContext(ctx, "unsubscribe pubsub", "error", err, "channel", channel)
}

if err := pubsub.Close(); err != nil {
slog.ErrorContext(ctx, "close pubsub", "err", err, "channel", channel)
slog.ErrorContext(ctx, "close pubsub", "error", err, "channel", channel)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func (s *Service) Enabled() bool {

func (s *Service) Close() {
if err := s.client.Close(); err != nil {
slog.Error("redis close", "err", err)
slog.Error("redis close", "error", err)
}
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/renderer/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (s Service) render(w http.ResponseWriter, r *http.Request, templateFunc Tem
if exception := recover(); exception != nil {
output := make([]byte, 1024)
runtime.Stack(output, false)
slog.ErrorContext(r.Context(), "recovered from panic", "err", exception, "stacktrace", string(output))
slog.ErrorContext(r.Context(), "recovered from panic", "error", exception, "stacktrace", string(output))

s.Error(w, r, nil, fmt.Errorf("recovered from panic: %s", exception))
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/renderer/renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ func (s *Service) handleStatic(w http.ResponseWriter, r *http.Request) bool {

defer func() {
if closeErr := file.Close(); closeErr != nil {
slog.WarnContext(r.Context(), "close static file", "err", err)
slog.WarnContext(r.Context(), "close static file", "error", err)
}
}()

Expand Down
Loading

0 comments on commit 32896b6

Please sign in to comment.