zoukankan      html  css  js  c++  java
  • go log

    go自带log包

    /*
    golang log example
    E-Mail : Mike_Zhang@live.com
    */
    package main
    
    import (
        "log"
        "os"
    )
    
    func main() {
        logFile,err := os.Create("test1.log")
        defer logFile.Close()
        if err != nil {
            log.Fatalln("open file error!")
        }
        logger := log.New(logFile,"[Debug]",log.Ldate | log.Ltime | log.Lshortfile)
        logger.Println("test debug message")
        logger.SetPrefix("[Info]")
        logger.Println("test info message")
    
    }

    封装logger 一:

    package main
    
    import (
        "log"
        "os"
        "io/ioutil"
        "io"
    )
    
    var (
        Trace   *log.Logger // 记录所有日志
        Info    *log.Logger // 重要的信息
        Warning *log.Logger // 需要注意的信息
        Error   *log.Logger // 致命错误
    )
    
    func init() {
        file, err := os.OpenFile("file", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
        if err != nil {
            log.Fatalln("Failed to open error log file:", err)
        }
    
        Trace = log.New(ioutil.Discard, "TRACE: ", log.Ltime|log.Lshortfile)
        Info = log.New(os.Stdout, "Info: ", log.Ltime|log.Lshortfile)
        Warning = log.New(os.Stdout, "Warning: ", log.Ltime|log.Lshortfile)
        Error = log.New(io.MultiWriter(file, os.Stderr),  "Error", log.Ltime|log.Lshortfile)
    }
    
    func main() {
        Trace.Println("I have something standard to say")
        Info.Println("Special Information")
        Warning.Println("There is something you need to know about")
        Error.Println("Something has failed")
    }

    封装logger二:

    package main
    
    import (
        "bytes"
        "fmt"
        "log"
        "io"
        "io/ioutil"
        "os"
    )
    type Logger struct {
        // contains filtered or unexported fields
    }    
    var (
        Trace   *log.Logger
        Info    *log.Logger
        Warning *log.Logger
        Error   *log.Logger
    )
    
    func Init( traceHandle io.Writer, infoHandle io.Writer, 
        warningHandle io.Writer, errorHandle io.Writer)(Trace,Info,Warning,Error *log.Logger) {
        Trace = log.New(traceHandle,"TRACE: ", log.Ldate|log.Ltime|log.Lshortfile)
        Info = log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
        Warning = log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
        Error = log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
        // Trace.Println("XXXXXXXXXXXX")
        return //Trace,Info,Warning,Error
    }
    
    func test_log2(){
        Trace,Info,Warning,Error :=Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
        Trace.Println("I have something standard to say")
        Info.Println("Special Information")
        Warning.Println("There is something you need to know about")
        Error.Println("Something has failed")
    }
    
    func test_log1(){
        var buf bytes.Buffer
        logger := log.New(&buf, "logger: ", log.Lshortfile|log.Ldate)
        logger.Print("Hello, log file!")
        fmt.Print(&buf)
    }
    
    func main() {
        
        test_log1()
        test_log2()
        
    }

    go 切割日志文件

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "time"
    )
    
    const (
        BACKUP_COUNT = 5
        MAX_FILE_BYTES = 2 * 1024
    )
    
    func doRotate(fPrefix string) {
        for j := BACKUP_COUNT; j >= 1; j-- {
            curFileName := fmt.Sprintf("%s_%d.log",fPrefix,j)
            k := j-1
            preFileName := fmt.Sprintf("%s_%d.log",fPrefix,k)
    
            if k == 0 {
                preFileName = fmt.Sprintf("%s.log", fPrefix)
            }
            _,err := os.Stat(curFileName)
            if err == nil {
                os.Remove(curFileName)
                fmt.Println("remove : ", curFileName)
            }
            _,err = os.Stat(preFileName)
            if err  == nil {
                fmt.Println("rename : ", preFileName, " => ", curFileName)
                err = os.Rename(preFileName, curFileName)
                if err != nil {
                    fmt.Println(err)
                }
            }
        }
    }
    
    func NewLogger(fPrefix string) (*log.Logger, *os.File) {
        var logger *log.Logger
        fileName := fmt.Sprintf("%s.log", fPrefix)
        fmt.Println("fileName :", fileName)
        logFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    
        if err != nil {
            fmt.Println("open file error!")
        } else {
            logger = log.New(logFile, "[Debug]", log.Ldate|log.Ltime|log.Lshortfile)
        }
        return logger, logFile
    }
    
    func logWorker(msgQueue <-chan string) {
        fPrefix := "msg"
        logger, logFile := NewLogger(fPrefix)
        for msg := range msgQueue {
            logger.Println(msg)
            fi, err2 := logFile.Stat()
            if err2 == nil {
                if fi.Size() > MAX_FILE_BYTES {
                    logFile.Close()
                    doRotate(fPrefix)
                    logger,logFile = NewLogger(fPrefix)
                }
            }
        }
        logFile.Close()
    }
    
    func main() {
        msgQueue := make(chan string, 1000)
        go logWorker(msgQueue)
    
        for j := 1; j <= 1000; j++ {
            msgQueue <- fmt.Sprintf("msg_%d", j)
            time.Sleep(1 * time.Second)
        }
        close(msgQueue)
        return
    }
  • 相关阅读:
    将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数组
    vue 设计一个倒计时秒杀的组件
    es6之三个点(...)扩展运算符
    es6之解构赋值
    es6之字符串添加的东西
    ES6系列之变量声明let const
    js对数组进行删除
    python学习
    泛型
    随笔
  • 原文地址:https://www.cnblogs.com/tigerzhouv587/p/11498630.html
Copyright © 2011-2022 走看看