英文:
How can I access my log instance from other files
问题
我最近开始学习Go语言,当我决定将我的代码放在多个文件(main.go以外)时,出现了一个问题。常用的日志、缓存、配置、指标等等,我经常需要在其他文件中使用,即使它们属于同一个"package main"。我想要根据配置(viper包)的数据来配置我的日志实例(logrus包)。而且这只是个开始,我很快还会有一个数据库实例、缓存实例等等。
解决我的问题的最佳方式是什么?有什么最佳的Go语言实践方法?我如何遵循DRY原则?
如果我将初始的日志设置放入"mylog"包中,然后在每个包的每个文件中导入它,那么会有多少个mylog实例?每个文件/包都有一个吗?这样效率高吗?
另外,日志和配置是相互依赖的。我需要记录配置错误,而且我需要配置日志来记录。
英文:
I've recently started learning Go and when I decided to put my code in more than 1 file (main.go), a problem emerged. None of the commonly used stuff like log, cache, config, metrics, etc, that I often need are available in other files, even though it belongs to the same "package main". I want to configure my log instance (logrus package) once, based on data from config (viper package). And this is just the beginning, I will soon have a DB instance(?), Cache instance, etc.
What's the best way to solve my problem, what's the best Go practice? How can I follow DRY principle?
If I put my initial log setup into "mylog" package and then import it in each file of each package, how many mylog instances will there be? One for each file/package/? ? Is it efficient?
Also Log and Config depend on each other. I need to log config errors and I need the config to configure the log.
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
}
答案1
得分: 3
你需要将你使用的包添加到每个使用该包的文件的导入部分中。所以在你的cache.go
文件中,写入以下内容:
import (
"github.com/bradfitz/gomemcache/memcache"
Log "github.com/Sirupsen/logrus"
// 列出在cache.go中提到的所有包。
)
英文:
You need to add packages you use into the import section of every file that's using the package. So in your cache.go
, write
import (
"github.com/bradfitz/gomemcache/memcache"
Log "github.com/Sirupsen/logrus"
// List all packages mentioned in cache.go.
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论