如何在Go中设置和访问“全局”记录器?

时间:2019-02-17 23:33:02

标签: go logging

我确信我缺少一些简单的基本问题,我还很新。 假设我不想使用默认记录器,如何设置记录器以便可以在功能之间共享?

logissue.go

package main

import (
  "fmt"
  "github.com/pkg/errors"
  "log"
  "os"
)

var dlog log.Logger

const logfile string = "killer.log"
const logprefix string = "LOGTEST: "

func setupLogger(filename, prefix string) (*log.Logger, error) {
  out, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  if err != nil {
    return nil, errors.Wrap(err, "can't open logfile for writing")
  }
  return log.New(out, prefix, log.LstdFlags), nil
}

func uselog() error {
  fmt.Printf("%T\n", dlog)
  dlog.Printf("Hello")            ///// < Here is the issue
  return nil
}

func main() {
  dlog, err := setupLogger(logfile, logprefix)
  if err != nil {
    fmt.Printf("%+v", err)
  }
  dlog.Printf("test from main")
  uselog()
}

stdout

log.Logger
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x10970b8]

goroutine 1 [running]:
log.(*Logger).Output(0x116dd00, 0x2, 0xc000016106, 0x5, 0x0, 0x0)
    /usr/local/go/src/log/log.go:172 +0x1e8
log.(*Logger).Printf(0x116dd00, 0x10c9202, 0x5, 0x0, 0x0, 0x0)
    /usr/local/go/src/log/log.go:179 +0x7e
main.uselog(0xc000088050, 0x10ca43b)
    /Users/sequoia/learning/Ex_Files_Go_EssT/Exercise Files/logissue.go:25 +0xc4
main.main()
    /Users/sequoia/learning/Ex_Files_Go_EssT/Exercise Files/logissue.go:35 +0xee
exit status 2

killer.log

LOGTEST: 2019/02/17 18:25:12 test from main

2 个答案:

答案 0 :(得分:0)

我尝试过:


import (
    "fmt"
    "github.com/pkg/errors"
    "log"
    "os"
)

const logfile string = "killer.log"
const logprefix string = "LOGTEST: "

var DLog *log.Logger
func setupLogger(filename, prefix string) {
    var err error
    out, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal( nil, errors.Wrap(err, "can't open logfile for writing"))
    }
    DLog=log.New(out, prefix, log.LstdFlags)

    fmt.Println("Log object: ",DLog)

}

func uselog() error {
    DLog.Print("Hello") ///// < Here is the issue
    DLog.Print("I have something standard to say")

    fmt.Println("I am done")
    return nil
}

func main() {
    setupLogger(logfile, logprefix)
    DLog.Printf("test from main")
    uselog()
}

答案 1 :(得分:0)

因此,首先,根据您上面的代码,您尝试将非指针记录器设置为无法正常工作的指针记录器。其次,在设置dlog时会使用:=,它会在您的main方法中创建范围变量,而不是设置全局变量