Go (Golang) / Error Handling in Go

Logging and Debugging in Go

In this tutorial, we'll explore the 'log' package in Go. You'll learn how to use it to log errors and debug your programs.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Teaches best practices for handling errors in Go.

Logging and Debugging in Go

1. Introduction

In this tutorial, we will explore how to utilize the built-in 'log' package in Go for logging and debugging purposes. Logging is a crucial aspect of software development as it helps us track the execution flow and debug the program when an issue arises.

By the end of this tutorial, you will learn:
- Basics of the 'log' package in Go.
- How to log errors and debug your programs.
- Good practices for logging in Go.

Prerequisites: To follow along, you should have a basic understanding of Go programming. Familiarity with error handling in Go is beneficial but not mandatory.

2. Step-by-Step Guide

Go's 'log' package provides simple logging functionalities. It defines a type, Logger, with methods for formatting output. It also has predefined 'log.Logger' objects for standard error, which are ready to use.

Logging Basics

To log a message, you can use the 'Println' function from the 'log' package:

log.Println("This is a log message")

Logging Levels

In many scenarios, distinguishing between different kinds of log messages is helpful. You can use 'log' package to create different log levels:

log.Println("[INFO] Information message")
log.Println("[WARN] Warning message")
log.Println("[ERROR] Error message")

Logging to a File

You can also direct the logs to a file:

f, err := os.OpenFile("log.txt", os.O_APPEND | os.O_CREATE | os.O_RDWR, 0666)
if err != nil {
    fmt.Printf("error opening file: %v", err)
}
defer f.Close()

log.SetOutput(f)
log.Println("This is a log message")

3. Code Examples

Example 1: Basic Logging

In this simple example, we are logging an info message:

package main

import "log"

func main() {
    log.Println("[INFO] This is an info message")
}

Output:

2009/11/10 23:00:00 [INFO] This is an info message

Example 2: Logging to a File

In this example, we're logging an error message to a file:

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    f, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
    if err != nil {
        fmt.Printf("error opening file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)
    log.Println("[ERROR] This is an error message")
}

Output in log.txt file:

2009/11/10 23:00:00 [ERROR] This is an error message

4. Summary

In this tutorial, we have learned the basics of logging in Go using the 'log' package. We covered how to create log messages, how to categorize them into different log levels, and how to direct them to a file.

For further learning, you can explore how to customize the log format and how to use the 'log' package in a large application.

5. Practice Exercises

  1. Write a Go program that logs different types of messages (info, warning, error) to the console.
  2. Modify the program to log these messages to a file.
  3. Create a custom logger that prefixes every log message with the current date and time.

Solutions and tips for these exercises can be found in the official Go documentation and 'log' package source code. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Image Converter

Convert between different image formats.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help