Logging Information II

Let’s learn how to write to a custom log file and print line numbers in log entries.

Writing to a custom log file

Most of the time, and especially on applications and services that are deployed to production, we just need to write our logging data in a log file of our choice. This can be for many reasons, including writing debugging data without messing with the system log files or keeping our own logging data separate from system logs in order to transfer it or store it in a database or software like Elasticsearch. This lesson teaches us how to write to a custom log file that is usually application-specific.

Note: Saving information to files is very handy when troubleshooting and debugging Go code.

The path of the log file that is used is hardcoded into the code using a global variable named LOGFILE. In this example, the log file is placed inside the /tmp directory. This location is chosen to prevent our file system from running out of space in case something goes wrong. It’s worth noting that the /tmp directory is not typically used for storing data because its contents are usually cleared after each system reboot.

Additionally, at this point, this will save us from having to execute customLog.go with root privileges and from putting unnecessary files into our precious system directories.

Coding example

Now, we will discuss the code of the customLog.go program:

Get hands-on with 1200+ tech skills courses.