【问题标题】:How can I access my log instance from other files如何从其他文件访问我的日志实例
【发布时间】:2015-11-13 21:51:04
【问题描述】:

我最近开始学习 Go,当我决定将我的代码放在多个文件 (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: Log

main.go:

package main

import (
    "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"
)
.
.
.

cache.go:

package main

import  (
    "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
}

【问题讨论】:

  • “在其他文件中不可用”是什么意思?你在用go run吗?
  • 我正在使用“go build”
  • 如何调用go build?你得到什么错误?将此添加到您的问题中。

标签: go dependencies


【解决方案1】:

您需要将您使用的包添加到使用该包的每个文件的导入部分。所以在你的cache.go,写

import  (
    "github.com/bradfitz/gomemcache/memcache"
    Log "github.com/Sirupsen/logrus"
    // List all packages mentioned in cache.go.
)

【讨论】:

  • 我明白了,但它是同一个 Log 实例吗?如果我在 main.go 中配置(即设置日志格式)登录,这些更改是否也适用于 cache.go 中的 Log.* 调用?
  • 是的,应该是一样的。
  • 哇,你说得对,在 main.go 中设置日志格式化程序确实会影响它在其他包中的行为。我没想到这会奏效。是否有任何文档或参考资料可以解释这种行为?
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2017-08-06
  • 2013-04-16
相关资源
最近更新 更多