01 Introduction to Logging in Golang
Introduction to Logging
Logging, which contains information about a system, can deliver clear messages about events that occur within our system. Logging is not only used to display information but can sometimes also be used as part of the debugging process when something goes wrong in a system we have built.
There are many logging mechanisms in a system: some store logs in a file, some store them in a database, and there are even dedicated third-party tools that can be used for the logging process, for example ElasticSearch Kibana. Logging is so important that there are many storage mechanisms for it, allowing logs to be distributed and recorded historically so that events occurring in the system—such as system issues, calculation issues, and even problems with the business processes built into the system—can be recorded in this logging system.
Libraries We Will Use
In Golang, a logging framework package is actually already available, but the features it provides are limited and not as complete as several libraries that are now widely used, even for specialized needs. Most programmers also do not use it once they have implemented their systems in live production.
There are many libraries that have become popular among programmers, especially in the Go community, including:
- Zerolog: https://github.com/rs/zerolog
- Zap: https://github.com/uber-go/zap
- Logrus: https://github.com/sirupsen/logrus
- and many others.
Based on benchmarking information here , the conclusion is that Zerolog and Zap offer high performance, but when we want to learn standard logging that is easy to use, we can also use Logrus.
This time we will use the Logrus logging package or framework because we want something that is easy to use and implement in our system, and also because, judging from the stars on the repository, this package is the most popular of them all.
Creating a New Project
Let’s go ahead and create a new project to learn the basics, starting by creating a folder named learn-golang-logging, then running the following in the terminal.
1go mod init github.com/santekno/learn-golang-loggingcontinue by adding the dependency package we will use
1go get github.com/sirupsen/logrusAfter that, you will see two files, go.mod and go.sum, as shown below.
1.
2├── go.mod
3└── go.sumand the go.mod file will be populated like this
1module github.com/santekno/learn-golang-logging
2
3go 1.21.1
4
5require (
6 github.com/sirupsen/logrus v1.9.3 // indirect
7 golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
8)The new project is now ready, and we are prepared to learn about logging in Golang in the next article. If you want to add the repo and store it in git, you can add an initial git setup and push it to a git repository. For example, santekno currently uses GitHub to store the code repositories we create.
1git init
2git remote add origin git@github.com:santekno/learn-golang-logging.git
3git push origin main