golang

Golang Log to File

Logging is one of the most important tools for a developer. It allows to monitor an application for bugs, performance issues, usage tracking, and much more. Hence, learning to create logs for your application is highly beneficial.

Using this guide, we will introduce you to the log package in the Go standard library and use it to create custom logs.

Golang Log Package

The Go standard library is massive, believe me, it holds a collection of tools, utilities and packages for almost all-important aspects of a programmer.

One such package is the log package. It comes equipped with everything you need to implement logging features for your Go programs. This includes various logging levels such as debug, warning, error, info, etc.

The most basic method in the log package is the Println method. Like the Println method from the fmt package, it allows you to create a basic log message.

An example source code is as shown below:

package main
import "log"
func main() {
    log.Println("Hello, there!")
}

If we run the above code, we should see and output as shown:

2022/01/27 21:29:35 Hello, there!

Notice something different in the message printed to the console?

The Println method from the log package includes a timestamp of when the log message was created. If you are ingesting the logs for a logging application, having the timestamp is hugely beneficial for filtering logs.

Keep in mind that the log package will print the message to the stderr stream. You can also configure it to write to a file, as we will cover in the next section.

Golang Log to File

To log to a file, you can use the OS package to create a log file if it does not exist or open and write to an existing file. Doing so will set the output of the log package to the specified output file.

Keep in mind that the log package also supports other output destination that supports io.Writer interface.

An example code to log to a file is as shown in the snippet below:

package main
import (
    "log"
    "os"
    "time"
)
func main() {
    // open file and create if non-existent
    file, err := os.OpenFile("custom.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    logger := log.New(file, "Custom Log", log.LstdFlags)
    logger.Println("I am a new log message")
    time.Sleep(5 * time.Second)
    logger.Println("A new log, 5 seconds later")
}

In the example above, we start by opening a file to use as the log output. We include the flags to write to the file and create it if it does not exist.

We then check if there is an error when reading/writing to the file. If an error occurs, we log the error using log.Fatal.

The log.Fatal() method is similar to the Print() method but includes a call to os.Exit() with a status code of 1.

The next step is to close the file. We set the set close function to defer, allowing the function to be executed after the main function is done.

The next step is to create a new logger that writes to the file. The log.Logger function takes 3 principal arguments:

  1. The log output, in this case, is the log file.
  2. The prefix which is appended to the beginning of each entry in the log file.
  3. Finally, is the log constant after the text prefix for each log line.

The following are supported log constants:

  1. Ldate
  2. Ltime
  3. Lmicroseconds
  4. Llongfile
  5. Lshortfile
  6. LUTC
  7. Lmsgprefix
  8. LstdFlags

Consider the documentation resource below to learn more.

https://pkg.go.dev/log#pkg-constants

In our example above, we also set a sleep time for 5 seconds. If we run the code above, we should get an output as shown below:

$ cat custom.log
Custom Log2022/01/27 21:40:25 I am a new log message
Custom Log2022/01/27 21:40:30 A new log, 5 seconds later

The timestamp between the first log entry and the second log entry is 5 seconds apart. This is because of the sleep function in the code above.

Conclusion

This post explores the concept of creating and building loggers for your application in Go. Using this guide, you can get started in using the Go log package and create advanced logging mechanisms for your applications.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list