Logging in Go: Overview of the Standard log Library and Alternatives

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is logging in Go?

Logging is the process of recording events that occur in a program during its execution. In Go, built-in logging support is implemented through the log package from the standard library. This package provides a simple and efficient way to output messages to stdout/stderr, write them to files, and manage the output format. Logs are necessary for debugging, monitoring application performance, security auditing, and analyzing errors in a production environment.

Why is logging needed?

  • Debugging: quickly detect and fix errors during development.
  • Monitoring: track the application's state in real time.
  • Auditing: record user actions and system events.
  • Performance analysis: identify bottlenecks and performance issues.

Installation

The log package is part of the Go standard library, so no additional installation is required. Simply import it into your project:

import "log"

For advanced logging, there are popular third-party libraries that can be installed via go get:

go get github.com/sirupsen/logrus# orgo get go.uber.org/zap

Main functions of the standard log library

  • log.Print(), log.Printf(), log.Println() — output messages.
  • log.Fatal(), log.Fatalf(), log.Fatalln() — output a message and terminate the program with exit code 1.
  • log.Panic(), log.Panicf(), log.Panicln() — output a message and trigger a panic.

Go code example

package main

import (\t"log"\t"os")

func main() {\t// Configure output to a file\tfile, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\tif err != nil {\t\tlog.Fatal(err)\t}\tdefer file.Close()

\t// Create a logger with a prefix and flags\tlogger := log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)

\t// Logging examples\tlogger.Println("Application started")\tlogger.Printf("User %s logged in", "admin")

\t// Using the standard logger\tlog.Println("This is a message to stdout")}

When to use

  • Standard log: for simple projects, scripts, command-line utilities.
  • Logrus: for production applications that need logging levels (Info, Warn, Error, Debug) and structured logs in JSON format.
  • Zap: for high-load systems where performance is critical (minimal memory allocation).
  • Zerolog: another fast logger with zero allocation support.

The choice of library depends on performance requirements, project complexity, and the need for structured logs.

Recommendations