github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/log/log.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package log
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"github.com/GeniusesGroup/libgo/event"
     9  	"github.com/GeniusesGroup/libgo/protocol"
    10  )
    11  
    12  type Logger struct {
    13  	event.EventTarget
    14  }
    15  
    16  // PanicHandler recover from panics if exist to prevent app stop.
    17  // Call it by defer in any goroutine due to >> https://github.com/golang/go/issues/20161
    18  func (l *Logger) PanicHandler() {
    19  	var r = recover()
    20  	if r != nil {
    21  		var logEvent protocol.LogEvent
    22  		switch message := r.(type) {
    23  		case protocol.LogEvent:
    24  			logEvent = message
    25  		case protocol.Error:
    26  			logEvent = PanicEvent("Unknown protocol.Error Domain", message.ToString())
    27  		case error:
    28  			logEvent = PanicEvent("Unknown error Domain", message.Error())
    29  		case string:
    30  			logEvent = PanicEvent("Unknown string Domain", message)
    31  		case protocol.Stringer:
    32  			logEvent = PanicEvent("Unknown Stringer Domain", message.ToString())
    33  		default:
    34  			logEvent = PanicEvent("Unknown Domain", fmt.Sprint(r))
    35  		}
    36  		l.Log(logEvent)
    37  	}
    38  }
    39  
    40  func (l *Logger) Log(event protocol.LogEvent) (err protocol.Error) {
    41  	l.DispatchEvent(event)
    42  	// Due to LogEvent is not cancelable, we don't need to check event.DefaultPrevented() before save log.
    43  	// if event.DefaultPrevented() {}
    44  	err = l.saveEvent(event)
    45  	return
    46  }
    47  
    48  func (l *Logger) saveEvent(event protocol.LogEvent) (err protocol.Error) {
    49  	if !CheckLevelEnabled(event.Level()) {
    50  		return
    51  	}
    52  
    53  	// TODO::: First save locally as cache to reduce network trip for non important data??
    54  
    55  	// TODO::: Each day, Save logs to storage(mediatype.LOG.ID()) with NodeID as object ID
    56  	// protocol.App.Objects().
    57  	return
    58  }