Skip to content

Introduce a log text formatter that prefixes the binary name to the log entry #32

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

Merged
merged 1 commit into from
Aug 19, 2020
Merged
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
28 changes: 28 additions & 0 deletions logging/formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package logging

import (
"bytes"
"fmt"

"github.com/sirupsen/logrus"
)

// TextFormatterWithBinName is a logrus formatter that prefixes the binary name to the log output.
type TextFormatterWithBinName struct {
Name string
TextFormatter logrus.TextFormatter
}

func (formatter *TextFormatterWithBinName) Format(entry *logrus.Entry) ([]byte, error) {
logTxt, err := formatter.TextFormatter.Format(entry)
if err != nil {
return logTxt, err
}

outBuf := &bytes.Buffer{}
fmt.Fprintf(outBuf, "[%s] ", formatter.Name)
if _, err := outBuf.Write(logTxt); err != nil {
return logTxt, err
}
return outBuf.Bytes(), nil
}
18 changes: 8 additions & 10 deletions logging/logging.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package logging

import (
"github.com/sirupsen/logrus"
"sync"
)

const loggerNameField = "name"
"github.com/sirupsen/logrus"
)

var globalLogLevel = logrus.InfoLevel
var globalLogLevelLock = sync.Mutex{}
Expand All @@ -16,15 +15,14 @@ func GetLogger(name string) *logrus.Logger {

logger.Level = globalLogLevel

logger.Formatter = &logrus.TextFormatter{
FullTimestamp: true,
logger.Formatter = &TextFormatterWithBinName{
Name: name,
TextFormatter: logrus.TextFormatter{
FullTimestamp: true,
},
}

if name != "" {
return logger.WithField(loggerNameField, name).Logger
} else {
return logger.WithFields(make(logrus.Fields)).Logger
}
return logger
}

// Set the log level. Note: this ONLY affects loggers created using the GetLogger function AFTER this function has been
Expand Down