Suppress log if needed

chubin/logging
Igor Chubin 2 years ago
parent 5d86d36b7e
commit a6f2844c67

@ -1,2 +1,4 @@
srv: srv.go internal/*/*.go
go build -o srv ./
test:
go test ./

@ -32,6 +32,9 @@ type logEntry struct {
// NewRequestLogger returns a new RequestLogger for the specified log file.
// Flush logging entries after period of time.
//
// If filename is empty, no log will be written, and all logging entries
// will be silently dropped.
func NewRequestLogger(filename string, period time.Duration) *RequestLogger {
return &RequestLogger{
buf: map[logEntry]int{},
@ -74,6 +77,7 @@ func (rl *RequestLogger) flush() error {
return nil
}
if rl.filename != "" {
// Generate log output.
output := ""
for k, hitsNumber := range rl.buf {
@ -92,6 +96,7 @@ func (rl *RequestLogger) flush() error {
if err != nil {
return err
}
}
// Flush buffer.
rl.buf = map[logEntry]int{}

@ -19,6 +19,8 @@ type LogSuppressor struct {
// NewLogSuppressor creates a new LogSuppressor for specified
// filename and lines to be suppressed.
//
// If filename is empty, log entries will be printed to stderr.
func NewLogSuppressor(filename string, suppress []string, linePrefix string) *LogSuppressor {
return &LogSuppressor{
filename: filename,
@ -29,6 +31,9 @@ func NewLogSuppressor(filename string, suppress []string, linePrefix string) *Lo
// Open opens log file.
func (ls *LogSuppressor) Open() error {
if ls.filename == "" {
return nil
}
var err error
ls.logFile, err = os.OpenFile(ls.filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
return err
@ -36,6 +41,9 @@ func (ls *LogSuppressor) Open() error {
// Close closes log file.
func (ls *LogSuppressor) Close() error {
if ls.filename == "" {
return nil
}
return ls.logFile.Close()
}
@ -46,6 +54,10 @@ func (ls *LogSuppressor) Write(p []byte) (n int, err error) {
output string
)
if ls.filename == "" {
return os.Stdin.Write(p)
}
ls.m.Lock()
defer ls.m.Unlock()

Loading…
Cancel
Save