orange/logger/stream.go

48 lines
980 B
Go
Raw Normal View History

2019-10-23 11:39:48 +08:00
package logger
import (
"bytes"
"fmt"
"os"
)
// StreamMessageHandler
type StreamMessageHandler struct {
LogDir string
LogFileName string
LogExt string
LogBuffer bytes.Buffer
2019-10-23 11:39:48 +08:00
}
// Write write log to buffer
func (handler *StreamMessageHandler) Write(message []byte) {
handler.LogBuffer.Write(message)
}
// SyncLog interval sync log stream buffer
func (handler *StreamMessageHandler) SyncLog() {
var logFile *os.File
if handler.LogBuffer.Len() == 0 {
return
}
if handler.LogDir != "" {
logPath := fmt.Sprintf("%s/%s%s", handler.LogDir, handler.LogFileName, handler.LogExt)
logFileTmp, err := os.OpenFile(logPath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
2019-10-23 11:39:48 +08:00
if err != nil {
panic(fmt.Sprintf("log file create error: %v", err))
}
logFile = logFileTmp
defer logFile.Close()
} else {
logFile = os.Stdout
}
if handler.LogBuffer.Len() > 0 {
message := handler.LogBuffer.Bytes()
logFile.Write(message)
handler.LogBuffer.Reset()
}
}