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

DDD
Release: 2024-11-11 01:19:02
Original
869 people have browsed it

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)
}
Copy after login
  1. Create a MultiWriter to combine console and file outputs:
mw := io.MultiWriter(os.Stdout, logFile)
Copy after login
  1. Set the default output destination for logs:
log.SetOutput(mw)
Copy after login

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")
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template