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,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())
}
// 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
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()
// Save output to log file.
_, err = f.Write([]byte(output))
if err != nil {
return err
}
}
// Flush buffer.

@ -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