Skip to content

Instantly share code, notes, and snippets.

@chainhead
Last active March 28, 2021 02:29

Revisions

  1. chainhead revised this gist Mar 28, 2021. 3 changed files with 63 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions 0-intro.md
    Original file line number Diff line number Diff line change
    @@ -4,3 +4,21 @@ A basic implementation of logging with Go language. Copied from [https://www.hon

    ## Usage

    1. Run the following commands to test with built-in `log` package. Logs will be saved in `logs.txt`.

    ```bash
    go run log.go
    ```

    2. Run the following commands to test with built-in `logr` package.

    ```bash
    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`.
    30 changes: 30 additions & 0 deletions log.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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")
    }
    15 changes: 15 additions & 0 deletions logr.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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.")
    }
  2. chainhead created this gist Mar 28, 2021.
    6 changes: 6 additions & 0 deletions 0-intro.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    # Introduction

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

    ## Usage