GO-log日誌封裝

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go封裝日誌:


  • 支援歸檔輸出,一個小時壓縮歸檔一份
  • 最多保留三天的日誌
  • 支援記錄層級自訂
  • 如果沒有指定輸出檔案預設輸出到控制台。
  • 支援輸出檔案名行號,以及時間、日誌界別

如: info 10:08:40.826836 handler.go:81

package loggerimport (    "fmt"    "log"    "os"    "os/exec"    "strings"    "time")const (    PanicLevel int = iota    FatalLevel    ErrorLevel    WarnLevel    InfoLevel    DebugLevel)type LogFile struct {    level    int    logTime  int64    fileName string    fileFd   *os.File}var logFile LogFilefunc Config(logFolder string, level int) {    logFile.fileName = logFolder    logFile.level = level    log.SetOutput(logFile)    log.SetFlags(log.Lmicroseconds | log.Lshortfile)}func SetLevel(level int) {    logFile.level = level}func Debugf(format string, args ...interface{}) {    if logFile.level >= DebugLevel {        log.SetPrefix("debug ")        log.Output(2, fmt.Sprintf(format, args...))    }}func Infof(format string, args ...interface{}) {    if logFile.level >= InfoLevel {        log.SetPrefix("info ")        log.Output(2, fmt.Sprintf(format, args...))    }}func Warnf(format string, args ...interface{}) {    if logFile.level >= WarnLevel {        log.SetPrefix("warn ")        log.Output(2, fmt.Sprintf(format, args...))    }}func Errorf(format string, args ...interface{}) {    if logFile.level >= ErrorLevel {        log.SetPrefix("error ")        log.Output(2, fmt.Sprintf(format, args...))    }}func Fatalf(format string, args ...interface{}) {    if logFile.level >= FatalLevel {        log.SetPrefix("fatal ")        log.Output(2, fmt.Sprintf(format, args...))    }}func (me LogFile) Write(buf []byte) (n int, err error) {    if me.fileName == "" {        fmt.Printf("consol: %s", buf)        return len(buf), nil    }    if logFile.logTime+3600 < time.Now().Unix() {        logFile.createLogFile()        logFile.logTime = time.Now().Unix()    }    if logFile.fileFd == nil {        return len(buf), nil    }    return logFile.fileFd.Write(buf)}func (me *LogFile) createLogFile() {    logdir := "./"    if index := strings.LastIndex(me.fileName, "/"); index != -1 {        logdir = me.fileName[0:index] + "/"        os.MkdirAll(me.fileName[0:index], os.ModePerm)    }    now := time.Now()    filename := fmt.Sprintf("%s_%04d%02d%02d_%02d%02d", me.fileName, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute())    if err := os.Rename(me.fileName, filename); err == nil {        go func() {            tarCmd := exec.Command("tar", "-zcf", filename+".tar.gz", filename, "--remove-files")            tarCmd.Run()            rmCmd := exec.Command("/bin/sh", "-c", "find "+logdir+` -type f -mtime +2 -exec rm {} \;`)            rmCmd.Run()        }()    }    for index := 0; index < 10; index++ {        if fd, err := os.OpenFile(me.fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeExclusive); nil == err {            me.fileFd.Sync()            me.fileFd.Close()            me.fileFd = fd            break        }        me.fileFd = nil    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.