Skip to content

Instantly share code, notes, and snippets.

@chainhead
Last active March 28, 2021 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chainhead/cab6e86a5edbe2585dd55847383bf15f to your computer and use it in GitHub Desktop.
Save chainhead/cab6e86a5edbe2585dd55847383bf15f to your computer and use it in GitHub Desktop.
Logging in Go - logrus

Introduction

A basic implementation of logging with Go language. Copied from https://www.honeybadger.io/blog/golang-logging/

Usage

  1. Run the following commands to test with built-in log package. Logs will be saved in logs.txt.
go run log.go
  1. Run the following commands to test with built-in logr package.
go get github.com/sirupsen/logrus
go run log.go

Notes

  1. Time-stamps in logs - when using either log or sirupsen/logrus - can be modified by setting the TZ environment variable in the shell.
  2. Built in log package is the simplest for generating file name and number.
  3. For JSON formatting of logs, use sirupsen/logrus.
package main
import (
"log"
"os"
)
var (
WarningLogger *log.Logger
InfoLogger *log.Logger
ErrorLogger *log.Logger
)
func init() {
file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
InfoLogger = log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
WarningLogger = log.New(file, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
ErrorLogger = log.New(file, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}
func main() {
InfoLogger.Println("Starting the application...")
InfoLogger.Println("Something noteworthy happened")
WarningLogger.Println("There is something you should know about")
ErrorLogger.Println("Something went wrong")
}
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.SetReportCaller(true)
log.SetFormatter(&log.JSONFormatter{})
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment