github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/common/log/log.go (about)

     1  package log // import "v2ray.com/core/common/log"
     2  
     3  import (
     4  	"sync"
     5  
     6  	"v2ray.com/core/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 (
    36  	logHandler syncHandler
    37  )
    38  
    39  // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded.
    40  func RegisterHandler(handler Handler) {
    41  	if handler == nil {
    42  		panic("Log handler is nil")
    43  	}
    44  	logHandler.Set(handler)
    45  }
    46  
    47  type syncHandler struct {
    48  	sync.RWMutex
    49  	Handler
    50  }
    51  
    52  func (h *syncHandler) Handle(msg Message) {
    53  	h.RLock()
    54  	defer h.RUnlock()
    55  
    56  	if h.Handler != nil {
    57  		h.Handler.Handle(msg)
    58  	}
    59  }
    60  
    61  func (h *syncHandler) Set(handler Handler) {
    62  	h.Lock()
    63  	defer h.Unlock()
    64  
    65  	h.Handler = handler
    66  }