Skip to content

Commit

Permalink
Fixed write file return ErrShortWrite error in the concurrent scene.
Browse files Browse the repository at this point in the history
  • Loading branch information
mstmdev committed Dec 10, 2021
1 parent 61355bf commit c2cfb96
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v0.0.6
v0.0.7
21 changes: 15 additions & 6 deletions file_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,14 @@ type fileLogger struct {
type logMsg struct {
log []byte
closed bool
flush bool
}

var (
flushLogMsg = logMsg{flush: true}
closeLogMsg = logMsg{closed: true}
)

// NewFileLogger get a file logger
func NewFileLogger(level Level, logDir string, filePrefix string) (Logger, error) {
return NewFileLoggerWithAutoFlush(level, logDir, filePrefix, false, time.Duration(0))
Expand All @@ -36,7 +42,7 @@ func NewFileLogger(level Level, logDir string, filePrefix string) (Logger, error
func NewFileLoggerWithAutoFlush(level Level, logDir string, filePrefix string, autoFlush bool, flushInterval time.Duration) (Logger, error) {
logger := &fileLogger{
logDir: logDir,
in: make(chan logMsg, 10),
in: make(chan logMsg, 100),
close: make(chan bool, 1),
filePrefix: filePrefix,
autoFlush: autoFlush,
Expand All @@ -61,7 +67,7 @@ func (l *fileLogger) Close() error {
// stop a new log to write
l.closed = true
// send a closed message
l.in <- logMsg{closed: true}
l.in <- closeLogMsg
// wait to receive a close finished message
<-l.close
return nil
Expand Down Expand Up @@ -116,9 +122,12 @@ func (l *fileLogger) write() {
l.writer.Flush()
}
l.close <- true
return
}
if l.initialized && l.writer != nil && len(msg.log) > 0 {
} else if msg.flush && l.initialized && l.writer != nil && l.writer.Buffered() > 0 {
// received a flush message, flush logs to file
if err := l.writer.Flush(); err != nil {
l.innerLog("file logger flush log error. %s", err)
}
} else if l.initialized && l.writer != nil && len(msg.log) > 0 {
if _, err := l.writer.Write(msg.log); err != nil {
l.innerLog("file logger write log error. %s", err)
}
Expand Down Expand Up @@ -146,7 +155,7 @@ func (l *fileLogger) startAutoFlush() {
return
}
if l.writer.Buffered() > 0 {
l.writer.Flush()
l.in <- flushLogMsg
wait = l.flushInterval
nop = 0
} else {
Expand Down

0 comments on commit c2cfb96

Please sign in to comment.