Golang — With Logging
In the Last Article, we discussed Integrating MySQL with Go. In this article, we will discuss how to configure a file logger in Go.
For configuring log file, we will first download logrus dependency.
go get -u github.com/sirupsen/logrus
Once we have the dependency, we will import it to our code,
import (
log "github.com/sirupsen/logrus"
)
Create file object to open file from a custom path,
file, err := OpenFile(logFile, O_RDWR|O_CREATE|O_APPEND, 0666)
And set this file as Output for logrus.
log.SetOutput(file)
Thats It. We have now configured our logger to point to a custom file path.
We can also se the formatter for the log file to JSON or Text Formatter.
log.SetFormatter(&log.TextFormatter{})
log.SetFormatter(&log.JSONFormatter{})
Following is the complete function to configure a log file.
func InitializeLogging(logFile string) {
var file, err = OpenFile(logFile, O_RDWR|O_CREATE|O_APPEND, 0666)
if err != nil {
fmt.Println("Could Not Open Log File : " + err.Error())
}
log.SetOutput(file)
//log.SetFormatter(&log.TextFormatter{})
log.SetFormatter(&log.JSONFormatter{})
}
We can print logs using print or fatal commands of logrus.
log.Println("Something Happened!!")
log.Fatalf("What Happened??")
Complete code for this can be accessed through the Github Repo.
I hope you find it helpful. If you have any suggestions, please feel free to drop a comment.
In the Next Article, we will discuss how to add test cases for a Go Project.