golang log

package log                                                                                                                                                                                                 

import (
    "log"
    "os"
    "time"
)

var (
    debug_log  = "debug.log"
    log_format = "2006-01-02-15"
)

var fileHandle *os.File
var cs chan string

func init() {
    file_name := getFileName()
    fileHandle, _ = os.OpenFile(file_name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
    log.SetOutput(fileHandle)
    cs = make(chan string, 1024)
    go WriteChan(cs)

}

func getFileName() string {
    now := time.Now()
    date := now.Format(log_format)
    file_path := "/your/local/dir/"
    filename := file_path + debug_log + "." + date

    return filename
}

func WriteDebugLog(content string) {

    //check log file
    curFileName := getFileName()

    if _, err := os.Stat(curFileName); os.IsNotExist(err) {
        file_name := getFileName()
        fileHandle, _ = os.OpenFile(file_name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
        log.SetOutput(fileHandle)
    }   
    //WriteSingleLog(content)
    cs <- content
}

func WriteChan(cs chan string) {
    for {
        select {
        case con := <-cs:
            WriteSingleLog(con)
            //beego.Debug(len(cs))
        }
    }
}

func WriteSingleLog(content string) {
    log.Println(content)
}          

  

posted @ 2017-11-07 20:01  hao.ma  阅读(240)  评论(0编辑  收藏  举报