gologrus

logrus output in different formats


My program uses logrus in a basic way without any config:

   logrus.Info("...")

But in different places, it outputs in different formats, some place like:

INFO[0016] pushed     

and some place like:

time="2023-11-30T05:26:39Z" level=info msg=pushed

I wonder what is a mistery behind?


Solution

  • Let me self-answer this question. I looked into logrus code in the weekend, and found the tricky.

    logrus has a mechanism to detect if the current terminal is colored, if yes, it will output in format like INFO[0000] pushed, otherwise in format like time="2023-11-30T05:26:39Z" level=info msg=pushed.

    So if you want to always output in the first format, which is shorter, then you just set force color:

        logrus.SetFormatter(&logrus.TextFormatter{
            ForceColors: true,
        })
    

    If you want the second format, then just force disable color:

        logrus.SetFormatter(&logrus.TextFormatter{
            DisableColors: true,
        })
    

    You can also configure time format for sure.