mtchuyen / Golang-Tips

Tips in Golang programming
3 stars 2 forks source link

Logrus #40

Open mtchuyen opened 9 months ago

mtchuyen commented 9 months ago

See: https://itnext.io/elevate-your-golang-logging-with-the-strength-of-logrus-eb028b117c40

Basic Logging with Logrus

Feature:

1. Formatting Logs with Logrus

logrus.SetFormatter(&logrus.JSONFormatter{})

we’re setting the log format to JSON and logging an informational message.

 logrus.Info("This is an informational message.")

you’ll get a JSON-formatted log entry like this:

{"level":"info","msg":"This is an informational message.","time":"2023-07-23T14:56:00Z"}.

1.2. Log Entry Order

You can maintain a consistent order of log entry fields.

func main() {
 logrus.SetFormatter(&logrus.JSONFormatter{FieldMap: logrus.FieldMap{
  logrus.FieldKeyTime:  "@timestamp",
  logrus.FieldKeyLevel: "@level",
  logrus.FieldKeyMsg:   "@message",
 }})
 logrus.Info("Log with consistent field order.")
}

1.3. Custom Log Formatter

You can create custom formatters to control how log entries are formatted.

type CustomFormatter struct{}

func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  return []byte(fmt.Sprintf("%s: %s\n", entry.Level.String(), entry.Message)), nil
}

func main() {
  logrus.SetFormatter(new(CustomFormatter))
  logrus.Info("Log with a custom formatter.")
}

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 calls os.Exit(1).

2.4. Logging With a Panic

In case you need to log an error message and panic, use Panic.

logrus.Panic("This is a panic log!")

2.5. Trace level:

If you want even more detail than Debug, Logrus provides a Trace level.

 logrus.SetLevel(logrus.TraceLevel)
 logrus.Trace("This is a trace log.")

2.5. Logging to an io.Writer

 logrus.SetOutput(os.Stdout)
 logrus.Info("This log is written to stdout.")

2.6. Logging in Different Timezones

You can set your preferred timezone for the log timestamps.

// Use UTC time
logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: time.RFC3339})
logrus.Info("Log with RFC3339 timestamp format.")

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

mtchuyen commented 9 months ago

Hook in Logrus

mtchuyen commented 9 months ago

Log format sample:

1. 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"