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

我确信我遗漏了一些简单的基本问题,我是新手。假设我不想使用默认记录器,如何设置记录器以便它可以在函数之间共享?


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


繁星coding
浏览 106回答 2
2回答

慕尼黑的夜晚无繁华

因此,首先,根据您上面的代码,您尝试设置一个带有指针记录器的非指针记录器,但该指针记录器不起作用。其次,您在设置 dlog 时使用 := ,它在您的 main 方法中创建一个作用域变量,而不是设置您的全局变量

江户川乱折腾

我试过这个:import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/pkg/errors"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os")const logfile string = "killer.log"const logprefix string = "LOGTEST: "var DLog *log.Loggerfunc setupLogger(filename, prefix string) {&nbsp; &nbsp; var err error&nbsp; &nbsp; out, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal( nil, errors.Wrap(err, "can't open logfile for writing"))&nbsp; &nbsp; }&nbsp; &nbsp; DLog=log.New(out, prefix, log.LstdFlags)&nbsp; &nbsp; fmt.Println("Log object: ",DLog)}func uselog() error {&nbsp; &nbsp; DLog.Print("Hello") ///// < Here is the issue&nbsp; &nbsp; DLog.Print("I have something standard to say")&nbsp; &nbsp; fmt.Println("I am done")&nbsp; &nbsp; return nil}func main() {&nbsp; &nbsp; setupLogger(logfile, logprefix)&nbsp; &nbsp; DLog.Printf("test from main")&nbsp; &nbsp; uselog()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go