1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/common/log/log.go

71 lines
1.3 KiB
Go
Raw Normal View History

2021-02-16 15:31:50 -05:00
package log
2017-12-10 16:48:28 -05:00
import (
2018-01-05 18:32:21 -05:00
"sync"
2017-12-10 16:48:28 -05:00
"github.com/v2fly/v2ray-core/v5/common/serial"
2017-12-10 16:48:28 -05:00
)
2017-12-19 16:02:57 -05:00
// Message is the interface for all log messages.
2017-12-10 16:48:28 -05:00
type Message interface {
String() string
}
2017-12-19 16:02:57 -05:00
// Handler is the interface for log handler.
2017-12-10 16:48:28 -05:00
type Handler interface {
Handle(msg Message)
}
// Follower is the interface for following logs.
type Follower interface {
AddFollower(func(msg Message))
RemoveFollower(func(msg Message))
}
2017-12-19 16:02:57 -05:00
// GeneralMessage is a general log message that can contain all kind of content.
2017-12-10 16:48:28 -05:00
type GeneralMessage struct {
Severity Severity
Content interface{}
}
2017-12-19 16:02:57 -05:00
// String implements Message.
2017-12-10 16:48:28 -05:00
func (m *GeneralMessage) String() string {
2018-02-22 09:27:51 -05:00
return serial.Concat("[", m.Severity, "] ", m.Content)
2017-12-10 16:48:28 -05:00
}
2017-12-19 16:02:57 -05:00
// Record writes a message into log stream.
2017-12-10 16:48:28 -05:00
func Record(msg Message) {
2018-01-05 18:32:21 -05:00
logHandler.Handle(msg)
2017-12-10 16:48:28 -05:00
}
2021-05-19 17:28:52 -04:00
var logHandler syncHandler
2017-12-10 16:48:28 -05:00
2017-12-19 16:02:57 -05:00
// RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded.
2017-12-10 16:48:28 -05:00
func RegisterHandler(handler Handler) {
if handler == nil {
panic("Log handler is nil")
}
2018-01-05 18:32:21 -05:00
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
2017-12-10 16:48:28 -05:00
}