Xray-core/common/log/log.go

65 lines
1.2 KiB
Go
Raw Permalink Normal View History

2020-12-04 01:36:16 +00:00
package log // import "github.com/xtls/xray-core/common/log"
2020-11-25 11:01:53 +00:00
import (
"sync"
2020-12-04 01:36:16 +00:00
"github.com/xtls/xray-core/common/serial"
2020-11-25 11:01:53 +00:00
)
// Message is the interface for all log messages.
type Message interface {
String() string
}
// Handler is the interface for log handler.
type Handler interface {
Handle(msg Message)
}
// GeneralMessage is a general log message that can contain all kind of content.
type GeneralMessage struct {
Severity Severity
Content interface{}
}
// String implements Message.
func (m *GeneralMessage) String() string {
return serial.Concat("[", m.Severity, "] ", m.Content)
}
// Record writes a message into log stream.
func Record(msg Message) {
logHandler.Handle(msg)
}
2021-10-19 16:57:14 +00:00
var logHandler syncHandler
2020-11-25 11:01:53 +00:00
2022-01-13 02:51:47 +00:00
// RegisterHandler registers a new handler as current log handler. Previous registered handler will be discarded.
2020-11-25 11:01:53 +00:00
func RegisterHandler(handler Handler) {
if handler == nil {
panic("Log handler is nil")
}
logHandler.Set(handler)
}
type syncHandler struct {
sync.RWMutex
Handler
}
func (h *syncHandler) Handle(msg Message) {
h.RLock()
defer h.RUnlock()
if h.Handler != nil {
h.Handler.Handle(msg)
}
}
func (h *syncHandler) Set(handler Handler) {
h.Lock()
defer h.Unlock()
h.Handler = handler
}