logger

package logger

import (
    "io"
    "log"
    "os"
)

const (
    LTrace = iota
    LInfo
    LWarn
    LError
)

var (
    Trace *log.Logger
    Info  *log.Logger
    Warn  *log.Logger
    Error *log.Logger
)

func newLevel(file *os.File, level, curLevel int) *log.Logger {
    var flag int = (log.Ldate | log.Lmicroseconds | log.Llongfile)
    logNew := func(prefix string, l1, l2 int) *log.Logger {
        if l1 <= l2 {
            return log.New(io.MultiWriter(file, os.Stdout), prefix, flag)
        } else {
            return log.New(os.Stdout, prefix, flag)
        }
    }

    switch level {
    case LTrace:
        return logNew("[TRACE] ", curLevel, LTrace)
    case LInfo:
        return logNew("[INFO ] ", curLevel, LInfo)
    case LWarn:
        return logNew("[WARN ] ", curLevel, LWarn)
    case LError:
        return logNew("[ERROR] ", curLevel, LError)
    default:
        return logNew("[TRACE] ", curLevel, LTrace)
    }
}

func Init(path string, level int) error {
    file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        return err
    }
    Trace = newLevel(file, LTrace, level)
    Info = newLevel(file, LInfo, level)
    Warn = newLevel(file, LWarn, level)
    Error = newLevel(file, LError, level)
    return nil
}

使用:

package main

import (
    "fmt"
    "os"

    "./logger"
)

func init() {
    if err := logger.Init("test.log", logger.LInfo); err != nil {
        fmt.Println("init logger failed", err)
        os.Exit(1)
    }
}

func main() {
    logger.Trace.Println("trace message")
    logger.Info.Println("info message")
    logger.Warn.Println("warn message")
    logger.Error.Println("error message")
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

鄂ICP备17003086号. Copyright © 2016. All Rights Reserved.