Sling Academy
Home/Golang/Using `log` for Simple Logging in Go Applications

Using `log` for Simple Logging in Go Applications

Last updated: November 27, 2024

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.

Next Article: Efficient File Operations with `os` and `io/ioutil` in Go

Series: Go Utilities and Tools

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant