Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logrus add extra field to contextlogger

Tags:

go

I use logrus in all my go apps and recently I started using a context logger. Now I want to "build up" a context during the execution path of my app. See example below, which illustrates what I want.

package main

import (
    "github.com/Sirupsen/logrus"
)

func main() {
    logrus.Info("normal logger")

    cl := logrus.WithFields(
        logrus.Fields{
            "extra_field_one": "extra_value_one",
        })

    // some code here

    // here I want to add an additional field to to contextlogger cl.
    // How do I do that?

}

EDIT

As ymonad mentioned, it's possible by overwriting the contextLogger. Also found out that you can add one additional field:

cl = cl.WithField("key", "value")
like image 691
Rogier Lommers Avatar asked Mar 21 '17 07:03

Rogier Lommers


People also ask

Is logrus dead?

Logrus is in maintenance-mode. This does not mean Logrus is dead. Logrus will continue to be maintained for security, (backwards compatible) bug fixes, and performance (where we are limited by the interface).

What is logrus hook?

package logrus. // A hook to be fired when logging on the logging levels returned from. // `Levels()` on your implementation of the interface. Note that this is not. // fired in a goroutine or a channel with workers, you should handle such.

What is logrus?

Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. Logrus is in maintenance-mode.


1 Answers

You can just call cl.WithFields()

package main

import "github.com/Sirupsen/logrus"

func main() {
    cl := logrus.WithFields(
        logrus.Fields{
            "extra_field_one": "extra_value_one",
        })
    cl = cl.WithFields(
        logrus.Fields{
            "extra_field_two": "extra_value_two",
        })
    cl.Info("hello world")
}

Output is:

INFO[0000] hello world extra_field_one="extra_value_one" extra_field_two="extra_value_two"
like image 53
ymonad Avatar answered Oct 19 '22 13:10

ymonad