3
我有一个使用go-logging库(https://github.com/op/go-logging)的Golang应用程序。日志文件可以正确生成,但是当我停止并重新启动Go应用程序时,该日志文件会被新的日志文件覆盖。这不是一个错误,Golang会按照要求去做。但如果可能的话,我希望新的日志被添加到现有的日志文件中。在Golang中实现日志文件appender
首先,我main.go的摘录:
package main
import (
"utils"
"webapp"
"odbc"
"constants"
"github.com/op/go-logging"
)
var config = &Configuration{}
var log = logging.MustGetLogger("main")
func main() {
// Load the configuration file
utils.Load(constants.CONFIG_PATH, config)
utils.InitLog(config.LOG)
...
}
我appUtils.go其中utilitary函数定义:
package utils
import (
"github.com/op/go-logging"
"os"
"fmt"
)
func InitLog(config LOG) {
f, err := os.Create(config.LogFile)
backend := logging.NewLogBackend(f, "", 0)
format := logging.MustStringFormatter(config.FORMAT,)
backendFormatter := logging.NewBackendFormatter(backend, format)
// Only errors and more severe messages should be sent to backend1 logging.Level
logging.SetBackend(backendFormatter)
level, err := logging.LogLevel(config.LEVEL)
if err != nil {
logging.SetLevel(logging.ERROR, "")
} else{
logging.SetLevel(level, "")
}
}
type LOG struct {
FORMAT string
LEVEL string
LogFile string
}
如果需要的话我也把我的配置的内容。 json:
{
"LOG":{
"LEVEL": "DEBUG",
"FORMAT": "%{color}%{time:15:04:05.000} %{shortfunc} => %{level:.4s} %{id:03x}%{color:reset} %{message}",
"LogFile": "logfile.log"
}
}
是我想要的吗? 我已经认识到这个问题来源于此行:创建
f, err := os.Create(config.LogFile)
一个新的文件后(重新)启动该应用程序。 为了避免我想这:
var f *os.File
if _, err := os.Stat(config.LogFile); os.IsNotExist(err) {
f, err := os.Create(config.LogFile)
}
else {
f, err := os.OpenFile(config.LogFile, os.O_APPEND|os.O_WRONLY, 0600)
}
,但它很瞎扯淡,但它不工作。
如果它不可行,我应该修改我的config.json来生成名称中含有毫秒数的文件吗?
我强烈强烈建议您花点时间重新组织你的包和阅读[有效去(https://开头golang。组织/ DOC/effective_go.html)。 – OneOfOne