123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- package clog
- import "fmt"
- type Logger interface {
-
- Level() LEVEL
-
- Init(interface{}) error
-
- ExchangeChans(chan<- error) chan *Message
-
- Start()
-
- Destroy()
- }
- type Adapter struct {
- level LEVEL
- msgChan chan *Message
- quitChan chan struct{}
- errorChan chan<- error
- }
- type Factory func() Logger
- var factories = map[MODE]Factory{}
- func Register(mode MODE, f Factory) {
- if f == nil {
- panic("clog: register function is nil")
- }
- if factories[mode] != nil {
- panic("clog: register duplicated mode '" + mode + "'")
- }
- factories[mode] = f
- }
- type receiver struct {
- Logger
- mode MODE
- msgChan chan *Message
- }
- var (
-
- receivers []*receiver
- errorChan = make(chan error, 5)
- quitChan = make(chan struct{})
- )
- func init() {
-
- go func() {
- for {
- select {
- case err := <-errorChan:
- fmt.Printf("clog: unable to write message: %v\n", err)
- case <-quitChan:
- return
- }
- }
- }()
- }
- func New(mode MODE, cfg interface{}) error {
- factory, ok := factories[mode]
- if !ok {
- return fmt.Errorf("unknown mode '%s'", mode)
- }
- logger := factory()
- if err := logger.Init(cfg); err != nil {
- return err
- }
- msgChan := logger.ExchangeChans(errorChan)
-
- hasFound := false
- for i := range receivers {
- if receivers[i].mode == mode {
- hasFound = true
-
- receivers[i].Destroy()
-
- receivers[i].Logger = logger
- receivers[i].msgChan = msgChan
- break
- }
- }
- if !hasFound {
- receivers = append(receivers, &receiver{
- Logger: logger,
- mode: mode,
- msgChan: msgChan,
- })
- }
- go logger.Start()
- return nil
- }
- func Delete(mode MODE) {
- foundIdx := -1
- for i := range receivers {
- if receivers[i].mode == mode {
- foundIdx = i
- receivers[i].Destroy()
- }
- }
- if foundIdx >= 0 {
- newList := make([]*receiver, len(receivers)-1)
- copy(newList, receivers[:foundIdx])
- copy(newList[foundIdx:], receivers[foundIdx+1:])
- receivers = newList
- }
- }
|