Home >Backend Development >Golang >How to Log to Both Console and File Simultaneously in Go?

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

DDD
DDDOriginal
2024-11-11 01:19:02900browse

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

Logging Simultaneously to Console and File in Go

To direct log messages to a file, the code typically uses log.SetOutput(logFile). However, if you desire both console output and logging to a file, here's a solution using io.MultiWriter.

What is io.MultiWriter?

An io.MultiWriter allows writing data to multiple destinations simultaneously. It resembles the behavior of the Unix tee command.

Solution

To log to both the console and a file:

  1. Create a file for logging:
logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
if err != nil {
    panic(err)
}
  1. Create a MultiWriter to combine console and file outputs:
mw := io.MultiWriter(os.Stdout, logFile)
  1. Set the default output destination for logs:
log.SetOutput(mw)

Example

package main

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

func main() {
    logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
    if err != nil {
        panic(err)
    }

    mw := io.MultiWriter(os.Stdout, logFile)
    log.SetOutput(mw)

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

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

Statement:
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