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


package main

import (
    // "github.com/gin-gonic/gin"
    Log "github.com/Sirupsen/logrus"
    // "io/ioutil"


package main

import  (

var conn = memcache.New("")

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
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • 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  (
        Log "github.com/Sirupsen/logrus"
        // List all packages mentioned in cache.go.
    点赞 评论 复制链接分享