我想为警告,调试,错误和信息生成四个日志文件。我想控制在运行时应该打印哪个文件

时间:2017-02-10 07:47:05

标签: go

package Loggers

import (
    "io"
    "os"
    "log"
)

var logCloser io.Closer
func MyLogger() {
    logFile, err := os.OpenFile("C:/Git/goclassec/src/gclassec/Logs/log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
    if err != nil {
        panic(err)
    }
    logCloser = logFile
    log.SetOutput(logFile)
}
func CloseMyLogger() {
    logCloser.Close()
}

1 个答案:

答案 0 :(得分:1)

您可以使用ng-repeat创建不同的记录器并将其包装在MyLogger中

这是新格式

log.New

以下是一个示例实现

<强>代码

 New(out io.Writer, prefix string, flag int)

<强>用法

package loggers

import (
    "log"
    "os"
)

//MyLogger custom logger
type MyLogger struct {
    ErrorL *log.Logger
    InfoL  *log.Logger
    DebugL *log.Logger
}

//New returns logger
//TODO : deal with error
func New() *MyLogger {
    ml := new(MyLogger)
    if logFile, err := os.OpenFile("C:/Git/goclassec/src/gclassec/Logs/log_error.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666); err == nil {
        ml.ErrorL = log.New(logFile, "ERROR", log.LUTC)
    }
    if logFile, err := os.OpenFile("C:/Git/goclassec/src/gclassec/Logs/log_info.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666); err == nil {
        ml.InfoL = log.New(logFile, "INFO", log.LUTC)
    }
    if logFile, err := os.OpenFile("C:/Git/goclassec/src/gclassec/Logs/log_debug.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666); err == nil {
        ml.DebugL = log.New(logFile, "DEBUG", log.LUTC)
    }
    return ml
}

func (ml MyLogger) Error(data ...interface{}) {
    ml.ErrorL.Println(data...)
}

func (ml MyLogger) Info(data ...interface{}) {
    ml.InfoL.Println(data...)
}

func (ml MyLogger) Debug(data ...interface{}) {
    ml.DebugL.Println(data...)
}