ctop/logging/main.go

83 lines
1.4 KiB
Go
Raw Normal View History

package logging
import (
"os"
"time"
"github.com/op/go-logging"
)
const (
2017-02-04 08:59:33 +00:00
size = 1024
)
2017-02-11 03:58:26 +00:00
var (
2017-02-12 05:10:40 +00:00
Log *CTopLogger
exited bool
level = logging.INFO // default level
2017-02-11 03:58:26 +00:00
format = logging.MustStringFormatter(
2017-02-16 23:32:16 +00:00
`%{color}%{time:15:04:05.000} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
2017-02-11 03:58:26 +00:00
)
)
type CTopLogger struct {
*logging.Logger
backend *logging.MemoryBackend
2017-02-04 08:59:33 +00:00
}
func Init() *CTopLogger {
2017-02-12 05:10:40 +00:00
if Log == nil {
2017-02-16 23:32:16 +00:00
logging.SetFormatter(format) // setup default formatter
2017-02-12 05:10:40 +00:00
Log = &CTopLogger{
logging.MustGetLogger("ctop"),
logging.NewMemoryBackend(size),
}
2017-02-04 08:59:33 +00:00
if debugMode() {
level = logging.DEBUG
StartServer()
}
2017-02-16 23:32:16 +00:00
backendLvl := logging.AddModuleLevel(Log.backend)
backendLvl.SetLevel(level, "")
logging.SetBackend(backendLvl)
2017-02-12 05:10:40 +00:00
Log.Notice("logger initialized")
2017-02-04 08:59:33 +00:00
}
2017-02-12 05:10:40 +00:00
return Log
2017-02-04 08:59:33 +00:00
}
func (log *CTopLogger) tail() chan string {
stream := make(chan string)
node := log.backend.Head()
go func() {
for {
stream <- node.Record.Formatted(0)
for {
nnode := node.Next()
if nnode != nil {
node = nnode
break
}
if exited {
close(stream)
return
}
time.Sleep(1 * time.Second)
}
}
}()
return stream
}
func (log *CTopLogger) Exit() {
exited = true
StopServer()
}
func debugMode() bool { return os.Getenv("CTOP_DEBUG") == "1" }
func debugModeTCP() bool { return os.Getenv("CTOP_DEBUG_TCP") == "1" }