wttr.in/internal/logging/suppress.go

85 lines
1.6 KiB
Go
Raw Normal View History

2022-12-03 15:08:43 +00:00
package logging
2022-11-20 16:45:06 +00:00
import (
"os"
"strings"
"sync"
)
// LogSuppressor provides io.Writer interface for logging
// with lines suppression. For usage with log.Logger.
type LogSuppressor struct {
filename string
suppress []string
linePrefix string
logFile *os.File
m sync.Mutex
}
// NewLogSuppressor creates a new LogSuppressor for specified
// filename and lines to be suppressed.
2022-12-04 09:35:58 +00:00
//
// If filename is empty, log entries will be printed to stderr.
2022-11-20 16:45:06 +00:00
func NewLogSuppressor(filename string, suppress []string, linePrefix string) *LogSuppressor {
return &LogSuppressor{
filename: filename,
suppress: suppress,
linePrefix: linePrefix,
}
}
// Open opens log file.
func (ls *LogSuppressor) Open() error {
2022-12-11 13:28:34 +00:00
var err error
2022-12-04 09:35:58 +00:00
if ls.filename == "" {
return nil
}
2022-12-11 13:28:34 +00:00
//nolint:nosnakecase
ls.logFile, err = os.OpenFile(ls.filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
2022-11-20 16:45:06 +00:00
return err
}
// Close closes log file.
func (ls *LogSuppressor) Close() error {
2022-12-04 09:35:58 +00:00
if ls.filename == "" {
return nil
}
2022-12-11 13:28:34 +00:00
2022-11-20 16:45:06 +00:00
return ls.logFile.Close()
}
// Write writes p to log, and returns number f bytes written.
// Implements io.Writer interface.
2022-12-11 13:28:34 +00:00
func (ls *LogSuppressor) Write(p []byte) (int, error) {
var output string
2022-11-20 16:45:06 +00:00
2022-12-04 09:35:58 +00:00
if ls.filename == "" {
return os.Stdin.Write(p)
}
2022-11-20 16:45:06 +00:00
ls.m.Lock()
defer ls.m.Unlock()
lines := strings.Split(string(p), ls.linePrefix)
for _, line := range lines {
2022-12-11 13:28:34 +00:00
if (func(line string) bool {
2022-11-20 16:45:06 +00:00
for _, suppress := range ls.suppress {
if strings.Contains(line, suppress) {
return true
}
}
2022-12-11 13:28:34 +00:00
2022-11-20 16:45:06 +00:00
return false
2022-12-11 13:28:34 +00:00
})(line) {
2022-11-20 16:45:06 +00:00
continue
}
output += line
}
2022-12-11 13:28:34 +00:00
return ls.logFile.Write([]byte(output))
2022-11-20 16:45:06 +00:00
}