我确信我遗漏了一些简单的基本问题,我是新手。假设我不想使用默认记录器,如何设置记录器以便它可以在函数之间共享?
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
慕尼黑的夜晚无繁华
江户川乱折腾
相关分类