首頁 > 後端開發 > Golang > 主體

如何在 Go 中將訊息記錄到控制台和檔案?

Patricia Arquette
發布: 2024-11-15 06:10:03
原創
186 人瀏覽過

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)
}
登入後複製

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.

以上是如何在 Go 中將訊息記錄到控制台和檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板