github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/log/collectorHook.go (about)

     1  package log
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/sirupsen/logrus"
     7  )
     8  
     9  // logCollectorHook provides a logrus hook which stores details about any logs of each step.
    10  // This is helpful in order to transfer the logs and error details to an logging system as Splunk
    11  // and by that make it possible to have a better investigation of any error.
    12  
    13  type CollectorHook struct {
    14  	CorrelationID string
    15  	Messages      []Message
    16  	// TODO: log Levels?
    17  }
    18  
    19  // Levels returns the supported log level of the hook.
    20  func (f *CollectorHook) Levels() []logrus.Level {
    21  	return []logrus.Level{logrus.InfoLevel, logrus.DebugLevel, logrus.WarnLevel, logrus.ErrorLevel, logrus.PanicLevel, logrus.FatalLevel}
    22  }
    23  
    24  type Message struct {
    25  	Time    time.Time    `json:"time,omitempty"`
    26  	Level   logrus.Level `json:"level,omitempty"`
    27  	Message string       `json:"message,omitempty"`
    28  	Data    interface{}  `json:"data,omitempty"`
    29  }
    30  
    31  // Fire creates a new event from the logrus and stores it in the SplunkHook object
    32  func (f *CollectorHook) Fire(entry *logrus.Entry) error {
    33  	message := Message{
    34  		Time:    entry.Time,
    35  		Data:    entry.Data,
    36  		Message: entry.Message,
    37  	}
    38  	f.Messages = append(f.Messages, message)
    39  	return nil
    40  }