github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/common/log/log.go (about)

     1  package log
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/v2fly/v2ray-core/v5/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  // Follower is the interface for following logs.
    20  type Follower interface {
    21  	AddFollower(func(msg Message))
    22  	RemoveFollower(func(msg Message))
    23  }
    24  
    25  // GeneralMessage is a general log message that can contain all kind of content.
    26  type GeneralMessage struct {
    27  	Severity Severity
    28  	Content  interface{}
    29  }
    30  
    31  // String implements Message.
    32  func (m *GeneralMessage) String() string {
    33  	return serial.Concat("[", m.Severity, "] ", m.Content)
    34  }
    35  
    36  // Record writes a message into log stream.
    37  func Record(msg Message) {
    38  	logHandler.Handle(msg)
    39  }
    40  
    41  var logHandler syncHandler
    42  
    43  // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded.
    44  func RegisterHandler(handler Handler) {
    45  	if handler == nil {
    46  		panic("Log handler is nil")
    47  	}
    48  	logHandler.Set(handler)
    49  }
    50  
    51  type syncHandler struct {
    52  	sync.RWMutex
    53  	Handler
    54  }
    55  
    56  func (h *syncHandler) Handle(msg Message) {
    57  	h.RLock()
    58  	defer h.RUnlock()
    59  
    60  	if h.Handler != nil {
    61  		h.Handler.Handle(msg)
    62  	}
    63  }
    64  
    65  func (h *syncHandler) Set(handler Handler) {
    66  	h.Lock()
    67  	defer h.Unlock()
    68  
    69  	h.Handler = handler
    70  }