Golang log.Panicln Function

The log.Panicln function in Golang is part of the log package and is used to log a message with a newline at the end and then immediately trigger a panic. This function is particularly useful when you need to log an error or critical condition in a simple format and ensure that the program’s execution stops with a panic.

Table of Contents

  1. Introduction
  2. log.Panicln Function Syntax
  3. Examples
    • Basic Usage
    • Logging and Panicking on Critical Errors
    • Using log.Panicln in Goroutines
  4. Real-World Use Case Example
  5. Conclusion

Introduction

The log.Panicln function provides a straightforward way to log error messages followed by a newline and then trigger a panic, which stops the normal flow of the program. Unlike log.Fatal, which terminates the program immediately, log.Panicln allows the panic to propagate up the call stack, potentially being recovered elsewhere in the program.

log.Panicln Function Syntax

The syntax for the log.Panicln function is as follows:

func Panicln(v ...interface{})

Parameters:

  • v ...interface{}: The message or variables to be logged. This is a variadic parameter, meaning you can pass multiple arguments of any type.

Behavior:

  • Logs the message: The function logs the provided message(s) using the standard logger, automatically appending a newline.
  • Triggers a panic: After logging the message, the function calls panic, which stops the normal execution of the program and begins unwinding the stack.

Examples

Basic Usage

This example demonstrates how to use log.Panicln to log a message and trigger a panic.

Example

package main

import (
	"log"
)

func main() {
	log.Panicln("A critical error occurred!")
}

Output:

2024/08/10 12:34:56 A critical error occurred!
panic: A critical error occurred!

Explanation:

  • The log.Panicln function logs the message "A critical error occurred!" with a newline at the end and then triggers a panic, which stops the normal flow of the program and produces a stack trace.

Logging and Panicking on Critical Errors

This example shows how to use log.Panicln to handle critical errors that should cause the program to stop.

Example

package main

import (
	"log"
	"os"
)

func main() {
	fileName := "nonexistentfile.txt"
	file, err := os.Open(fileName)
	if err != nil {
		log.Panicln("Error opening file:", fileName, err)
	}
	defer file.Close()

	// Additional file operations...
}

Output:

2024/08/10 12:34:56 Error opening file: nonexistentfile.txt open nonexistentfile.txt: no such file or directory
panic: Error opening file: nonexistentfile.txt open nonexistentfile.txt: no such file or directory

Explanation:

  • The log.Panicln function logs the error message along with the file name and error details, and then triggers a panic, allowing the program to stop execution and print a stack trace.

Using log.Panicln in Goroutines

This example demonstrates how to use log.Panicln within a goroutine to log an error and trigger a panic that can be recovered.

Example

package main

import (
	"log"
	"sync"
)

func worker(wg *sync.WaitGroup) {
	defer wg.Done()
	defer func() {
		if r := recover(); r != nil {
			log.Println("Recovered from panic:", r)
		}
	}()
	log.Panicln("A critical error in worker!")
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go worker(&wg)
	wg.Wait()
	log.Println("Program finished.")
}

Output:

2024/08/10 12:34:56 A critical error in worker!
panic: A critical error in worker!

2024/08/10 12:34:56 Recovered from panic: A critical error in worker!
2024/08/10 12:34:56 Program finished.

Explanation:

  • The log.Panicln function triggers a panic inside the goroutine. The recover function catches the panic, allowing the program to handle the error and continue.

Real-World Use Case Example: Panic on Unrecoverable Network Error

A practical use case for log.Panicln is handling unrecoverable network errors, such as failing to start a server due to an invalid configuration.

Example: Handling a Fatal Network Error

package main

import (
	"log"
	"net"
)

func startServer(port int) {
	address := fmt.Sprintf(":%d", port)
	listener, err := net.Listen("tcp", address)
	if err != nil {
		log.Panicln("Failed to start server on port", port, err)
	}
	defer listener.Close()

	log.Println("Server started on port", port)
	// Additional server operations...
}

func main() {
	port := 8080
	startServer(port)
}

Explanation:

  • The log.Panicln function is used to handle errors that occur when starting a network server. If the server fails to start due to an invalid configuration or another issue, the program logs the error and triggers a panic, stopping the server from continuing.

Conclusion

The log.Panicln function in Go is used for logging error messages with a newline and triggering a panic when a critical error occurs. Unlike log.Fatal, log.Panicln allows the panic to be recovered, giving you the flexibility to handle the error or stop the program’s execution. Whether you’re dealing with file operations, network servers, or goroutines, log.Panicln provides a straightforward way to handle fatal errors in your Go applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top