如何在Golang的文本文件中捕获fmt.Print输出

There are certain fmt.Print statements that I want to save into a .txt file.

I don't want to store all print statments. Can I do this ?

package main

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

func main() {
    file, err := os.Create("myfile")
    if err != nil {
        log.Fatal(err)
    }

    mw := io.MultiWriter(os.Stdout, file)
    fmt.Fprintln(mw, "This line will be written to stdout and also to a file")
}

Use the fmt.Fprint() method for calls you want to save to a file. There are also fmt.Fprintf() and fmt.Fprintln().

These functions take a destination io.Writer as the first argument, to which you can pass your file (*os.File).

For example:

f, err := os.Open("data.txt")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

fmt.Println("This goes to standard output.")
fmt.Fprintln(f, "And this goes to the file")
fmt.Fprintf(f, "Also to file, with some formatting. Time: %v, line: %d
",
    time.Now(), 2)

If you want all fmt.PrintXX() calls to go to the file which you have no control over (e.g. you can't change them to fmt.FprintXX() because they are part of another library), you may change os.Stdout temporarily, so all further fmt.PrintXX() calls will write to the output you set, e.g.:

// Temporarily set your file as the standard output (and save the old)
old, os.Stdout = os.Stdout, f

// Now all fmt.PrintXX() calls output to f
somelib.DoSomething()

// Restore original standard output
os.Stdout = old