求大神帮忙看看问题,谢谢。
环境:windows 10,64位;go version:1.10
两个问题:
1、apiserver/main.go时,/logs下的init func初始化的变量没有生效,还是nil。
报错如下:
```go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x6f524d]
goroutine 1 [running]:
github.com/Sirupsen/logrus.(*Logger).newEntry(0x0, 0xc1e11f)
D:/golang/src/github.com/Sirupsen/logrus/logger.go:79 +0x2d
github.com/Sirupsen/logrus.(*Logger).WithField(0x0, 0xe3ee8c, 0x4, 0xcb9520, 0xeec440, 0x0)
D:/golang/src/github.com/Sirupsen/logrus/logger.go:94 +0x3f
```
2、windows下无法指定日志保存目录。
```go
Failed to fire hook: failed to acquite target io.Writer: failed to open file &{./logs/options.log.%Y%m%d%H%M [%!s(*strftime.timefmtw=&{./logs/options.log.200601021504})]}: open ./logs/options.log.201806020800: The system cannot find the path specified.
```
项目结构如下:
```go
|--services
|-- apiserver
...
-- main.go
|-- cluster
...
-- main.go
|-- conf
-- loadconf.go
|-- logs
-- loadlogrus.go
```
日志代码:
```go
import (
"github.com/Sirupsen/logrus"
"fmt"
"runtime"
"time"
"github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
)
var Log *logrus.Logger
func init() {
Log = NewLogger()
}
func NewLogger() *logrus.Logger {
fmt.Println("NewLogger")
var Logger *logrus.Logger
var logPath string
if runtime.GOOS == "windows" {
logPath = "options.log"
} else {
logPath = "/var/log/thingslink/options.log"
}
writer, err := rotatelogs.New(
logPath+".%Y%m%d%H%M",
rotatelogs.WithLinkName(logPath),
rotatelogs.WithMaxAge(7*24*time.Hour),
rotatelogs.WithRotationTime(24*time.Hour),
)
if err != nil {
logrus.Errorf("config local file system logger error. %+v", err)
}
Logger = logrus.New()
Logger.Hooks.Add(lfshook.NewHook(
lfshook.WriterMap{
logrus.DebugLevel: writer,
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
},
&logrus.JSONFormatter{},
))
return Logger
}
```
有疑问加站长微信联系(非本文作者)