转到日志未出现

时间:2019-04-07 19:28:05

标签: go logging

我想在golang中为日志记录系统创建依赖项注入, 但是当我执行<Context ...> <Environment name="JENKINS_HOME" value="/opt/jenikins" type="java.lang.String"/> </Context>时,它不会在日志文件中显示任何内容。 这是我的代码:

app.go

log.Info.Println

init.go

package main

import (
    log "github.com/jass-trix/BVDI/backend/application/logging"
)

func main() {
    logger := log.InitLog()
    logger.Info.Println("test info")
    logger.Error.Println("test error")
}

当我在app.go中调用package logging import ( "flag" "io" "log" "os" ) const logPath = "log/path/" //Logger is a struct that contain all type of logger //logger will be separated into two level type Logger struct { Info *log.Logger Error *log.Logger } var infoLog *log.Logger var errorLog *log.Logger //InitLog is a function to instantiate logging func InitLog() *Logger { flag.Parse() fileInfo, err := os.OpenFile(logPath+"file.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660) if err != nil { log.Fatalf("error on opening file: %v", err) } defer fileInfo.Close() multiInfo := io.MultiWriter(fileInfo, os.Stdout) infoLog := log.New(multiInfo, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) fileError, err := os.OpenFile(logPath+"file.error.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660) if err != nil { log.Fatalf("error on opening file: %v", err) } defer fileError.Close() multiError := io.MultiWriter(fileError, os.Stdout) errorLog := log.New(multiError, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) return &Logger{ Info: infoLog, Error: errorLog, } } 时,它不会打印任何内容, 但是当我在init.go中调用logger.Info.Println()时,它将打印到文件中。

日志记录是否支持依赖注入?

1 个答案:

答案 0 :(得分:1)

InitLog中,您使用

  

defer fileInfo.Close()

InitLog调用后关闭了文件。然后logger.Info.Println("test info")尝试写入关闭的文件。

如果(确实)想要使用全局记录器,则不应在InitLog函数中关闭文件。