我想將日志資訊發送到套接字,為此,我需要先捕獲 os.stdout。我知道我可以用 os.pipe 重定向 os.stdout。但是有沒有辦法我直接從 os.stdout 使用 bufio.NewReader 或 bufio.NewScanner 讀取?
func Start() {
//dataChan := make(chan string)
outC := make(chan string, 3)
defer close(outC)
conn, err := net.Dial("tcp", "localhost:9090")
if err != nil {
log.Fatal(err)
}
fmt.Println("first line!")
fmt.Println("second line!")
fmt.Println("third line!")
// write to channel
go func() {
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
outC <- scanner.Text() "\n"
err = scanner.Err()
if err != nil {
log.Fatal(err)
}
}
}()
// read from channel and print to connection
go func() {
out := <-outC
for {
conn.Write([]byte(out "\n"))
}
}()
}
uj5u.com熱心網友回復:
您可以通過os.Pipe讀取標準輸出
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()
fmt.Println("first line!")
fmt.Println("second line!")
fmt.Println("third line!")
w.Close()
os.Stdout = old // restore stdout
for {
select {
case out := <-outC:
conn.Write([]byte("read " out "\n"))
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514614.html
標籤:去日志记录io缓冲
