123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package clog
- import (
- "log"
- "github.com/fatih/color"
- )
- var consoleColors = []func(a ...interface{}) string{
- color.New(color.FgBlue).SprintFunc(),
- color.New(color.FgGreen).SprintFunc(),
- color.New(color.FgYellow).SprintFunc(),
- color.New(color.FgRed).SprintFunc(),
- color.New(color.FgHiRed).SprintFunc(),
- }
- type ConsoleConfig struct {
-
- Level LEVEL
-
- BufferSize int64
- }
- type console struct {
- *log.Logger
- Adapter
- }
- func newConsole() Logger {
- return &console{
- Logger: log.New(color.Output, "", log.Ldate|log.Ltime),
- Adapter: Adapter{
- quitChan: make(chan struct{}),
- },
- }
- }
- func (c *console) Level() LEVEL { return c.level }
- func (c *console) Init(v interface{}) error {
- cfg, ok := v.(ConsoleConfig)
- if !ok {
- return ErrConfigObject{"ConsoleConfig", v}
- }
- if !isValidLevel(cfg.Level) {
- return ErrInvalidLevel{}
- }
- c.level = cfg.Level
- c.msgChan = make(chan *Message, cfg.BufferSize)
- return nil
- }
- func (c *console) ExchangeChans(errorChan chan<- error) chan *Message {
- c.errorChan = errorChan
- return c.msgChan
- }
- func (c *console) write(msg *Message) {
- c.Logger.Print(consoleColors[msg.Level](msg.Body))
- }
- func (c *console) Start() {
- LOOP:
- for {
- select {
- case msg := <-c.msgChan:
- c.write(msg)
- case <-c.quitChan:
- break LOOP
- }
- }
- for {
- if len(c.msgChan) == 0 {
- break
- }
- c.write(<-c.msgChan)
- }
- c.quitChan <- struct{}{}
- }
- func (c *console) Destroy() {
- c.quitChan <- struct{}{}
- <-c.quitChan
- close(c.msgChan)
- close(c.quitChan)
- }
- func init() {
- Register(CONSOLE, newConsole)
- }
|