为了账号安全,请及时绑定邮箱和手机立即绑定

如何从其他文件访问我的日志实例

如何从其他文件访问我的日志实例

Go
沧海一幻觉 2021-11-01 16:09:33
我最近开始学习 Go,当我决定将我的代码放在 1 个以上的文件 (main.go) 中时,出现了一个问题。我经常需要的日志、缓存、配置、指标等常用的东西都没有在其他文件中可用,即使它们属于同一个“包主”。我想根据配置(viper 包)中的数据配置我的日志实例(logrus 包)一次。而这只是开始,我很快就会有一个数据库实例(?)、缓存实例等。解决我的问题的最佳方法是什么,最好的 Go 实践是什么?如何遵循 DRY 原则?如果我将我的初始日志设置放入“mylog”包中,然后将其导入每个包的每个文件中,那么会有多少个 mylog 实例?每个文件/包/?? 它有效率吗?Log 和 Config 也相互依赖。我需要记录配置错误,我需要配置来配置日志。user@host:~/dev/go/src/helloworld$ go build && ./helloworld  # helloworld./cache.go:10: undefined: Log./cache.go:17: undefined: Logmain.go:package mainimport (    "fmt"    "time"    "os"    "strconv"    "strings"    "github.com/julienschmidt/httprouter"    "crypto/hmac"    "crypto/sha256"    // "github.com/gin-gonic/gin"    "net"    "net/http"    Log "github.com/Sirupsen/logrus"    // "io/ioutil"    "encoding/json"    "encoding/hex"    "encoding/base64"    "golang.org/x/crypto/bcrypt"    "github.com/asaskevich/govalidator"    "gopkg.in/gomail.v2-unstable"    "github.com/spf13/viper")...缓存去:package mainimport  (    "github.com/bradfitz/gomemcache/memcache")var conn = memcache.New("10.1.11.1:11211")func Set(key string, value []byte, ttl int32) error {    Log.Info("Cache: Set: key: " + key)    err := conn.Set(&memcache.Item{Key: key, Value: value, Expiration: ttl})    // fmt.Println(err)    return err}
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信