啟動程式的上一級目錄如何初始化全域性變數?

lql發表於2018-06-02

求大神幫忙看看問題,謝謝。 環境:windows 10,64 位;go version:1.10

兩個問題: 1、apiserver/main.go 時,/logs 下的 init func 初始化的變數沒有生效,還是 nil。我想在/logs 下用 init 初始化 Log 這個變數,能讓/apiserver 和/conf 都可以用。 報錯如下:

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 下無法指定日誌儲存目錄。

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.

專案結構如下:

|--services
  |-- apiserver
     ...
    -- main.go
  |-- cluster
     ...
    -- main.go
  |-- conf
    -- loadconf.go
  |-- logs
    -- loadlogrus.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" // 這裡指定為"./logs/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
}
更多原創文章乾貨分享,請關注公眾號
  • 啟動程式的上一級目錄如何初始化全域性變數?
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章