orange/logger/stream.go

48 lines
980 B
Go

package logger
import (
"bytes"
"fmt"
"os"
)
// StreamMessageHandler
type StreamMessageHandler struct {
LogDir string
LogFileName string
LogExt string
LogBuffer bytes.Buffer
}
// 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)
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()
}
}