php小編香蕉在這篇文章中將要介紹的是如何將日誌寫入終端機和檔案。在開發過程中,日誌是非常重要的,它可以幫助我們追蹤和偵錯程式碼的問題。將日誌寫入終端和檔案是常見的兩種方式,它們各有優劣,可以根據具體需求選擇合適的方式。接下來,我們將詳細討論如何使用php程式碼將日誌寫入終端機和文件,並介紹一些常用的日誌寫入函數和技巧,幫助開發者更好地進行日誌管理。
我有這個函數可以將日誌寫入終端機和日誌檔案:
// Run an executable and print its log in real-time and print its log into a file too. func RunWithLog(pthExe string, arg []string, fLog *os.File, dir string) error { cmd := exec.Command(pthExe, arg...) if dir != "" { cmd.Dir = dir } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } var wg sync.WaitGroup wg.Add(4) go streamRealTime(stdout, &wg) go streamRealTime(stderr, &wg) go streamToLogFile(stdout, fLog, &wg) go streamToLogFile(stderr, fLog, &wg) err = cmd.Start() if err != nil { return err } wg.Wait() err = cmd.Wait() return err } func streamRealTime(output io.ReadCloser, wg *sync.WaitGroup) { defer wg.Done() scanner := bufio.NewScanner(output) scanner.Split(bufio.ScanRunes) for scanner.Scan() { fmt.Print(scanner.Text()) } err := scanner.Err() if err != nil { log.Printf("error: write log to terminal: %s", err.Error()) } } func streamToLogFile(output io.ReadCloser, fLog *os.File, wg *sync.WaitGroup) { defer wg.Done() scanner := bufio.NewScanner(output) scanner.Split(bufio.ScanRunes) for scanner.Scan() { _, err := fLog.WriteString(scanner.Text()) if err != nil { log.Printf("error: write log to file: %s", err.Error()) } } err := scanner.Err() if err != nil { log.Printf("error: write log to file: %s", err.Error()) } }
上面的函數呼叫:
// Log file. fLog, err := os.OpenFile(pathLog, os.O_APPEND, os.ModeAppend) if err != nil { return err } defer fLog.Close() err = RunWithLog(pathExe, []string{"-b"}, fLog, workDir) // ...
問題是有些日誌行印到終端,有些行會印到文件,如下所示:
如何確保所有日誌行都列印到終端機和檔案?
日誌透過以下方式列印到終端機和檔案:
// Run an executable and print its log real-time and print its log into a file too. func RunWithLog(pthExe string, arg []string, fLog *os.File, dir string) error { cmd := exec.Command(pthExe, arg...) if dir != "" { cmd.Dir = dir } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } var wg sync.WaitGroup wg.Add(2) go streamLogs(stdout, fLog, &wg) go streamLogs(stderr, fLog, &wg) err = cmd.Start() if err != nil { return err } wg.Wait() err = cmd.Wait() return err } // Stream logs to both terminal and a file. func streamLogs(output io.ReadCloser, fLog *os.File, wg *sync.WaitGroup) { defer wg.Done() scanner := bufio.NewScanner(output) scanner.Split(bufio.ScanRunes) for scanner.Scan() { // Stream to terminal: fmt.Print(scanner.Text()) // Stream to a file: _, err := fLog.WriteString(scanner.Text()) if err != nil { log.Printf("error: write log to file: %s", err.Error()) } } err := scanner.Err() if err != nil { log.Printf("error: write log to terminal: %s", err.Error()) } }
日誌是相同的:
以上是將日誌寫入終端機和文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!