美文网首页Go语言Golang程序员
iGO实现之路 —— Log

iGO实现之路 —— Log

作者: ChainZhang | 来源:发表于2018-01-28 23:27 被阅读96次

    本文为转载,原文:iGO实现之路 —— Log

    Golang

    介绍

    日志是软件用来记录运行时出错信息的文本文件。编程人员和维护人员等可以利用错误日志对系统进行调试和维护。
    经常线上系统出错的时候,我们都是通过日志的方式去找到问题所在的,因为,线上是无法调试的,所以,日志是非常重要的。

    那么本章就简单的介绍下简单日志的实现,其实go的官方log包已经很好了。我这里只是进行一些简单的封装,方便系统调用。

    源码

    igo-github源码地址

    ILog接口

    由于我们记录日志的方式可能是多样的,可能是文本,可能是数据库,或者其他等各种各样的形式,所以这里我们需要定义一个统一的接口:

    type ILog interface{
        debug(v ...interface{})
        debugf(format string, v ...interface{})
    
        info(v ...interface{})
        infof(format string, v ...interface{})
    
        warn(v ...interface{})
        warnf(format string, v ...interface{})
    
        error(v ...interface{})
        errorf(format string, v ...interface{})
    
        fatal(v ...interface{})
        fatalf(format string, v ...interface{})
    }
    

    从接口中,我们可以看到,我们定义了10个接口方法。功能也是非常简单,分别是实现debug,info,warn,error,fatal,等信息的日志记录函数。后面我们每实现是在日志的形式都是对这个接口的实现。

    然后再需要一个工厂方法,来实现log的实例化:

    func NewILog(adapter string, log_level int) (ILog, error){
        switch adapter{
        case "file":
            return newFileLog(log_level), nil
            default :
            return nil, errors.New("系统为定义该该类型日志")
        }
    }
    

    该函数有2个参数,adapter是日志的表现形式,从代码中可以看到,我们只实现了file类型的日志,再一个就是日志的等级,即定义了等级之后,低于这个等级的日志是不会被记录下来的,日志的等级定义为:debug < info < warn < error < fatal。为此,我还专门定义了个等级的枚举:

    package ilog
    
    const(
        Level_Debug = iota
        Level_Info
        Level_Warn
        Level_Error
        Level_Fatal
    )
    

    最后就是提供一些对外的调用的函数了。在此之前,需要对log进行一个初始化:

    var appLog ILog
    func init(){
        level, _ := conf.AppConfig.GetInt("log.level")
        adapter := conf.AppConfig.GetString("log.adapter")
        appLog, _ = NewILog(adapter, level)
    }
    

    这里面我们运用到了之前的配置模块,对于日志的配置信息如下:

    [log]
    level = 1
    adapter = file
    

    最后就是开放的函数了:

    func Debug(v ...interface{}){
        appLog.debug(v...)
    }
    
    func Debugf(format string, v ...interface{}){
        appLog.debugf(format, v...)
    }
    
    func Info(v ...interface{}){
        appLog.info(v...)
    }
    
    func Infof(format string, v ...interface{}){
        appLog.infof(format, v...)
    }
    
    func Warn(v ...interface{}){
        appLog.warn(v...)
    }
    
    func Warnf(format string, v ...interface{}){
        appLog.warnf(format, v...)
    }
    
    func Error(v ...interface{}){
        appLog.error(v...)
    }
    
    func Errorf(format string, v ...interface{}){
        appLog.errorf(format, v... )
    }
    
    func Fatal(v ...interface{}){
        appLog.fatal(v...)
    }
    
    func Fatalf(format string, v ...interface{}){
        appLog.fatalf(format, v...)
    }
    

    filelog的实现

    上面已经定义好日志的接口,以及对外开放的函数,接下来就是对不同日志形式的实现,这里先简单介绍文本形式的实现:

    package ilog
    
    import(
        "os"
        "sync"
        "strings"
    
        "time"
        "log"
        "path/filepath"
    )
    
    var(
        file_daliy = "daliy"
        file_single = "single"
        file_write_mutex *sync.Mutex
    )
    
    type FileLog struct{
        level int
    }
    
    func newFileLog(log_level int) (*FileLog){
        fileLog := new(FileLog)
        fileLog.level = log_level
        file_write_mutex = new(sync.Mutex)
        return fileLog
    }
    
    func (self *FileLog)getFileLogName()(string, error){
        filename := "log_" + time.Now().Format("2006-01-02") + ".log"
        path, err := filepath.Abs("storage/logs/" + filename)
        if err != nil{
            return "", err
        }
        path = strings.Replace(path, "\\", "/", -1)
        path = strings.Replace(path, "\\\\", "/", -1)
        return path, nil
    }
    
    func (self *FileLog)getWriter()(*os.File, error){
        filename, err := self.getFileLogName()
        if err != nil{
            return nil, err
        }
        writer, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND, 0666)
        if err != nil{
            return nil, err
        }
        return writer, nil
    }
    
    func (self *FileLog) debug(v ...interface{}){
        if self.level <= Level_Debug{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Debug]", log.LstdFlags)
                logger.Print(v...)
            }()
        }
    }
    
    func (self *FileLog) debugf(format string,v ...interface{}){
        if self.level <= Level_Debug{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Debug]", log.LstdFlags)
                logger.Printf(format, v...)
            }()
        }
    }
    
    func (self *FileLog) info(v ...interface{}){
        if self.level <= Level_Info{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Info]", log.LstdFlags)
                logger.Println(v...)
            }()
        }
    }
    
    func (self *FileLog) infof(format string,v ...interface{}){
        if self.level <= Level_Info{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Info]", log.LstdFlags)
                logger.Printf(format, v...)
            }()
        }
    }
    
    func (self *FileLog) error(v ...interface{}){
        if self.level <= Level_Error{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Error]", log.LstdFlags)
                logger.Println(v...)
            }()
        }
    }
    
    func (self *FileLog) errorf(format string,v ...interface{}){
        if self.level <= Level_Error{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Error]", log.LstdFlags)
                logger.Printf(format, v...)
            }()
        }
    }
    
    func (self *FileLog) warn(v ...interface{}){
        if self.level <= Level_Warn{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Warn]", log.LstdFlags)
                logger.Println(v...)
            }()
        }
    }
    
    func (self *FileLog) warnf(format string,v ...interface{}){
        if self.level <= Level_Warn{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Warn]", log.LstdFlags)
                logger.Printf(format, v...)
            }()
        }
    }
    
    func (self *FileLog) fatal(v ...interface{}){
        if self.level <= Level_Fatal{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Fatal]", log.LstdFlags)
                logger.Fatalln(v...)
            }()
        }
    }
    
    func (self *FileLog) fatalf(format string,v ...interface{}){
        if self.level <= Level_Fatal{
            go func(){
                file_write_mutex.Lock()
                defer file_write_mutex.Unlock()
                writer, err := self.getWriter()
                if err != nil{
                    return
                }
                defer writer.Close()
                logger := log.New(writer, "[Fatal]", log.LstdFlags)
                logger.Fatalf(format, v...)
            }()
        }
    }
    

    从代码中可以看到,我们的日志存放目录是写死的,所以在系统的运行目录下,必须要有storage/logs/目录,当然这个其实也是可以通过配置来实现。如果需要用配置的话,请自己修改代码。

    另外也可以看出日志是每天一个日志文件的,文件命名也是包含日期的。

    再一个就是我们写日志的方法为了防止主线程的阻塞,采用了go协程独自去写,也就是每调用一次写日志的方法,就是开启一个协程,如果并发量特别特别大的话,可能会出现大量的go协程等待的情况。而且还会出现大量的打开关闭文件的操作。这种情况怎么处理呢,后面有机会再处理吧。不过这里可以提供一个解决线索,那就是可以通过一个缓冲的chan信道,然后使用一个单独的协程来专门实现写文件的功能。至于要多大的缓冲,可以根据系统的需要,使用配置的方式来实现。

    测试

    package test
    
    import(
        "igo/ilog"
        "fmt"
    )
    
    func TestLog(){
        ilog.Debug("app log debug message")
        ilog.Info("app log info message")
        ilog.Warn("app log warn message")
        ilog.Error("app log error message")
        ilog.Fatal("app log fatal message")
    
        var str string
        fmt.Scan(&str)
    }
    
    测试结果

    转载请注明出处:
    iGO实现之路 —— Log

    iGO我的go语言库

    相关文章

      网友评论

        本文标题:iGO实现之路 —— Log

        本文链接:https://www.haomeiwen.com/subject/dmdtzxtx.html