123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- package log
- import (
- "flag"
- "fmt"
- )
- var (
- h Handler
- level string
- file string
- stdout bool
- defaultLevel int
- levelIndex = map[string]int{
- "debug": debugLevel,
- "DEBUG": debugLevel,
- "info": infoLevel,
- "INFO": infoLevel,
- "warn": warnLevel,
- "WARN": warnLevel,
- "error": errorLevel,
- "ERROR": errorLevel,
- }
- )
- const (
- debugLevel = iota
- infoLevel
- warnLevel
- errorLevel
- )
- func init() {
- flag.StringVar(&level, "level", "", "log level")
- flag.StringVar(&file, "file", "", "log will print into file {log}")
- flag.BoolVar(&stdout, "stdout", true, "log will print into stdout")
- }
- type Config struct {
- Level string `toml:"level"`
- File string `toml:"file"`
- Stdout bool `toml:"stdout"`
- }
- func Init(c *Config) {
- if c == nil {
- c = &Config{
- Level: "info",
- Stdout: true,
- }
- }
- if file != "" {
- c.File = file
- }
- if level != "" {
- c.Level = level
- }
- var ok bool
- defaultLevel, ok = levelIndex[c.Level]
- if !ok {
- defaultLevel = infoLevel
- }
- var handlers []Handler
- if c.Stdout && stdout {
- handlers = append(handlers, NewStdHandler())
- }
- if c.File != "" {
- handlers = append(handlers, NewFileHandler(c.File))
- }
- h = Handlers(handlers)
- }
- func Info(args ...interface{}) {
- logs("INFO", args...)
- }
- func Infof(format string, args ...interface{}) {
- logf("INFO", format, args...)
- }
- func Warn(args ...interface{}) {
- logs("WARN", args...)
- }
- func Warnf(format string, args ...interface{}) {
- logf("WARN", format, args...)
- }
- func Error(args ...interface{}) {
- logs("ERROR", args...)
- }
- func Errorf(format string, args ...interface{}) {
- logf("ERROR", format, args...)
- }
- func Panic(v interface{}) {
- panic(v)
- }
- func Panicf(format string, args ...interface{}) {
- panic(fmt.Sprintf(format, args...))
- }
- func logf(lv, format string, args ...interface{}) {
- if h == nil {
- return
- }
- if levelIndex[lv] < defaultLevel {
- return
- }
- msg := format
- if len(args) > 0 {
- msg = fmt.Sprintf(format, args...)
- }
- h.Log(lv, msg)
- }
- func logs(lv string, args ...interface{}) {
- if h == nil {
- return
- }
- if levelIndex[lv] < defaultLevel {
- return
- }
- h.Log(lv, fmt.Sprint(args...))
- }
- func Close() (err error) {
- if h == nil {
- return
- }
- return h.Close()
- }
|