1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00
v2fly/common/log/log.go

67 lines
1.2 KiB
Go
Raw Normal View History

2018-04-03 16:34:59 -04:00
package log // import "v2ray.com/core/common/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
"v2ray.com/core/common/serial"
)
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)
}
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
}
var (
2018-01-05 18:32:21 -05:00
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
}