Skip to content

Instantly share code, notes, and snippets.

@bgbaroo
Created October 12, 2021 18:02
Show Gist options
  • Save bgbaroo/63ebfeccbd4bc70a7ea84f49971f6ec9 to your computer and use it in GitHub Desktop.
Save bgbaroo/63ebfeccbd4bc70a7ea84f49971f6ec9 to your computer and use it in GitHub Desktop.
Basic logging in Go
package main
import (
"log"
"os"
)
var (
InfoLogger *log.Logger
WarningLogger *log.Logger
ErrorLogger *log.Logger
)
func init() {
fp, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
InfoLogger = log.New(os.Stdout, "INFO: ", log.LstdFlags)
WarningLogger = log.New(fp, "WARNING: ", log.LstdFlags|log.Lshortfile)
ErrorLogger = log.New(fp, "ERROR: ", log.LstdFlags|log.Lshortfile)
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Println("Hey!")
log.SetOutput(os.Stdout)
log.Println("Hey again!")
InfoLogger.Println("This is some info")
WarningLogger.Println("This is something serious")
ErrorLogger.Println("Something bad happened")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment