【背景】
折腾:
期间,需要去搞懂:
如果新建和设置MultiWriter。
【折腾过程】
1.参考:
去看看:
2.然后去试试代码:var filenameOnly string
filenameOnly = GetCurFilename()
fmt.Println("filenameOnly=", filenameOnly)
var logFilename string = filenameOnly + ".log";
fmt.Println("logFilename=", logFilename)
logFile, err := os.OpenFile(logFilename, os.O_RDWR | os.O_CREATE, 0777)
if err != nil {
fmt.Printf("open file error=%s\r\n", err.Error())
os.Exit(-1)
}
defer logFile.Close()
writers := []io.Writer{
logFile,
os.Stdout,
}
fileAndStdoutWriter := io.MultiWriter(writers...)
fileAndStdoutWriter.Write([]byte("show in both log file and console via multiwriter"))
结果是:
是可以实现对应的效果的:
至此,至少基本实现了:
如何新建和使用MultiWriter了。
【总结】
新建和使用MultiWriter的示例代码如下:var logFilename string = "multiWriterTest.log";
fmt.Println("logFilename=", logFilename)
logFile, err := os.OpenFile(logFilename, os.O_RDWR | os.O_CREATE, 0777)
if err != nil {
fmt.Printf("open file error=%s\r\n", err.Error())
os.Exit(-1)
}
defer logFile.Close()
writers := []io.Writer{
logFile,
os.Stdout,
}
fileAndStdoutWriter := io.MultiWriter(writers...)
fileAndStdoutWriter.Write([]byte("show in both log file and console via multiwriter\r\n"))
虽然效果不是那么爽,但是基本能用。