2016-11-08 26 views
0

我想要將某些fmt.Print語句保存爲.txt文件。如何在Golang中的文本文件中捕獲fmt.Print輸出

我不想存儲所有的打印語句。我可以這樣做嗎?

+0

https://開頭GOL ang.org/pkg/log/#New –

+0

謝謝,但我沒有記錄。這些是打印聲明 – aaj

+0

對不起。錯過了。但它是相同的[概念](https://golang.org/pkg/fmt/#Fprint) –

回答

2
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") 
} 
1

使用fmt.Fprint()方法調用要保存到文件的呼叫。還有fmt.Fprintf()fmt.Fprintln()

這些函數將目標io.Writer作爲第一個參數,您可以向其傳遞文件(*os.File)。

例如:

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\n", 
    time.Now(), 2) 

如果希望所有fmt.PrintXX()呼叫轉接到你無法控制的文件(例如,你不能改變他們fmt.FprintXX()因爲他們是另一個庫的一部分),你可能暫時改變os.Stdout,因此所有進一步fmt.PrintXX()通話將寫信給你設定的輸出,如:

// 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 
相關問題