github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/log/hooks/log_writer.go (about)

     1  package hooks
     2  
     3  import (
     4  	"io"
     5  	"sync"
     6  
     7  	"github.com/sirupsen/logrus"
     8  	"gopkg.in/natefinch/lumberjack.v2"
     9  )
    10  
    11  func NewLogWriterHook(p string) *LogWriterHook {
    12  	return &LogWriterHook{
    13  		lock: new(sync.Mutex),
    14  		levels: []logrus.Level{
    15  			logrus.DebugLevel,
    16  			logrus.InfoLevel,
    17  		},
    18  		writer: &lumberjack.Logger{
    19  			Filename:   p,
    20  			MaxSize:    500, // megabytes
    21  			MaxBackups: 3,
    22  			MaxAge:     30, //days
    23  		},
    24  	}
    25  }
    26  
    27  func NewLogWriterForErrorHook(p string) *LogWriterHook {
    28  	return &LogWriterHook{
    29  		lock: new(sync.Mutex),
    30  		levels: []logrus.Level{
    31  			logrus.WarnLevel,
    32  			logrus.ErrorLevel,
    33  			logrus.FatalLevel,
    34  			logrus.PanicLevel,
    35  		},
    36  		writer: &lumberjack.Logger{
    37  			Filename:   p + ".wf",
    38  			MaxSize:    500, // megabytes
    39  			MaxBackups: 3,
    40  			MaxAge:     30, //days
    41  		},
    42  	}
    43  }
    44  
    45  type LogWriterHook struct {
    46  	levels []logrus.Level
    47  	writer io.Writer
    48  	lock   *sync.Mutex
    49  }
    50  
    51  func (hook *LogWriterHook) Fire(entry *logrus.Entry) error {
    52  	hook.lock.Lock()
    53  	defer hook.lock.Unlock()
    54  
    55  	msg, err := entry.String()
    56  	if err != nil {
    57  		return err
    58  	} else {
    59  		hook.writer.Write([]byte(msg))
    60  	}
    61  
    62  	return nil
    63  }
    64  
    65  func (hook *LogWriterHook) Levels() []logrus.Level {
    66  	return hook.levels
    67  }