diff --git a/console.go b/console.go index fabfddb..b8c413a 100644 --- a/console.go +++ b/console.go @@ -15,6 +15,11 @@ const ( type ConsoleAppender struct { } +// Close implements LoggerAppender. +func (c *ConsoleAppender) Close() { + +} + func (c *ConsoleAppender) GetName() string { return "console" } diff --git a/file.go b/file.go index d4c71f0..81b9f18 100644 --- a/file.go +++ b/file.go @@ -9,6 +9,13 @@ type FileAppender struct { filePath string lchan chan LogEvent file *os.File + stopChan chan struct{} +} + +// Close implements LoggerAppender. +func (f *FileAppender) Close() { + //send stop signal + f.stopChan <- struct{}{} } func (f *FileAppender) GetName() string { @@ -17,6 +24,7 @@ func (f *FileAppender) GetName() string { func (f *FileAppender) start() { f.lchan = make(chan LogEvent, 10) + f.stopChan = make(chan struct{}) if f.file == nil || int(f.file.Fd()) == -1 { dirName := filepath.Dir(f.filePath) _, err := os.Stat(dirName) @@ -29,9 +37,14 @@ func (f *FileAppender) start() { go func() { defer f.file.Close() for { - logEvent := <-f.lchan - logMsg := format(logEvent) - f.file.WriteString(logMsg) + select { + case <-f.stopChan: + return + case logEvent := <-f.lchan: + logMsg := format(logEvent) + f.file.WriteString(logMsg) + } + } }() } diff --git a/main.go b/main.go index ed6aa82..979cc46 100644 --- a/main.go +++ b/main.go @@ -56,6 +56,7 @@ type LogEvent struct { type LoggerAppender interface { GetName() string Append(logEvent LogEvent) + Close() } var consoleAppender LoggerAppender = &ConsoleAppender{}