github.com/moqsien/xraycore@v1.8.5/common/log/log.go (about)

     1  package log // import "github.com/moqsien/xraycore/common/log"
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/moqsien/xraycore/common/serial"
     7  )
     8  
     9  // Message is the interface for all log messages.
    10  type Message interface {
    11  	String() string
    12  }
    13  
    14  // Handler is the interface for log handler.
    15  type Handler interface {
    16  	Handle(msg Message)
    17  }
    18  
    19  // GeneralMessage is a general log message that can contain all kind of content.
    20  type GeneralMessage struct {
    21  	Severity Severity
    22  	Content  interface{}
    23  }
    24  
    25  // String implements Message.
    26  func (m *GeneralMessage) String() string {
    27  	return serial.Concat("[", m.Severity, "] ", m.Content)
    28  }
    29  
    30  // Record writes a message into log stream.
    31  func Record(msg Message) {
    32  	logHandler.Handle(msg)
    33  }
    34  
    35  var logHandler syncHandler
    36  
    37  // RegisterHandler registers a new handler as current log handler. Previous registered handler will be discarded.
    38  func RegisterHandler(handler Handler) {
    39  	if handler == nil {
    40  		panic("Log handler is nil")
    41  	}
    42  	logHandler.Set(handler)
    43  }
    44  
    45  type syncHandler struct {
    46  	sync.RWMutex
    47  	Handler
    48  }
    49  
    50  func (h *syncHandler) Handle(msg Message) {
    51  	h.RLock()
    52  	defer h.RUnlock()
    53  
    54  	if h.Handler != nil {
    55  		h.Handler.Handle(msg)
    56  	}
    57  }
    58  
    59  func (h *syncHandler) Set(handler Handler) {
    60  	h.Lock()
    61  	defer h.Unlock()
    62  
    63  	h.Handler = handler
    64  }