Archive

Posts Tagged ‘rotation’

一个简单的rolling filelog,written in go

August 29th, 2014 No comments

使用了go-logging但是发现它只有logging format部分,没有数据输出部分(直接使用os.File进行输出). 所以自己做了一个简单的rolling file log. 可以设置保留的log文件个数,每一个log文件的最大字节数,强制flush的时间间隔.
使用方法如下:

func main() {
    l := rolling_filelog.LogFile{BaseName: "./test.log",
                MaxSize: 5*1024*1024,
                FileCount: 10,
                FlushInterval: 2*time.Second,
                BufferSize: 10*1024,
                BufferCount: 3}
    err := l.Open()
    if err != nil {
        fmt.Printf("failed to open log file,%s: %s\n", l.BaseName, err)
        return
    }
    data := make([]byte,10)
    copy(data[:],"1234567890")

    for i := 0 ; i < 10000000; i ++ {
        n,err := l.Write(data)
        if err != nil {
            fmt.Printf("failed to write data to %s :%s\n", l.BaseName, err )
            return
        }
        if n <= 0 {
            fmt.Printf("failed to write data to %s : %s\n", l.BaseName, "0 bytes written")
            return
        }
    }
    l.Close()

当然了,这个是用作其他logging的backend的,例go-logging

 logFile := utils.LogFile{BaseName: "./test.log",
                MaxSize: 8*1024,
                FileCount: 3,
                FlushInterval: 2*time.Second,
                BufferSize: 1*1024,
                BufferCount: 3}
    if logFile == nil {
        fmt.Println("failed to open log file")
        return nil
    }

    logger := logging.MustGetLogger("")
    if logger == nil {
        logFile.Close()
        return nil
    }

    logging.SetFormatter(logging.MustStringFormatter(" %{level:.4s} %{message}"))
    logBackend := logging.NewLogBackend( logFile, "", stdlog.LstdFlags|stdlog.Lmicroseconds)
    logging.SetBackend(logBackend)
    logging.SetLevel(logging.INFO,"")

这样以来, 日志文件就会保持在FileCount指定的数量上滚动, 以防止日志文件的无限制增长而吃光存储空间.

Categories: programming Tags: , ,