Logging is a crucial aspect of software development, and Go provides a simple yet effective package for logging: the log package. In this article, we'll explore how to use the log package for basic logging tasks in Go applications.

Getting Started with the log Package

The log package in Go is part of the standard library, which means you can use it without any additional installations. Import the log package at the top of your file:

import (
    "log"
)

Basic Logging

To record a basic log message, you can use the Println, Printf, or Print functions. Here is an example of how to use these functions:

package main

import (
    "log"
)

func main() {
    log.Println("This is a log message.")
    log.Printf("This is a formatted log message with a number: %d", 42)
}

The above example will output log messages to the standard output, typically your console or terminal.

Log Levels

While the standard log package does not provide predefined log levels (such as INFO, WARNING, ERROR), you can create your own if you need more detailed logging. Here's an example:

package main

import (
    "fmt"
    "log"
)

const (
    INFO    = "INFO"
    WARNING = "WARNING"
    ERROR   = "ERROR"
)

func logMessage(level string, message string) {
    log.Printf("[%s] %s", level, message)
}

func main() {
    logMessage(INFO, "This is an info message.")
    logMessage(WARNING, "This is a warning message.")
    logMessage(ERROR, "This is an error message.")
}

Customizing Log Output

The log package allows you to customize the output format. You can use the SetFlags function to set how the output looks. Here's an example:

package main

import (
    "log"
)

func main() {
    log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
    log.Println("This is a customized log message.")
}

In the example above, the date, time, and the short file name (file.go and line number) are included in the log messages.

Redirecting Log Output

By default, log messages are printed to the standard output. You can redirect log output to different destinations, such as a file:

package main

import (
    "log"
    "os"
)

func main() {
    f, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal(err)
    }
    log.SetOutput(f)
    log.Println("This log message will go to app.log")
}

In this example, the log output is redirected to a file named app.log. Ensure you handle error scenarios appropriately when working with file operations.

Conclusion

The log package in Go provides a straightforward approach to logging in your applications. While it does not offer advanced features like log level separation out of the box, it is more than sufficient for simple logging needs. For more sophisticated logging, you might consider additional packages, such as logrus or zap.