diff --git a/Makefile b/Makefile index 506fb6a..9674c9f 100644 --- a/Makefile +++ b/Makefile @@ -1,2 +1,4 @@ srv: srv.go internal/*/*.go go build -o srv ./ +test: + go test ./ diff --git a/internal/logging/logging.go b/internal/logging/logging.go index e58b6e1..d1c8e75 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -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,23 +77,25 @@ func (rl *RequestLogger) flush() error { return nil } - // Generate log output. - output := "" - for k, hitsNumber := range rl.buf { - output += fmt.Sprintf("%s %3d %s\n", time.Now().Format(time.RFC3339), hitsNumber, k.String()) - } + if rl.filename != "" { + // Generate log output. + output := "" + for k, hitsNumber := range rl.buf { + output += fmt.Sprintf("%s %3d %s\n", time.Now().Format(time.RFC3339), hitsNumber, k.String()) + } - // Open log file. - f, err := os.OpenFile(rl.filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) - if err != nil { - return err - } - defer f.Close() + // Open log file. + f, err := os.OpenFile(rl.filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + if err != nil { + return err + } + defer f.Close() - // Save output to log file. - _, err = f.Write([]byte(output)) - if err != nil { - return err + // Save output to log file. + _, err = f.Write([]byte(output)) + if err != nil { + return err + } } // Flush buffer. diff --git a/internal/logging/suppress.go b/internal/logging/suppress.go index 76cecce..ab217f2 100644 --- a/internal/logging/suppress.go +++ b/internal/logging/suppress.go @@ -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()