dsf323233323332
dsf323233323332
2015-08-20 09:55

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

  • dependencies
已采纳

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条回答

  • douchui3933 douchui3933 6年前

    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.
    )
    
    点赞 评论 复制链接分享