你可以通过以下方式从其他文件中访问日志实例:

huangapple go评论91阅读模式
英文:

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.
)

huangapple
  • 本文由 发表于 2015年8月20日 17:55:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/32115109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定