Open mtchuyen opened 9 months ago
logrus.WithFields
& logrus.Fields
cl := logrus.WithFields(
logrus.Fields{
"field_one": "value_one",
})
cl = cl.WithFields(
logrus.Fields{
"field_two": "value_two",
})
cl.Info("hello_world")
INFO[0000] hello_world field_one="value_one" field_two="value_two"
log.WithFields(log.Fields{
"animal": "walrus",
"field_one": "value_one",
"field_two": "value_two",
}).Info("hello_world")
INFO[0000] hello_world animal=walrus field_one="value_one" field_two="value_two"
See: https://itnext.io/elevate-your-golang-logging-with-the-strength-of-logrus-eb028b117c40
Basic Logging with Logrus
Feature:
1. Formatting Logs with Logrus
we’re setting the log format to JSON and logging an informational message.
you’ll get a JSON-formatted log entry like this:
1.2. Log Entry Order
You can maintain a consistent order of log entry fields.
1.3. Custom Log Formatter
You can create custom formatters to control how log entries are formatted.
2. Setting the Log Level
Logrus provides several log levels.
2.3. Logging a Fatal Error:
If you have a severe error that needs to terminate the program, you can use
Fatal
which logs the error and callsos.Exit(1)
.2.4. Logging With a Panic
In case you need to log an error message and panic, use
Panic
.2.5. Trace level:
If you want even more detail than
Debug
, Logrus provides aTrace
level.2.5. Logging to an io.Writer
2.6. Logging in Different Timezones
You can set your preferred timezone for the log timestamps.
3. Implementing Hooks with Logrus
Logrus hooks can be extremely useful for sending log entries to external services that Logrus don’t already support.
Ref