xlog/xlog.go

84 lines
1.3 KiB
Go

// vi:ts=4:sts=4:sw=4:noet:tw=72
package xlog
import (
"fmt"
"log"
"os"
"runtime"
)
const (
FATAL = iota
ERROR
WARNING
INFO
DEBUG
)
var levelNames = map[int]string{
FATAL: "[FAT] ",
ERROR: "[ERR] ",
WARNING: "[WRN] ",
INFO: "[INF] ",
DEBUG: "[DBG] ",
}
var logLevel int
var logger *log.Logger
type LogWriter struct {
}
func (w *LogWriter) Write(buf []byte) (int, error) {
fmt.Printf("%s", string(buf))
return len(buf), nil
}
func Init(lvl int) {
logger = log.New(&LogWriter{}, "", log.Ldate|log.Ltime)
logLevel = lvl
}
func Log(lvl int, s string, a ...interface{}) {
if lvl <= logLevel {
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "???"
} else {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
}
l := fmt.Sprintf("%d", line)
logger.Printf(levelNames[lvl]+file+":"+l+": "+s, a...)
}
}
func Debug(s string, a ...interface{}) {
Log(DEBUG, s, a...)
}
func Info(s string, a ...interface{}) {
Log(INFO, s, a...)
}
func Warning(s string, a ...interface{}) {
Log(WARNING, s, a...)
}
func Error(s string, a ...interface{}) {
Log(ERROR, s, a...)
}
func Fatal(s string, a ...interface{}) {
Log(FATAL, s, a...)
os.Exit(0)
}