How to Log Messages to Both Console and File in Go?

Patricia Arquette
Release: 2024-11-15 06:10:03
Original
183 people have browsed it

How to Log Messages to Both Console and File in Go?

How to Log Messages to Multiple Destinations in Go

When logging messages in Go, it may be necessary to output logs to both the console and a file simultaneously. While it's straightforward to direct messages solely to a file using log.SetOutput(logFile), there's a way to enable logging in both terminals and target files.

Implementing Multiple Destinations

To achieve logging in multiple destinations, utilize the io.MultiWriter. As implied by its name, MultiWriter facilitates writing to multiple writers concurrently, similar to the Unix tee(1) command.

Here's how to implement this using MultiWriter:

import (
  "os"
  "io"
  "log"
)

func main() {
  logFile, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
  if err != nil {
    panic(err)
  }
  
  // Initialize io.MultiWriter to write to both file and console
  mw := io.MultiWriter(os.Stdout, logFile)
  
  // Set output to MultiWriter
  log.SetOutput(mw)
}
Copy after login

In this example, mw is an io.MultiWriter instance that writes to both os.Stdout (console) and the logFile. By setting log.SetOutput(mw), all subsequent log messages will be printed in the console and logged to the specified file.

The above is the detailed content of How to Log Messages to Both Console and File in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template