Skip to content

Commit 2045b19

Browse files
authored
Merge pull request #32 from gruntwork-io/yori-log-formatter
Introduce a log text formatter that prefixes the binary name to the log entry
2 parents 00c7cf8 + 75d9ccc commit 2045b19

File tree

2 files changed

+36
-10
lines changed

2 files changed

+36
-10
lines changed

logging/formatter.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package logging
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
7+
"github.com/sirupsen/logrus"
8+
)
9+
10+
// TextFormatterWithBinName is a logrus formatter that prefixes the binary name to the log output.
11+
type TextFormatterWithBinName struct {
12+
Name string
13+
TextFormatter logrus.TextFormatter
14+
}
15+
16+
func (formatter *TextFormatterWithBinName) Format(entry *logrus.Entry) ([]byte, error) {
17+
logTxt, err := formatter.TextFormatter.Format(entry)
18+
if err != nil {
19+
return logTxt, err
20+
}
21+
22+
outBuf := &bytes.Buffer{}
23+
fmt.Fprintf(outBuf, "[%s] ", formatter.Name)
24+
if _, err := outBuf.Write(logTxt); err != nil {
25+
return logTxt, err
26+
}
27+
return outBuf.Bytes(), nil
28+
}

logging/logging.go

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
package logging
22

33
import (
4-
"github.com/sirupsen/logrus"
54
"sync"
6-
)
75

8-
const loggerNameField = "name"
6+
"github.com/sirupsen/logrus"
7+
)
98

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

1716
logger.Level = globalLogLevel
1817

19-
logger.Formatter = &logrus.TextFormatter{
20-
FullTimestamp: true,
18+
logger.Formatter = &TextFormatterWithBinName{
19+
Name: name,
20+
TextFormatter: logrus.TextFormatter{
21+
FullTimestamp: true,
22+
},
2123
}
2224

23-
if name != "" {
24-
return logger.WithField(loggerNameField, name).Logger
25-
} else {
26-
return logger.WithFields(make(logrus.Fields)).Logger
27-
}
25+
return logger
2826
}
2927

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

0 commit comments

Comments
 (0)