diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 02bed8ee0..838e33c41 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,3 +1,6 @@ +### 2.5.0 +* Migrate to static logging tool + ### 2.4.1 * Service restart command was with typo diff --git a/VERSION b/VERSION index 005119baa..437459cd9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.4.1 +2.5.0 diff --git a/conf/conf.go b/conf/conf.go index f5f56967c..50690bcda 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -5,7 +5,6 @@ import ( "github.com/mageddo/dns-proxy-server/flags" "os" "github.com/mageddo/dns-proxy-server/utils/env" - "github.com/mageddo/go-logging" "strings" ) @@ -47,7 +46,7 @@ func GetResolvConf() string { } func getConf() (*local.LocalConfiguration, error) { - return local.LoadConfiguration(logging.NewContext()) + return local.LoadConfiguration() } func LogLevel() string { diff --git a/conf/conf_test.go b/conf/conf_test.go index 2a986949b..1d83e8f28 100644 --- a/conf/conf_test.go +++ b/conf/conf_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/mageddo/dns-proxy-server/flags" "github.com/mageddo/dns-proxy-server/events/local" - "github.com/mageddo/go-logging" "github.com/mageddo/dns-proxy-server/utils" "flag" "github.com/mageddo/dns-proxy-server/utils/env" @@ -29,8 +28,7 @@ func TestFlagValuesFromArgs(t *testing.T) { func TestFlagValuesFromConf(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "webServerPort": 8080, "dnsServerPort": 62, "defaultDns": false }`, utils.GetPath(*flags.ConfPath)) assert.Nil(t, err) @@ -48,11 +46,10 @@ func TestLogLevel_DefaultValue(t *testing.T) { func TestLogLevel_ReadFromConfig(t *testing.T) { // arrange - ctx := logging.NewContext() - c, err := local.LoadConfiguration(ctx) + c, err := local.LoadConfiguration() assert.Nil(t, err) c.LogLevel = "INFO" - local.SaveConfiguration(ctx, c) + local.SaveConfiguration(c) // act level := LogLevel() @@ -90,11 +87,10 @@ func TestLogFile_DefaultValue(t *testing.T) { func TestLogFile_ReadFromConfig(t *testing.T) { // arrange - ctx := logging.NewContext() - c, err := local.LoadConfiguration(ctx) + c, err := local.LoadConfiguration() assert.Nil(t, err) c.LogFile = "false" - local.SaveConfiguration(ctx, c) + local.SaveConfiguration(c) // act level := LogFile() diff --git a/controller/cache.go b/controller/cache.go index 0fcc2cb43..9a9d2b21a 100644 --- a/controller/cache.go +++ b/controller/cache.go @@ -6,6 +6,7 @@ import ( "github.com/mageddo/dns-proxy-server/utils" "github.com/mageddo/dns-proxy-server/cache/store" "github.com/mageddo/go-logging" + . "github.com/mageddo/go-httpmap" ) const ( CACHE_V1 = "/v1/caches" @@ -13,11 +14,10 @@ const ( ) func init() { - Get(CACHE_V1, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string) { + Get(CACHE_V1, func(ctx context.Context, res http.ResponseWriter, req *http.Request) { - logger := logging.NewLog(ctx) c, encoder := store.GetInstance(), utils.GetJsonEncoder(res) - logger.Debugf("m=%s, size=%d", CACHE_V1, c.Size()) + logging.Debugf("m=%s, size=%d", CACHE_V1, c.Size()) res.Header().Add("Content-Type", "application/json") cacheObject := make(map[string]interface{}) @@ -26,20 +26,19 @@ func init() { } if err := encoder.Encode(cacheObject); err != nil { - logger.Errorf("m=%s, err=%v", CACHE_V1, err) + logging.Errorf("m=%s, err=%v", CACHE_V1, err) RespMessage(res, http.StatusServiceUnavailable, "Could not get caches, please try again later") } }) - Get(CACHE_SIZE_V1, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string) { + Get(CACHE_SIZE_V1, func(ctx context.Context, res http.ResponseWriter, req *http.Request) { - logger := logging.NewLog(ctx) c, encoder := store.GetInstance(), utils.GetJsonEncoder(res) - logger.Debugf("m=%s, size=%d", CACHE_SIZE_V1, c.Size()) + logging.Debugf("m=%s, size=%d", CACHE_SIZE_V1, c.Size()) res.Header().Add("Content-Type", "application/json") if err := encoder.Encode(map[string]interface{}{"size": c.Size()}); err != nil { - logger.Errorf("m=%s, err=%v", CACHE_SIZE_V1, err) + logging.Errorf("m=%s, err=%v", CACHE_SIZE_V1, err) RespMessage(res, http.StatusServiceUnavailable, "Temporary unavailable, please try again later") } }) diff --git a/controller/env.go b/controller/env.go index 12294a26e..c6eeada83 100644 --- a/controller/env.go +++ b/controller/env.go @@ -1,12 +1,13 @@ package controller import ( - log "github.com/mageddo/go-logging" "net/http" "github.com/mageddo/dns-proxy-server/events/local" "encoding/json" "context" "github.com/mageddo/dns-proxy-server/utils" + . "github.com/mageddo/go-httpmap" + "github.com/mageddo/go-logging" ) const ( @@ -18,80 +19,77 @@ const ( func init(){ - Get(ENV_ACTIVE, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get(ENV_ACTIVE, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + if conf, _ := local.LoadConfiguration(); conf != nil { utils.GetJsonEncoder(res).Encode(local.EnvVo{Name: conf.ActiveEnv}) return } confLoadError(res) }) - Put(ENV_ACTIVE, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Put(ENV_ACTIVE, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ - logger := log.NewLog(ctx) - logger.Infof("m=/env/active/, status=begin") + logging.Infof("m=/env/active/, status=begin") res.Header().Add("Content-Type", "application/json") var envVo local.EnvVo json.NewDecoder(req.Body).Decode(&envVo) - logger.Infof("m=/env/active/, status=parsed-host, env=%+v", envVo) + logging.Infof("m=/env/active/, status=parsed-host, env=%+v", envVo) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { - if err := conf.SetActiveEnv(ctx, envVo); err != nil { - logger.Infof("m=/env/, status=error, action=create-env, err=%+v", err) + if conf, _ := local.LoadConfiguration(); conf != nil { + if err := conf.SetActiveEnv(envVo); err != nil { + logging.Infof("m=/env/, status=error, action=create-env, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/env/active/, status=success, action=active-env") + logging.Infof("m=/env/active/, status=success, action=active-env") return } confLoadError(res) }) - Get(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + if conf, _ := local.LoadConfiguration(); conf != nil { utils.GetJsonEncoder(res).Encode(conf.Envs) return } confLoadError(res) }) - Post(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ - logger := log.NewLog(ctx) + Post(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - logger.Infof("m=/env/, status=begin, action=create-env") + logging.Infof("m=/env/, status=begin, action=create-env") var envVo local.EnvVo json.NewDecoder(req.Body).Decode(&envVo) - logger.Infof("m=/env/, status=parsed-host, env=%+v", envVo) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + logging.Infof("m=/env/, status=parsed-host, env=%+v", envVo) + if conf, _ := local.LoadConfiguration(); conf != nil { if err := conf.AddEnv(ctx, envVo); err != nil { - logger.Infof("m=/env/, status=error, action=create-env, err=%+v", err) + logging.Infof("m=/env/, status=error, action=create-env, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/env/, status=success, action=create-env") + logging.Infof("m=/env/, status=success, action=create-env") return } confLoadError(res) }) - Delete(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ - logger := log.NewLog(ctx) + Delete(ENV, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - logger.Infof("m=/env/, status=begin, action=delete-env") + logging.Infof("m=/env/, status=begin, action=delete-env") var env local.EnvVo json.NewDecoder(req.Body).Decode(&env) - logger.Infof("m=/env/, status=parsed-host, action=delete-env, env=%+v", env) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { - if err := conf.RemoveEnvByName(ctx, env.Name); err != nil { - logger.Infof("m=/env/, status=error, action=delete-env, err=%+v", err) + logging.Infof("m=/env/, status=parsed-host, action=delete-env, env=%+v", env) + if conf, _ := local.LoadConfiguration(); conf != nil { + if err := conf.RemoveEnvByName(env.Name); err != nil { + logging.Infof("m=/env/, status=error, action=delete-env, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/env/, status=success, action=delete-env") + logging.Infof("m=/env/, status=success, action=delete-env") return } confLoadError(res) diff --git a/controller/env_test.go b/controller/env_test.go index 0770ad1e8..db04d792b 100644 --- a/controller/env_test.go +++ b/controller/env_test.go @@ -8,7 +8,6 @@ import ( "github.com/mageddo/dns-proxy-server/events/local" "github.com/mageddo/dns-proxy-server/utils" "github.com/mageddo/dns-proxy-server/flags" - "github.com/mageddo/go-logging" ) func TestGetActiveEnvSuccess(t *testing.T) { @@ -42,8 +41,7 @@ func TestPutChangeActiveEnvSuccess(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [{ "name": "testEnv" }] @@ -72,12 +70,8 @@ func TestPutChangeActiveEnvSuccess(t *testing.T) { func TestGetEnvsSuccess(t *testing.T) { defer local.ResetConf() - - ctx := logging.NewContext() - local.LoadConfiguration(ctx) - + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [{ "name": "SecondEnv" }]}`, utils.GetPath(*flags.ConfPath)) - assert.Nil(t, err) s := httptest.NewServer(nil) @@ -120,9 +114,7 @@ func TestPostEnvSuccess(t *testing.T) { func TestDeleteEnvSuccess(t *testing.T) { defer local.ResetConf() - - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [{ "name": "SecondEnv" }]}`, utils.GetPath(*flags.ConfPath)) diff --git a/controller/hostname.go b/controller/hostname.go index d5396ee7a..958aeb453 100644 --- a/controller/hostname.go +++ b/controller/hostname.go @@ -5,8 +5,9 @@ import ( "encoding/json" "github.com/mageddo/dns-proxy-server/events/local" "golang.org/x/net/context" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "fmt" + . "github.com/mageddo/go-httpmap" ) const ( @@ -16,9 +17,9 @@ const ( func init(){ - Get(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + if conf, _ := local.LoadConfiguration(); conf != nil { envName := req.URL.Query().Get("env") if env, _ := conf.GetEnv(envName); env != nil { json.NewEncoder(res).Encode(env) @@ -30,9 +31,9 @@ func init(){ confLoadError(res) }) - Get(HOSTNAME_FIND, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get(HOSTNAME_FIND, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + if conf, _ := local.LoadConfiguration(); conf != nil { env := req.URL.Query().Get("env") hostname := req.URL.Query().Get("hostname") var err error @@ -47,64 +48,61 @@ func init(){ confLoadError(res) }) - Post(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ - logger := log.NewLog(ctx) + Post(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - logger.Infof("m=/hostname/, status=begin, action=create-hostname") + logging.Infof("m=/hostname/, status=begin, action=create-hostname") var hostname local.HostnameVo if err := json.NewDecoder(req.Body).Decode(&hostname); err != nil { BadRequest(res, "Invalid JSON") return } - logger.Infof("m=/hostname/, status=parsed-host, host=%+v", hostname) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { - if err := conf.AddHostname(ctx, hostname.Env, hostname); err != nil { - logger.Infof("m=/hostname/, status=error, action=create-hostname, err=%+v", err) + logging.Infof("m=/hostname/, status=parsed-host, host=%+v", hostname) + if conf, _ := local.LoadConfiguration(); conf != nil { + if err := conf.AddHostname(hostname.Env, hostname); err != nil { + logging.Infof("m=/hostname/, status=error, action=create-hostname, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/hostname/, status=success, action=create-hostname") + logging.Infof("m=/hostname/, status=success, action=create-hostname") return } confLoadError(res) }) - Put(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ - logger := log.NewLog(ctx) + Put(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - logger.Infof("m=/hostname/, status=begin, action=update-hostname") + logging.Infof("m=/hostname/, status=begin, action=update-hostname") var hostname local.HostnameVo if err := json.NewDecoder(req.Body).Decode(&hostname); err != nil { BadRequest(res, "Invalid JSON") return } - logger.Infof("m=/hostname/, status=parsed-host, host=%+v", hostname) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { - if err := conf.UpdateHostname(ctx, hostname.Env, hostname); err != nil { - logger.Infof("m=/hostname/, status=error, action=update-hostname, err=%+v", err) + logging.Infof("m=/hostname/, status=parsed-host, host=%+v", hostname) + if conf, _ := local.LoadConfiguration(); conf != nil { + if err := conf.UpdateHostname(hostname.Env, hostname); err != nil { + logging.Infof("m=/hostname/, status=error, action=update-hostname, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/hostname/, status=success, action=update-hostname") + logging.Infof("m=/hostname/, status=success, action=update-hostname") return } confLoadError(res) }) - Delete(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ - logger := log.NewLog(ctx) + Delete(HOSTNAME, func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - logger.Infof("m=/hostname/, status=begin, action=delete-hostname") + logging.Infof("m=/hostname/, status=begin, action=delete-hostname") var hostname local.HostnameVo json.NewDecoder(req.Body).Decode(&hostname) - logger.Infof("m=/hostname/, status=parsed-host, action=delete-hostname, host=%+v", hostname) - if conf, _ := local.LoadConfiguration(ctx); conf != nil { - if err := conf.RemoveHostnameByEnvAndHostname(ctx, hostname.Env, hostname.Hostname); err != nil { - logger.Infof("m=/hostname/, status=error, action=delete-hostname, err=%+v", err) + logging.Infof("m=/hostname/, status=parsed-host, action=delete-hostname, host=%+v", hostname) + if conf, _ := local.LoadConfiguration(); conf != nil { + if err := conf.RemoveHostnameByEnvAndHostname(hostname.Env, hostname.Hostname); err != nil { + logging.Infof("m=/hostname/, status=error, action=delete-hostname, err=%+v", err) BadRequest(res, err.Error()) return } - logger.Infof("m=/hostname/, status=success, action=delete-hostname") + logging.Infof("m=/hostname/, status=success, action=delete-hostname") return } confLoadError(res) diff --git a/controller/hostname_test.go b/controller/hostname_test.go index 30889182b..2f93a88ea 100644 --- a/controller/hostname_test.go +++ b/controller/hostname_test.go @@ -8,16 +8,13 @@ import ( "net/http" "github.com/mageddo/dns-proxy-server/events/local" "github.com/mageddo/dns-proxy-server/flags" - "github.com/mageddo/go-logging" "github.com/mageddo/dns-proxy-server/utils" ) func TestGetHostnamesByEnv(t *testing.T) { defer local.ResetConf() - - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [ { "name": "MyEnv", "hostnames": [{"hostname": "github.io", "ip": [1,2,3,4], "ttl": 55}] } @@ -39,9 +36,7 @@ func TestGetHostnamesByEnv(t *testing.T) { func TestGetHostnamesByEnvAndHostname(t *testing.T) { defer local.ResetConf() - - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [ { "name": "MyEnv", "hostnames": [{"hostname": "github.io", "ip": [1,2,3,4], "ttl": 55}] } @@ -65,8 +60,7 @@ func TestPostHostname(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [{ "name": "MyOtherEnv" }]}`, utils.GetPath(*flags.ConfPath)) @@ -110,10 +104,7 @@ func TestPostHostnameInvalidPayloadError(t *testing.T) { func TestPutHostname(t *testing.T) { defer local.ResetConf() - - ctx := logging.NewContext() - local.LoadConfiguration(ctx) - + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [ { "name": "MyEnv", "hostnames": [{"id": 999, "hostname": "github.io", "ip": [1,2,3,4], "ttl": 55}] } ]}`, utils.GetPath(*flags.ConfPath)) @@ -145,8 +136,7 @@ func TestDeleteHostname(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - local.LoadConfiguration(ctx) + local.LoadConfiguration() err := utils.WriteToFile(`{ "remoteDnsServers": [], "envs": [ { "name": "MyEnv", "hostnames": [{"hostname": "github.io", "ip": [1,2,3,4], "ttl": 55}] } diff --git a/controller/index.go b/controller/index.go index c8034f49e..125dd10cd 100644 --- a/controller/index.go +++ b/controller/index.go @@ -5,17 +5,18 @@ import ( "golang.org/x/net/context" "github.com/mageddo/dns-proxy-server/utils" "github.com/mageddo/dns-proxy-server/events/local" + . "github.com/mageddo/go-httpmap" ) func init(){ - Get("/", func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get("/", func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Location", "/static") res.WriteHeader(301) }) - Get("/configuration/", func(ctx context.Context, res http.ResponseWriter, req *http.Request, url string){ + Get("/configuration/", func(ctx context.Context, res http.ResponseWriter, req *http.Request){ res.Header().Add("Content-Type", "application/json") - if conf, _ := local.LoadConfiguration(ctx); conf != nil { + if conf, _ := local.LoadConfiguration(); conf != nil { utils.GetJsonEncoder(res).Encode(conf) return } diff --git a/controller/main.go b/controller/main.go deleted file mode 100644 index dc20cbe00..000000000 --- a/controller/main.go +++ /dev/null @@ -1,91 +0,0 @@ -package controller - -import ( - . "github.com/mageddo/dns-proxy-server/log" - "net/http" - "golang.org/x/net/context" - log "github.com/mageddo/go-logging" - "encoding/json" -) - - -type Method string -const ( -POST Method = "POST" -GET Method = "GET" -PUT Method = "PUT" -PATCH Method = "PATCH" -DELETE Method = "DELETE" -) - -type Map struct { - method Method - path string -} - -type Message struct { - Code int `json:"code"` - Message string `json:"message"` -} - -func BadRequest(w http.ResponseWriter, msg string){ - LOGGER.Errorf("json=invalid, msg=%s", msg) - RespMessage(w, 400, msg) -} - -func RespMessage(w http.ResponseWriter, code int, msg string){ - w.WriteHeader(code) - json.NewEncoder(w).Encode(Message{Code:code, Message:msg}) -} - -var maps = make(map[string]map[string]func(context.Context, http.ResponseWriter, *http.Request, string)) - -func MapRequests() { - // this is a placebo to execute inits from this package -} - -func Post(path string, fn func(context.Context, http.ResponseWriter, *http.Request, string)) { - MapReq(POST, path, fn) -} - -func Get(path string, fn func(context.Context, http.ResponseWriter, *http.Request, string)) { - MapReq(GET, path, fn) -} - -func Put(path string, fn func(context.Context, http.ResponseWriter, *http.Request, string)) { - MapReq(PUT, path, fn) -} - -func Delete(path string, fn func(context.Context, http.ResponseWriter, *http.Request, string)) { - MapReq(DELETE, path, fn) -} - -func MapReq(method Method, path string, fn func(context.Context, http.ResponseWriter, *http.Request, string)) { - - _, mapped := maps[path] - if !mapped { - - maps[path] = make(map[string]func(context.Context, http.ResponseWriter, *http.Request, string)) - - http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { - urlPath := r.URL.Path - _, matched := maps[urlPath][r.Method] - ctx := log.NewContext() - logger := log.NewLog(ctx) - - logger.Debugf("status=begin, matched=%t, url=%s, method=%s", matched, urlPath, r.Method) - if matched { - function := maps[urlPath][r.Method] - function(ctx, w, r, urlPath) - logger.Debugf("status=success, url=%s %s", r.Method, urlPath) - }else{ - logger.Debugf("status=not-found, url=%s %s", r.Method, urlPath) - http.NotFound(w, r) - } - - }) - } - LOGGER.Debugf("status=mapping, url=%s %s", method, path) - maps[path][string(method)] = fn - -} diff --git a/controller/statics.go b/controller/statics.go index be8995efa..3219a77b7 100644 --- a/controller/statics.go +++ b/controller/statics.go @@ -3,16 +3,14 @@ package controller import ( "net/http" "github.com/mageddo/dns-proxy-server/utils" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" ) func init(){ http.HandleFunc("/static/", func(res http.ResponseWriter, req *http.Request){ - logger := log.NewLog(log.NewContext()) - staticPath := utils.GetPath("/") - logger.Infof("urlPath=%s", req.URL.Path) + logging.Infof("urlPath=%s", req.URL.Path) hd := http.FileServer(http.Dir(staticPath)) hd.ServeHTTP(res, req) }) diff --git a/dns.go b/dns.go index ce170a3f8..5424626f0 100644 --- a/dns.go +++ b/dns.go @@ -1,6 +1,7 @@ package main import ( + _ "github.com/mageddo/dns-proxy-server/controller" "github.com/mageddo/dns-proxy-server/log" "fmt" "os" @@ -13,7 +14,6 @@ import ( "github.com/mageddo/dns-proxy-server/events/local" "github.com/mageddo/dns-proxy-server/events/docker" "net/http" - "github.com/mageddo/dns-proxy-server/controller" "github.com/mageddo/dns-proxy-server/conf" "github.com/mageddo/dns-proxy-server/utils/exitcodes" "github.com/mageddo/dns-proxy-server/service" @@ -21,22 +21,20 @@ import ( "runtime/debug" "github.com/mageddo/dns-proxy-server/cache/store" "github.com/mageddo/dns-proxy-server/resolvconf" + "context" ) func init(){ - log.SetLevel(conf.LogLevel()) + // TODO unavailable log.SetLevel(conf.LogLevel()) log.SetOutput(conf.LogFile()) } func handleQuestion(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { - ctx := logging.NewContext() - logger := logging.NewLog(ctx) - defer func() { err := recover() if err != nil { - logger.Errorf("status=error, error=%v, stack=%s", err, string(debug.Stack())) + logging.Errorf("status=error, error=%v, stack=%s", err, string(debug.Stack())) } }() @@ -45,11 +43,11 @@ func handleQuestion(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { if questionsQtd != 0 { firstQuestion = reqMsg.Question[0] }else{ - logger.Error("status=question-is-nil") + logging.Error("status=question-is-nil") return } - logger.Debugf("status=begin, reqId=%d, questions=%d, question=%s, type=%s", reqMsg.Id, + logging.Debugf("status=begin, reqId=%d, questions=%d, question=%s, type=%s", reqMsg.Id, questionsQtd, firstQuestion.Name, utils.DnsQTypeCodeToName(firstQuestion.Qtype)) // loading the solvers and try to solve the hostname in that order @@ -60,19 +58,19 @@ func handleQuestion(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { for _, solver := range solvers { solverID := reflect.TypeOf(solver).String() - logger.Debugf("status=begin, solver=%s", solverID) + logging.Debugf("status=begin, solver=%s", solverID) // loop through questions - resp, err := solver.Solve(ctx, firstQuestion) + resp, err := solver.Solve(context.Background(), firstQuestion) if err == nil { var firstAnswer dns.RR answerLenth := len(resp.Answer) - logger.Debugf("status=answer-found, solver=%s, length=%d", solverID, answerLenth) + logging.Debugf("status=answer-found, solver=%s, length=%d", solverID, answerLenth) if answerLenth != 0 { firstAnswer = resp.Answer[0] } - logger.Debugf("status=resolved, solver=%s, alength=%d, answer=%v", solverID, answerLenth, firstAnswer) + logging.Debugf("status=resolved, solver=%s, alength=%d, answer=%v", solverID, answerLenth, firstAnswer) resp.SetReply(reqMsg) resp.Compress = conf.Compress() @@ -80,15 +78,15 @@ func handleQuestion(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { break } - logger.Debugf("status=not-resolved, solver=%s, err=%v", solverID, err) + logging.Debugf("status=not-resolved, solver=%s, err=%v", solverID, err) } } -func serve(net, name, secret string, logger logging.Log) { +func serve(net, name, secret string) { port := fmt.Sprintf(":%d", conf.DnsServerPort()) - logger.Debugf("status=begin, port=%d", conf.DnsServerPort()) + logging.Debugf("status=begin, port=%d", conf.DnsServerPort()) switch name { case "": server := &dns.Server{Addr: port, Net: net, TsigSecret: nil} @@ -107,10 +105,7 @@ func serve(net, name, secret string, logger logging.Log) { func main() { - ctx := logging.NewContext() - logger := logging.NewLog(ctx) - - service.NewService(ctx).Install() + service.NewService().Install() var name, secret string if conf.Tsig() != "" { @@ -120,7 +115,8 @@ func main() { if conf.CpuProfile() != "" { f, err := os.Create(conf.CpuProfile()) if err != nil { - logger.Fatal(err) + logging.Error(err) + os.Exit(-3) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() @@ -128,38 +124,37 @@ func main() { dns.HandleFunc(".", handleQuestion) - local.LoadConfiguration(ctx) + local.LoadConfiguration() go docker.HandleDockerEvents() - go serve("tcp", name, secret, logger) - go serve("udp", name, secret, logger) + go serve("tcp", name, secret) + go serve("udp", name, secret) go func(){ webPort := conf.WebServerPort() - logger.Infof("status=web-server-starting, port=%d", webPort) + logging.Infof("status=web-server-starting, port=%d", webPort) if err := http.ListenAndServe(fmt.Sprintf(":%d", webPort), nil); err != nil { - logger.Errorf("status=failed-start-web-server, err=%v, port=%d", err, webPort) + logging.Errorf("status=failed-start-web-server, err=%v, port=%d", err, webPort) exitcodes.Exit(exitcodes.FAIL_START_WEB_SERVER) }else{ - logger.Infof("status=web-server-started, port=%d", webPort) + logging.Infof("status=web-server-started, port=%d", webPort) } }() go func() { - logger.Infof("status=setup-requests") - controller.MapRequests() + logging.Infof("status=setup-requests") if conf.SetupResolvConf() { - logger.Infof("status=setResolvconf") + logging.Infof("status=setResolvconf") err := resolvconf.SetCurrentDNSServerToMachine() if err != nil { - logger.Errorf("status=setResolvconf, err=%v", err) + logging.Errorf("status=setResolvconf, err=%v", err) exitcodes.Exit(exitcodes.FAIL_SET_DNS_AS_DEFAULT) } } }() - logger.Infof("status=listing-signals") + logging.Infof("status=listing-signals") fmt.Printf("server started\n") s := <- utils.Sig - logger.Infof("status=exiting..., s=%s", s) + logging.Infof("status=exiting..., s=%s", s) resolvconf.RestoreResolvconfToDefault() - logger.Warningf("status=exiting, signal=%v", s) + logging.Warningf("status=exiting, signal=%v", s) } diff --git a/docker-compose.yml b/docker-compose.yml index d9b70f13a..c7881f48a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,7 +2,7 @@ version: '2' services: # Base Image to build project - gocompiler-docker-dns-proxy: + compiler-dps: image: golang:1.9 container_name: docker-dns-gocompiler working_dir: /app/src/github.com/mageddo/dns-proxy-server @@ -18,9 +18,8 @@ services: hostname: dns-proxy-server.dev network_mode: bridge - # Run from docker image - prod-docker-dns-prod-server: + prod-dps: container_name: dns-proxy-server image: defreitas/dns-proxy-server:2.4.1 hostname: dns.mageddo @@ -32,24 +31,24 @@ services: - 5380:5380 network_mode: bridge - # Build project and generate docker image - prod-build-docker-dns-proy-server: + # Build the project and generate binary at build folder + prod-build-binary-dps: + extends: compiler-dps + container_name: docker-dns-server-compiler + command: bash -c "builder build" + + # Build project and generate docker image you will need to run prod-build-image-dps first + prod-build-image-dps: build: context: . dockerfile: Dockerfile container_name: docker-dns-server-docker-compiler image: defreitas/dns-proxy-server:2.4.1 - # Build the project and generate binary at build folder - prod-build-dns-proxy-server: - extends: gocompiler-docker-dns-proxy - container_name: docker-dns-server-compiler - command: bash -c "builder build" - # build the project and make the github release prod-ci-deploy: container_name: prod-ci-deploy - extends: gocompiler-docker-dns-proxy + extends: compiler-dps command: bash -c "builder deploy-ci" environment: - CURRENT_BRANCH=$TRAVIS_BRANCH # current branch name diff --git a/docs/Compiling-the-project-from-source.md b/docs/Compiling-the-project-from-source.md index 209033d36..00687b380 100644 --- a/docs/Compiling-the-project-from-source.md +++ b/docs/Compiling-the-project-from-source.md @@ -5,7 +5,7 @@ Docker-Dns-proxy uses docker to simplify the compile process Generate the binaries - $ docker-compose up prod-build-dns-proxy-server + $ docker-compose up prod-build-binary-dps Starting docker-dns-server-compiler Attaching to docker-dns-server-compiler docker-dns-server-compiler | ok github.com/mageddo/dns-proxy-server/conf 0.008s @@ -18,7 +18,7 @@ Generate the binaries Create the docker image - $ docker-compose build prod-build-docker-dns-proy-server + $ docker-compose build prod-build-image-dps # Used tecnologies diff --git a/docs/Developing-at-the-project.md b/docs/Developing-at-the-project.md index 9ad80977d..07d91811a 100644 --- a/docs/Developing-at-the-project.md +++ b/docs/Developing-at-the-project.md @@ -2,7 +2,7 @@ Setup the environment - $ docker-compose -d gocompiler-docker-dns-proxy up + $ docker-compose -d compiler-dps up $ docker exec -it gocompiler bash Running the application diff --git a/events/docker/docker.go b/events/docker/docker.go index fcd0329ef..8b7bab30d 100644 --- a/events/docker/docker.go +++ b/events/docker/docker.go @@ -8,7 +8,7 @@ import ( "io" "github.com/docker/engine-api/client" "golang.org/x/net/context" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "github.com/docker/engine-api/types" "github.com/mageddo/dns-proxy-server/cache/lru" "github.com/mageddo/dns-proxy-server/cache" @@ -16,16 +16,14 @@ import ( "errors" ) -var c = lru.New(43690); +var c = lru.New(43690) func HandleDockerEvents(){ - defaultLogger := log.NewContext() - logger := log.NewLog(defaultLogger) // connecting to docker api cli, err := client.NewClient("unix:///var/run/docker.sock", "v1.21", nil, nil) if err != nil { - logger.Errorf("status=error-to-connect-at-host, solver=docker, err=%v", err) + logging.Errorf("status=error-to-connect-at-host, solver=docker, err=%v", err) return } @@ -34,11 +32,11 @@ func HandleDockerEvents(){ ctx := context.Background() serverVersion, err := cli.ServerVersion(ctx) - logger.Infof("serverVersion=%+v, err=%v", serverVersion, err) + logging.Infof("serverVersion=%+v, err=%v", serverVersion, err) containers, err := cli.ContainerList(ctx, options) if err != nil { - logger.Errorf("status=error-to-list-container, solver=docker, err=%v", err) + logging.Errorf("status=error-to-list-container, solver=docker, err=%v", err) return } @@ -51,28 +49,27 @@ func HandleDockerEvents(){ // registering at events before get the list of actual containers, this way no one container will be missed #55 body, err := cli.Events(ctx, types.EventsOptions{ Filters: eventFilter }) if err != nil { - logger.Errorf("status=error-to-attach-at-events-handler, solver=docker, err=%v", err) + logging.Errorf("status=error-to-attach-at-events-handler, solver=docker, err=%v", err) return } for _, c := range containers { cInspection, err := cli.ContainerInspect(ctx, c.ID) - logger.Infof("status=container-from-list-begin, container=%s", cInspection.Name) + logging.Infof("status=container-from-list-begin, container=%s", cInspection.Name) if err != nil { - logger.Errorf("status=inspect-error-at-list, container=%s, err=%v", c.Names, err) + logging.Errorf("status=inspect-error-at-list, container=%s, err=%v", c.Names, err) } hostnames := getHostnames(cInspection) - putHostnames(defaultLogger, hostnames, cInspection) - logger.Infof("status=container-from-list-success, container=%s, hostnames=%s", cInspection.Name, hostnames) + putHostnames(hostnames, cInspection) + logging.Infof("status=container-from-list-success, container=%s, hostnames=%s", cInspection.Name, hostnames) } dec := json.NewDecoder(body) for { - logCtx := log.NewContext() - logger = log.NewLog(logCtx) + ctx := context.Background() var event events.Message err := dec.Decode(&event) @@ -82,7 +79,7 @@ func HandleDockerEvents(){ cInspection, err := cli.ContainerInspect(ctx, event.ID) if err != nil { - logger.Warningf("status=inspect-error, id=%s, err=%v", event.ID, err) + logging.Warningf("status=inspect-error, id=%s, err=%v", event.ID, err) continue } hostnames := getHostnames(cInspection) @@ -90,11 +87,11 @@ func HandleDockerEvents(){ if len(action) == 0 { action = event.Status } - logger.Infof("status=resolved-hosts, action=%s, hostnames=%s", action, hostnames) + logging.Infof("status=resolved-hosts, action=%s, hostnames=%s", action, hostnames) switch action { case "start": - putHostnames(logCtx, hostnames, cInspection) + putHostnames(hostnames, cInspection) break case "stop", "die": @@ -136,8 +133,7 @@ func getHostnames(inspect types.ContainerJSON) []string { return hostnames } -func putHostnames(ctx context.Context, hostnames []string, inspect types.ContainerJSON) error { - logger := log.NewLog(ctx) +func putHostnames(hostnames []string, inspect types.ContainerJSON) error { for _, host := range hostnames { var ip string = "" @@ -148,11 +144,11 @@ func putHostnames(ctx context.Context, hostnames []string, inspect types.Contain ip = inspect.NetworkSettings.IPAddress; if len(ip) == 0 { err := fmt.Sprintf("no network found to %s", inspect.Name) - logger.Error(err) + logging.Error(err) return errors.New(err) } } - logger.Debugf("host=%s, ip=%s", host, ip) + logging.Debugf("host=%s, ip=%s", host, ip) c.Put(host, ip) } return nil diff --git a/events/local/local.go b/events/local/local.go index 26ff26f6d..0f4074bf6 100644 --- a/events/local/local.go +++ b/events/local/local.go @@ -3,7 +3,7 @@ package local import ( "encoding/json" "os" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "bufio" "github.com/mageddo/dns-proxy-server/utils" "errors" @@ -14,7 +14,6 @@ import ( "github.com/mageddo/dns-proxy-server/flags" "strings" "github.com/mageddo/dns-proxy-server/cache/store" - . "github.com/mageddo/dns-proxy-server/log" ) var confPath string = GetConfPath() @@ -23,19 +22,18 @@ func GetConfPath() string { return utils.GetPath(*flags.ConfPath) } -func LoadConfiguration(ctx context.Context) (*LocalConfiguration, error){ +func LoadConfiguration() (*LocalConfiguration, error){ configuration := LocalConfiguration { Envs: make([]EnvVo, 0), RemoteDnsServers: make([][4]byte, 0), } - logger := log.NewLog(ctx) - logger.Infof("status=begin, confPath=%s", confPath) + logging.Infof("status=begin, confPath=%s", confPath) if _, err := os.Stat(confPath); err == nil { - logger.Info("status=openingFile") + logging.Info("status=openingFile") f, _ := os.Open(confPath) defer f.Close() @@ -48,38 +46,37 @@ func LoadConfiguration(ctx context.Context) (*LocalConfiguration, error){ for j := range env.Hostnames { host := &env.Hostnames[j] if host.Id <= 0 { - logger.Infof("status=without-id, hostname=%s, id=%d", host.Hostname, host.Id) + logging.Infof("status=without-id, hostname=%s, id=%d", host.Hostname, host.Id) host.Id = configuration.nextId() } } } - logger.Info("status=success") + logging.Info("status=success") }else{ - logger.Info("status=create-new-conf") + logging.Info("status=create-new-conf") err := os.MkdirAll(confPath[:strings.LastIndex(confPath, "/")], 0755) if err != nil { - logger.Errorf("status=error-to-create-conf-folder, err=%v", err) + logging.Errorf("status=error-to-create-conf-folder, err=%v", err) return nil, err } - SaveConfiguration(ctx, &configuration) - logger.Info("status=success") + SaveConfiguration(&configuration) + logging.Info("status=success") } return &configuration, nil } -func SaveConfiguration(ctx context.Context, c *LocalConfiguration) { +func SaveConfiguration(c *LocalConfiguration) { t := time.Now() - logger := log.NewLog(ctx) - logger.Debugf("status=begin") + logging.Debugf("status=begin") if len(c.Envs) == 0 { c.Envs = NewEmptyEnv() } - logger.Debugf("status=save") + logging.Debugf("status=save") f, err := os.OpenFile(confPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) if err != nil { - logger.Errorf("status=error-to-create-conf-file, err=%v", err) + logging.Errorf("status=error-to-create-conf-file, err=%v", err) return } defer f.Close() @@ -89,10 +86,10 @@ func SaveConfiguration(ctx context.Context, c *LocalConfiguration) { enc.SetIndent("", "\t") err = enc.Encode(c) if err != nil { - logger.Errorf("status=error-to-encode, error=%v", err) + logging.Errorf("status=error-to-encode, error=%v", err) } store.GetInstance().Clear() - logger.Infof("status=success, time=%d", utils.DiffMillis(t, time.Now())) + logging.Infof("status=success, time=%d", utils.DiffMillis(t, time.Now())) } @@ -139,10 +136,9 @@ func (lc *LocalConfiguration) GetEnv(envName string) (*EnvVo, int) { return nil, -1 } -func (foundEnv *EnvVo) AddHostname(ctx context.Context, hostname *HostnameVo) error { +func (foundEnv *EnvVo) AddHostname(hostname *HostnameVo) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, env=%s, hostname=%+v", foundEnv.Name, hostname) + logging.Infof("status=begin, env=%s, hostname=%+v", foundEnv.Name, hostname) if foundEnv == nil { return errors.New("env not found") } @@ -152,7 +148,7 @@ func (foundEnv *EnvVo) AddHostname(ctx context.Context, hostname *HostnameVo) er } (*foundEnv).Hostnames = append(foundEnv.Hostnames, *hostname) - logger.Infof("status=success, foundEnv=%s", foundEnv.Name) + logging.Infof("status=success, foundEnv=%s", foundEnv.Name) return nil } @@ -171,26 +167,24 @@ func(env *EnvVo) GetHostname(hostname string) (*HostnameVo, int) { } func(env *EnvVo) FindHostnameByName(ctx context.Context, hostname string) *[]HostnameVo { - logger := log.NewLog(ctx) - logger.Infof("status=begin, hostname=%s", hostname) + logging.Infof("status=begin, hostname=%s", hostname) hostList := []HostnameVo{} for _, host := range env.Hostnames { if matched, _ := regexp.MatchString(fmt.Sprintf(".*%s.*", hostname), host.Hostname); matched { hostList = append(hostList, host) } } - logger.Infof("status=success, hostname=%s, length=%d", hostname, len(hostList)) + logging.Infof("status=success, hostname=%s, length=%d", hostname, len(hostList)) return &hostList } func(lc *LocalConfiguration) FindHostnameByNameAndEnv(ctx context.Context, envName, hostname string) (*[]HostnameVo, error) { - logger := log.NewLog(ctx) - logger.Infof("status=begin, envName=%s, hostname=%s", envName, hostname) + logging.Infof("status=begin, envName=%s, hostname=%s", envName, hostname) env,_ := lc.GetEnv(envName) if env == nil { return nil, errors.New("env not found") } - logger.Infof("status=success, envName=%s, hostname=%s", envName, hostname) + logging.Infof("status=success, envName=%s, hostname=%s", envName, hostname) return env.FindHostnameByName(ctx, hostname), nil } @@ -205,77 +199,72 @@ func(env *EnvVo) GetHostnameById(id int) (*HostnameVo, int) { } func (lc *LocalConfiguration) AddEnv(ctx context.Context, env EnvVo) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, env=%s", env.Name) + logging.Infof("status=begin, env=%s", env.Name) foundEnv, _ := lc.GetEnv(env.Name) if foundEnv != nil { return errors.New(fmt.Sprintf("The '%s' env already exists", env.Name)) } lc.Envs = append(lc.Envs, env) - SaveConfiguration(ctx, lc) - logger.Infof("status=success, env=%s", env.Name) + SaveConfiguration(lc) + logging.Infof("status=success, env=%s", env.Name) return nil } -func (lc *LocalConfiguration) RemoveEnvByName(ctx context.Context, name string) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, env=%s", name) +func (lc *LocalConfiguration) RemoveEnvByName(name string) error { + logging.Infof("status=begin, env=%s", name) env, i := lc.GetEnv(name) if env == nil { return errors.New(fmt.Sprintf("The env '%s' was not found", name)) } - lc.RemoveEnv(ctx, i) - SaveConfiguration(ctx,lc) - logger.Infof("status=success, env=%s", name) + lc.RemoveEnv(i) + SaveConfiguration(lc) + logging.Infof("status=success, env=%s", name) return nil } -func (lc *LocalConfiguration) RemoveEnv(ctx context.Context, index int){ - logger := log.NewLog(ctx) - logger.Infof("status=begin, index=%d", index) +func (lc *LocalConfiguration) RemoveEnv(index int){ + logging.Infof("status=begin, index=%d", index) lc.Envs = append(lc.Envs[:index], lc.Envs[index+1:]...) - SaveConfiguration(ctx,lc) - logger.Infof("status=success, index=%d", index) + SaveConfiguration(lc) + logging.Infof("status=success, index=%d", index) } -func (lc *LocalConfiguration) AddDns(ctx context.Context, dns [4]byte){ +func (lc *LocalConfiguration) AddDns( dns [4]byte){ lc.RemoteDnsServers = append(lc.RemoteDnsServers, dns) - SaveConfiguration(ctx, lc) + SaveConfiguration(lc) } -func (lc *LocalConfiguration) RemoveDns(ctx context.Context, index int){ +func (lc *LocalConfiguration) RemoveDns(index int){ lc.RemoteDnsServers = append(lc.RemoteDnsServers[:index], lc.RemoteDnsServers[index+1:]...) - SaveConfiguration(ctx, lc) + SaveConfiguration(lc) } -func (lc *LocalConfiguration) AddHostname(ctx context.Context, envName string, hostname HostnameVo) error { - logger := log.NewLog(ctx) +func (lc *LocalConfiguration) AddHostname(envName string, hostname HostnameVo) error { hostname.Id = lc.nextId() - logger.Infof("status=begin, evnName=%s, hostname=%+v", envName, hostname) + logging.Infof("status=begin, evnName=%s, hostname=%+v", envName, hostname) foundEnv, _ := lc.GetEnv(envName) if foundEnv == nil { return errors.New("env not found") } - err := foundEnv.AddHostname(ctx, &hostname) + err := foundEnv.AddHostname(&hostname) if err != nil { return err } - SaveConfiguration(ctx, lc) - logger.Infof("status=success") + SaveConfiguration(lc) + logging.Infof("status=success") return nil } func (lc *LocalConfiguration) nextId() int { - lc.LastId++; - return lc.LastId; + lc.LastId++ + return lc.LastId } -func (lc *LocalConfiguration) UpdateHostname(ctx context.Context, envName string, hostname HostnameVo) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, evnName=%s, hostname=%+v", envName, hostname) +func (lc *LocalConfiguration) UpdateHostname(envName string, hostname HostnameVo) error { + logging.Infof("status=begin, evnName=%s, hostname=%+v", envName, hostname) env, _ := lc.GetEnv(envName) - if(env == nil){ + if env == nil { return errors.New("env not found") } @@ -284,8 +273,8 @@ func (lc *LocalConfiguration) UpdateHostname(ctx context.Context, envName string return err } - SaveConfiguration(ctx, lc) - logger.Infof("status=success") + SaveConfiguration(lc) + logging.Infof("status=success") return nil } @@ -302,9 +291,8 @@ func (env *EnvVo) UpdateHostname(hostname HostnameVo) error { return nil } -func (lc *LocalConfiguration) RemoveHostnameByEnvAndHostname(ctx context.Context, envName string, hostname string) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, envName=%s, hostname=%s", envName, hostname) +func (lc *LocalConfiguration) RemoveHostnameByEnvAndHostname(envName string, hostname string) error { + logging.Infof("status=begin, envName=%s, hostname=%s", envName, hostname) env, envIndex := lc.GetEnv(envName) if envIndex == -1 { return errors.New("env not found") @@ -313,33 +301,31 @@ func (lc *LocalConfiguration) RemoveHostnameByEnvAndHostname(ctx context.Context if host == nil { return errors.New("hostname not found") } - lc.RemoveHostname(ctx, envIndex, hostIndex) - logger.Infof("status=success, envName=%s, hostname=%s", envName, hostname) + lc.RemoveHostname(envIndex, hostIndex) + logging.Infof("status=success, envName=%s, hostname=%s", envName, hostname) return nil } -func (lc *LocalConfiguration) RemoveHostname(ctx context.Context, envIndex int, hostIndex int){ +func (lc *LocalConfiguration) RemoveHostname(envIndex int, hostIndex int){ - logger := log.NewLog(ctx) - logger.Infof("status=begin, envIndex=%d, hostIndex=%d", envIndex, hostIndex) - env := &lc.Envs[envIndex]; + logging.Infof("status=begin, envIndex=%d, hostIndex=%d", envIndex, hostIndex) + env := &lc.Envs[envIndex] (*env).Hostnames = append((*env).Hostnames[:hostIndex], (*env).Hostnames[hostIndex+1:]...) - SaveConfiguration(ctx, lc) - logger.Infof("status=success, envIndex=%d, hostIndex=%d", envIndex, hostIndex) + SaveConfiguration(lc) + logging.Infof("status=success, envIndex=%d, hostIndex=%d", envIndex, hostIndex) } -func (lc *LocalConfiguration) SetActiveEnv(ctx context.Context, env EnvVo) error { - logger := log.NewLog(ctx) - logger.Infof("status=begin, envActive=%s", env.Name) +func (lc *LocalConfiguration) SetActiveEnv(env EnvVo) error { + logging.Infof("status=begin, envActive=%s", env.Name) foundEnv, _ := lc.GetEnv(env.Name) if foundEnv == nil { - logger.Warningf("status=env-not-found, envName=%s", env.Name) + logging.Warningf("status=env-not-found, envName=%s", env.Name) return errors.New("Env not found: " + env.Name) } lc.ActiveEnv = env.Name - SaveConfiguration(ctx, lc) - logger.Infof("status=success") + SaveConfiguration(lc) + logging.Infof("status=success") return nil } @@ -350,15 +336,15 @@ func NewEmptyEnv() []EnvVo { func (lc *LocalConfiguration) GetRemoteServers(ctx context.Context) [][4]byte { if len(lc.RemoteDnsServers) == 0 { lc.RemoteDnsServers = append(lc.RemoteDnsServers, [4]byte{8, 8, 8, 8}) - logger := log.NewLog(ctx) - logger.Infof("status=put-default-server") + logging.Infof("status=put-default-server") } return lc.RemoteDnsServers } func ResetConf() { if err := os.Remove(confPath); err != nil { - LOGGER.Fatalf("reset=failed, err=%v", err) + logging.Errorf("reset=failed, err=%v", err) + os.Exit(-1) } store.GetInstance().Clear() } diff --git a/events/local/local_test.go b/events/local/local_test.go index b8b63dcf7..baf3bfcb8 100644 --- a/events/local/local_test.go +++ b/events/local/local_test.go @@ -2,7 +2,6 @@ package local import ( "testing" - "github.com/mageddo/go-logging" "github.com/stretchr/testify/assert" "github.com/mageddo/dns-proxy-server/cache/store" ) @@ -13,15 +12,14 @@ func TestSaveConfiguration_ClearCacheAfterChangeConfiguration(t *testing.T) { expectedHostname := "github.io" - ctx := logging.NewContext() - conf, err := LoadConfiguration(ctx) + conf, err := LoadConfiguration() assert.Nil(t, err, "could not load conf") cache := store.GetInstance() env, _ := conf.GetActiveEnv() foundHostname, _ := env.GetHostname(expectedHostname) - assert.Nil(t, foundHostname) + assert.Nil(t, foundHostname, "can't be nil") // setting the host cache.Put(expectedHostname, foundHostname) @@ -30,7 +28,7 @@ func TestSaveConfiguration_ClearCacheAfterChangeConfiguration(t *testing.T) { // changing value for the hostname at configuration database hostname := HostnameVo{Ip: [4]byte{192,168,0,2}, Ttl:30, Env:"", Hostname: expectedHostname} - conf.AddHostname(ctx, "", hostname) + conf.AddHostname( "", hostname) // cache must be clear after add a hostname in conf assert.False(t, cache.ContainsKey(expectedHostname)) diff --git a/log/log.go b/log/log.go index 3b9299818..6e8755791 100644 --- a/log/log.go +++ b/log/log.go @@ -6,48 +6,12 @@ import ( "io" ) -var LOGGER logging.Log -var LEVEL string = "" func init(){ setup(os.Stdout) } func setup(out io.Writer) { - - mode := "dev" - backend := logging.NewLogBackend(out, "", 0) - // setando o log dependendo do ambiente - switch mode { - case "prod": - format := logging.MustStringFormatter( - `%{time:06-01-02 15:04:05} %{level:.3s} %{message}`, - ) - leveledBackend := logging.AddModuleLevel(logging.NewBackendFormatter(backend, format)) - logging.SetBackend(leveledBackend) - logging.SetLevel(logging.INFO, "") - break - default: - format := logging.MustStringFormatter( - `%{color}%{time:06-01-02 15:04:05.000} %{level:.3s} %{color:reset}%{message}`, - ) - backend2Formatter := logging.NewBackendFormatter(backend, format) - logging.SetBackend(backend2Formatter) - break - } - LOGGER = logging.NewLog(logging.NewContext()) - if LEVEL != "" { - SetLevel(LEVEL) - } -} - -func SetLevel(level string) error { - LEVEL = level - lvl, err := logging.LogLevel(level) - if err != nil { - return err - } - logging.SetLevel(lvl, "") - return nil + logging.SetOutput(out) } func SetOutput(f string) error { @@ -55,10 +19,6 @@ func SetOutput(f string) error { setup(os.Stdout) return nil } - if f == "" { - SetLevel("CRITICAL") - return nil - } out, err := os.OpenFile(f, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend) if err != nil { diff --git a/proxy/docker.go b/proxy/docker.go index c527b38d4..05d6e0a46 100644 --- a/proxy/docker.go +++ b/proxy/docker.go @@ -3,7 +3,7 @@ package proxy import ( "errors" "github.com/mageddo/dns-proxy-server/cache" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "github.com/miekg/dns" "golang.org/x/net/context" "net" @@ -17,15 +17,14 @@ type DockerDnsSolver struct { func (s DockerDnsSolver) Solve(ctx context.Context, question dns.Question) (*dns.Msg, error) { - logger := log.NewLog(ctx) key := question.Name[:len(question.Name)-1] if s.c.ContainsKey(key) { - logger.Debugf("solver=docker, status=solved-key, solver=docker, hostname=%s, ip=%+v", key, s.c.Get(key)) + logging.Debugf("solver=docker, status=solved-key, solver=docker, hostname=%s, ip=%+v", key, s.c.Get(key)) return s.getMsg(key, question), nil } i := strings.Index(key, ".") if i > 0 && s.c.ContainsKey(key[i:]) { - logger.Debugf("solver=docker, status=solved-key-wildcard, solver=docker, hostname=%s, ip=%+v", key, s.c.Get(key[i:])) + logging.Debugf("solver=docker, status=solved-key-wildcard, solver=docker, hostname=%s, ip=%+v", key, s.c.Get(key[i:])) return s.getMsg(key[i:], question), nil } return nil, errors.New("hostname not found " + key) diff --git a/proxy/docker_test.go b/proxy/docker_test.go index bd59bb769..e6e10ba13 100644 --- a/proxy/docker_test.go +++ b/proxy/docker_test.go @@ -5,14 +5,13 @@ import ( "github.com/miekg/dns" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/assert" - "github.com/mageddo/go-logging" "github.com/mageddo/dns-proxy-server/cache/lru" "github.com/mageddo/dns-proxy-server/cache" glru "github.com/hashicorp/golang-lru" + "context" ) -var ctx = logging.NewContext() -var logger = logging.NewLog(ctx) +var ctx = context.Background() func TestDockerSolve_HostFound(t *testing.T){ c := newCacheMock() @@ -65,4 +64,4 @@ func newCacheMock() cache.Cache { panic(err); } return &m -} \ No newline at end of file +} diff --git a/proxy/local.go b/proxy/local.go index 23f6c2bd9..1d265b557 100644 --- a/proxy/local.go +++ b/proxy/local.go @@ -5,12 +5,12 @@ import ( "github.com/mageddo/dns-proxy-server/cache" "github.com/mageddo/dns-proxy-server/cache/timed" "github.com/mageddo/dns-proxy-server/events/local" - . "github.com/mageddo/dns-proxy-server/log" "github.com/miekg/dns" "golang.org/x/net/context" "net" "strings" "time" + "github.com/mageddo/go-logging" ) type localDnsSolver struct { @@ -37,14 +37,14 @@ func NewLocalDNSSolver(c cache.Cache) *localDnsSolver { func (s localDnsSolver) ContainsKey(key interface{}) (interface{}, bool) { if !s.Cache.ContainsKey(key) { - LOGGER.Debugf("status=notfound, key=%v", key) + logging.Debugf("status=notfound, key=%v", key) return nil, false } if v := s.Cache.Get(key).(timed.TimedValue); v.IsValid(time.Now()) { - LOGGER.Debugf("status=fromcache, key=%v", key) + logging.Debugf("status=fromcache, key=%v", key) return v.Value(), true } - LOGGER.Debugf("status=expired, key=%v", key) + logging.Debugf("status=expired, key=%v", key) s.Cache.Remove(key) return nil, false } @@ -61,17 +61,17 @@ func (*localDnsSolver) getMsg(question dns.Question, hostname *local.HostnameVo) func (s localDnsSolver) solveHostname(ctx context.Context, question dns.Question, key string) (*dns.Msg, error) { if value, found := s.ContainsKey(key); found { - LOGGER.Debugf("solver=local, status=from-cache, hostname=%s, value=%v", key, value) + logging.Debugf("solver=local, status=from-cache, hostname=%s, value=%v", key, value) hostname := value.(*local.HostnameVo) if hostname != nil { return s.getMsg(question, hostname), nil } } - LOGGER.Debugf("solver=local, status=hot-load, hostname=%s", key) - conf, err := local.LoadConfiguration(ctx) + logging.Debugf("solver=local, status=hot-load, hostname=%s", key) + conf, err := local.LoadConfiguration() if err != nil { - LOGGER.Errorf("status=could-not-load-conf, err=%v", err) + logging.Errorf("status=could-not-load-conf, err=%v", err) return nil, err } activeEnv, _ := conf.GetActiveEnv() @@ -84,7 +84,7 @@ func (s localDnsSolver) solveHostname(ctx context.Context, question dns.Question ttl = int64(hostname.Ttl) } val := s.Cache.PutIfAbsent(key, timed.NewTimedValue(hostname, time.Now(), time.Duration(ttl)*time.Second)) - LOGGER.Debugf("status=put, key=%s, value=%v, ttl=%d", key, val, ttl) + logging.Debugf("status=put, key=%s, value=%v, ttl=%d", key, val, ttl) if hostname != nil { return s.getMsg(question, hostname), nil } diff --git a/proxy/local_test.go b/proxy/local_test.go index fbb68c8c1..db2c87974 100644 --- a/proxy/local_test.go +++ b/proxy/local_test.go @@ -6,7 +6,6 @@ import ( "github.com/mageddo/dns-proxy-server/cache/lru" "github.com/mageddo/dns-proxy-server/cache/store" "github.com/mageddo/dns-proxy-server/events/local" - "github.com/mageddo/go-logging" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -18,13 +17,12 @@ func TestLocalDnsSolver_Solve(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - conf, err := local.LoadConfiguration(ctx) + conf, err := local.LoadConfiguration() assert.Nil(t, err, "failed to load configuration") expectedHostname := "github.com" host := local.HostnameVo{Hostname: expectedHostname, Env: "", Ttl: 50, Ip: [4]byte{192, 168, 0, 1}} - conf.AddHostname(ctx, "", host) + conf.AddHostname( "", host) question := new(dns.Question) question.Name = expectedHostname + "." @@ -45,8 +43,6 @@ func TestLocalDnsSolver_SolveNotFoundHost(t *testing.T) { defer local.ResetConf() expectedHostname := "github.com" - ctx := logging.NewContext() - question := new(dns.Question) question.Name = expectedHostname + "." solver := NewLocalDNSSolver(store.GetInstance()) @@ -66,14 +62,13 @@ func TestLocalDnsSolver_SolveValidatingCache(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - conf, err := local.LoadConfiguration(ctx) + conf, err := local.LoadConfiguration() assert.Nil(t, err, "failed to load configuration") // configuring a new host at local configuration expectedHostname := "github.com" host := local.HostnameVo{Hostname: expectedHostname, Env: "", Ttl: 50, Ip: [4]byte{192, 168, 0, 1}} - conf.AddHostname(ctx, "", host) + conf.AddHostname( "", host) // creating a request for the created host question := new(dns.Question) @@ -108,14 +103,13 @@ func TestLocalDnsSolver_SolveCacheExpiration(t *testing.T) { defer local.ResetConf() - ctx := logging.NewContext() - conf, err := local.LoadConfiguration(ctx) + conf, err := local.LoadConfiguration() assert.Nil(t, err, "failed to load configuration") // configuring a new host at local configuration expectedHostname := "github.com" host := local.HostnameVo{Hostname: expectedHostname, Env: "", Ttl: 2, Ip: [4]byte{192, 168, 0, 1}} - conf.AddHostname(ctx, "", host) + conf.AddHostname( "", host) // creating a request for the created host question := new(dns.Question) @@ -156,12 +150,11 @@ func TestLocalDnsSolver_SolvingByWildcard(t *testing.T) { solver := NewLocalDNSSolver(c) defer local.ResetConf() - ctx := logging.NewContext() - conf, err := local.LoadConfiguration(ctx) + conf, err := local.LoadConfiguration() assert.Nil(t, err, "failed to load configuration") host := local.HostnameVo{Hostname: ".github.com", Env: "", Ttl: 2, Ip: [4]byte{192, 168, 0, 1}} - conf.AddHostname(ctx, "", host) + conf.AddHostname( "", host) question := new(dns.Question) question.Name = "server1.github.com." @@ -184,12 +177,11 @@ func TestLocalDnsSolver_WildcardRegisteredButNotMatched(t *testing.T) { solver := NewLocalDNSSolver(c) defer local.ResetConf() - ctx := logging.NewContext() - conf, err := local.LoadConfiguration(ctx) + conf, err := local.LoadConfiguration() assert.Nil(t, err, "failed to load configuration") host := local.HostnameVo{Hostname: ".github.com", Env: "", Ttl: 2, Ip: [4]byte{192, 168, 0, 1}} - conf.AddHostname(ctx, "", host) + conf.AddHostname( "", host) question := new(dns.Question) question.Name = "server1.mageddo.com." diff --git a/proxy/remote.go b/proxy/remote.go index cb7229c8f..f1985fb98 100644 --- a/proxy/remote.go +++ b/proxy/remote.go @@ -7,7 +7,7 @@ import ( "fmt" "golang.org/x/net/context" "github.com/mageddo/dns-proxy-server/events/local" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "github.com/mageddo/dns-proxy-server/cache/store" ) @@ -21,7 +21,6 @@ type remoteDnsSolver struct { // reference https://miek.nl/2014/August/16/go-dns-package/ func (r remoteDnsSolver) Solve(ctx context.Context, question dns.Question) (*dns.Msg, error) { c := store.GetInstance() - logger := log.NewLog(ctx) client := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(question.Name), question.Qtype) // CAN BE A, AAA, MX, etc. @@ -30,27 +29,27 @@ func (r remoteDnsSolver) Solve(ctx context.Context, question dns.Question) (*dns var config *local.LocalConfiguration var err error if !c.ContainsKey(SERVERS) { - logger.Debugf("solver=remote, status=servers-hot-load") + logging.Debugf("solver=remote, status=servers-hot-load") if config, err = r.confloader(ctx); err != nil { - logger.Errorf("error=%v",err) + logging.Errorf("error=%v",err) return nil, err } c.PutIfAbsent(SERVERS, config) } else { - logger.Debugf("solver=remote, status=servers-from-cache") + logging.Debugf("solver=remote, status=servers-from-cache") } config = c.Get(SERVERS).(*local.LocalConfiguration) for _, server := range config.GetRemoteServers(ctx) { if len(server) != 4 { - logger.Warning("status=wrong-server, server=%+v", server) + logging.Warning("status=wrong-server, server=%+v", server) continue } // server and port to ask formatServer := fmt.Sprintf("%d.%d.%d.%d", server[0], server[1], server[2], server[3]) - logger.Debugf("status=format-server, server=%s", formatServer) + logging.Debugf("status=format-server, server=%s", formatServer) var r *dns.Msg r, _, err = client.Exchange(m, net.JoinHostPort(formatServer, "53")) @@ -58,11 +57,11 @@ func (r remoteDnsSolver) Solve(ctx context.Context, question dns.Question) (*dns // if the answer not be returned if r == nil { err = errors.New(fmt.Sprintf("status=answer-can-not-be-null, err=%v", err)) - logger.Infof("status=no-answer, err=%s", err) + logging.Infof("status=no-answer, err=%s", err) continue } else if r.Rcode != dns.RcodeSuccess { // what the code of the return message ? err = errors.New(fmt.Sprintf("status=invalid-answer-name, name=%s, rcode=%d", question.Name, r.Rcode)) - logger.Infof("status=bad-code, name=%s, rcode=%d, err=%s", question.Name, r.Rcode, err) + logging.Infof("status=bad-code, name=%s, rcode=%d, err=%s", question.Name, r.Rcode, err) continue } return r, nil @@ -73,6 +72,6 @@ func (r remoteDnsSolver) Solve(ctx context.Context, question dns.Question) (*dns func NewRemoteDnsSolver() *remoteDnsSolver { return &remoteDnsSolver{ confloader: func(ctx context.Context) (*local.LocalConfiguration, error) { - return local.LoadConfiguration(ctx) + return local.LoadConfiguration() }} } diff --git a/proxy/remote_test.go b/proxy/remote_test.go index 320cd74ea..9a8a5b64f 100644 --- a/proxy/remote_test.go +++ b/proxy/remote_test.go @@ -7,7 +7,6 @@ import ( "github.com/mageddo/go-logging" "github.com/mageddo/dns-proxy-server/events/local" "context" - "github.com/mageddo/dns-proxy-server/log" ) type MockedRemoteDnsSolver struct { @@ -16,18 +15,16 @@ type MockedRemoteDnsSolver struct { } func (m MockedRemoteDnsSolver) loadConfiguration(ctx context.Context) (*local.LocalConfiguration, error) { - log.LOGGER.Infof("status=mocked-config") - return local.LoadConfiguration(ctx) + logging.Infof("status=mocked-config") + return local.LoadConfiguration() } func TestRemoteDnsSolver_SolveCacheSuccess(t *testing.T) { - ctx := logging.NewContext() - remoteSolver := new(MockedRemoteDnsSolver) remoteSolver.confloader = func(ctx context.Context) (*local.LocalConfiguration, error) { remoteSolver.MethodCalled("confloader", ctx) - return local.LoadConfiguration(ctx) + return local.LoadConfiguration() } remoteSolver.On("confloader", ctx).Once() diff --git a/resolvconf/resolvconf.go b/resolvconf/resolvconf.go index b6bb46c6e..2284d4e6f 100644 --- a/resolvconf/resolvconf.go +++ b/resolvconf/resolvconf.go @@ -1,7 +1,6 @@ package resolvconf import ( - . "github.com/mageddo/dns-proxy-server/log" "bytes" "os" "bufio" @@ -13,13 +12,14 @@ import ( "fmt" "github.com/mageddo/dns-proxy-server/conf" "net" + "github.com/mageddo/go-logging" ) func RestoreResolvconfToDefault() error { - LOGGER.Infof("status=begin") + logging.Infof("status=begin") hd := newDNSServerCleanerHandler() err := ProcessResolvconf(hd) - LOGGER.Infof("status=success, err=%v", err) + logging.Infof("status=success, err=%v", err) return err } @@ -31,7 +31,7 @@ func SetMachineDNSServer(serverIP string) error { func ProcessResolvconf( handler DnsHandler ) error { var newResolvConfBuff bytes.Buffer - LOGGER.Infof("status=begin") + logging.Infof("status=begin") resolvconf := conf.GetResolvConf() fileRead, err := os.Open(resolvconf) @@ -44,7 +44,7 @@ func ProcessResolvconf( handler DnsHandler ) error { hasContent = false foundDnsProxyEntry = false ) - LOGGER.Infof("status=open-conf-file, file=%s", fileRead.Name()) + logging.Infof("status=open-conf-file, file=%s", fileRead.Name()) scanner := bufio.NewScanner(fileRead) for scanner.Scan() { line := scanner.Text() @@ -53,7 +53,7 @@ func ProcessResolvconf( handler DnsHandler ) error { if entryType == PROXY { foundDnsProxyEntry = true } - LOGGER.Debugf("status=readline, line=%s, type=%s", line, entryType) + logging.Debugf("status=readline, line=%s, type=%s", line, entryType) if r := handler.process(line, entryType); r != nil { newResolvConfBuff.WriteString(*r) newResolvConfBuff.WriteByte('\n') @@ -70,7 +70,7 @@ func ProcessResolvconf( handler DnsHandler ) error { if err != nil { return err } - LOGGER.Infof("status=success, buffLength=%d", length) + logging.Infof("status=success, buffLength=%d", length) return nil } @@ -108,7 +108,7 @@ func SetCurrentDNSServerToMachineAndLockIt() error { func SetCurrentDNSServerToMachine() error { ip, err := GetCurrentIpAddress() - LOGGER.Infof("status=begin, ip=%s, err=%v", ip, err) + logging.Infof("status=begin, ip=%s, err=%v", ip, err) if err != nil { return err } @@ -125,7 +125,7 @@ func UnlockResolvConf() error { func LockFile(lock bool, file string) error { - LOGGER.Infof("status=begin, lock=%t, file=%s", lock, file) + logging.Infof("status=begin, lock=%t, file=%s", lock, file) flag := "-i" if lock { flag = "+i" @@ -133,16 +133,16 @@ func LockFile(lock bool, file string) error { cmd := exec.Command("chattr", flag, file) err := cmd.Run() if err != nil { - LOGGER.Warningf("status=error-at-execute, lock=%t, file=%s, err=%v", lock, file, err) + logging.Warningf("status=error-at-execute, lock=%t, file=%s, err=%v", lock, file, err) return err } status := cmd.ProcessState.Sys().(syscall.WaitStatus) if status.ExitStatus() != 0 { - LOGGER.Warningf("status=bad-exit-code, lock=%t, file=%s", lock, file) + logging.Warningf("status=bad-exit-code, lock=%t, file=%s", lock, file) return errors.New(fmt.Sprintf("Failed to lock file %d", status.ExitStatus())) } - LOGGER.Infof("status=success, lock=%t, file=%s", lock, file) + logging.Infof("status=success, lock=%t, file=%s", lock, file) return nil } diff --git a/resolvconf/set_machine_dns_server.go b/resolvconf/set_machine_dns_server.go index 63b2aae28..15e7a5bf6 100644 --- a/resolvconf/set_machine_dns_server.go +++ b/resolvconf/set_machine_dns_server.go @@ -1,8 +1,8 @@ package resolvconf import ( - . "github.com/mageddo/dns-proxy-server/log" "fmt" + "github.com/mageddo/go-logging" ) type setMachineDNSServerHandler struct { @@ -13,7 +13,7 @@ func (hd *setMachineDNSServerHandler) process(line string, entryType DnsEntry) * switch entryType { case PROXY: - LOGGER.Infof("status=found-dns-proxy-entry") + logging.Infof("status=found-dns-proxy-entry") v := getDNSLine(hd.serverIP) return &v case SERVER: diff --git a/service/service.go b/service/service.go index 5261d10e0..e502b807d 100644 --- a/service/service.go +++ b/service/service.go @@ -4,10 +4,9 @@ import ( "fmt" "github.com/mageddo/dns-proxy-server/flags" "github.com/mageddo/dns-proxy-server/utils" - log "github.com/mageddo/go-logging" "os" - "golang.org/x/net/context" "errors" + "github.com/mageddo/go-logging" ) const ( @@ -15,17 +14,14 @@ const ( DNS_PROXY_SERVER_PATH = "/etc/init.d/dns-proxy-server" ) -type Service struct { - ctx context.Context - logger log.Log -} +type Service struct {} type Script struct { Script string } -func NewService(ctx context.Context) *Service { - return &Service{ctx, log.NewLog(ctx)} +func NewService() *Service { + return &Service{} } func (sc *Service) Install() { @@ -34,7 +30,7 @@ func (sc *Service) Install() { if len(serviceMode) == 0 { return } - sc.logger.Infof("mode=%s, version=%s", serviceMode, flags.GetRawCurrentVersion()) + logging.Infof("mode=%s, version=%s", serviceMode, flags.GetRawCurrentVersion()) var err error switch serviceMode { case "docker": @@ -45,7 +41,7 @@ func (sc *Service) Install() { sc.Uninstall() } if err != nil { - sc.logger.Error(err) + logging.Error(err) os.Exit(-1) } os.Exit(0) @@ -54,41 +50,43 @@ func (sc *Service) Install() { func (sc *Service) SetupFor(servicePath, serviceName string, script *Script) error { - sc.logger.Debugf("status=begin, servicePath=%s", servicePath) + logging.Debugf("status=begin, servicePath=%s", servicePath) err := utils.CreateExecutableFile(fmt.Sprintf(SERVICE_TEMPLATE, script.Script), servicePath) if err != nil { err := fmt.Sprintf("status=service-template, msg=%v", err) - sc.logger.Warning(err) + logging.Warning(err) return errors.New(fmt.Sprintf("status=service-template, msg=%v", err)) } if utils.Exists("update-rc.d") { // debian _, err, _ = utils.Exec("update-rc.d", serviceName, "defaults") if err != nil { - sc.logger.Fatalf("status=fatal-install-service, service=update-rc.d, msg=%s", err.Error()) + logging.Errorf("status=fatal-install-service, service=update-rc.d, msg=%s", err.Error(), err) + os.Exit(-1) } } else if utils.Exists("chkconfig") { // redhat _, err, _ = utils.Exec("chkconfig", serviceName, "on") if err != nil { - sc.logger.Fatalf("status=fatal-install-service, service=chkconfig, msg=%s", err.Error()) + logging.Errorf("status=fatal-install-service, service=chkconfig, msg=%s", err.Error(), err) + os.Exit(-2) } } else { // not known - sc.logger.Warningf("status=impossible to setup to start at boot") + logging.Warningf("status=impossible to setup to start at boot") } out, err, _ := utils.Exec("service", serviceName, "stop") if err != nil { - sc.logger.Debugf("status=stop-service, msg=out=%s", string(out)) + logging.Debugf("status=stop-service, msg=out=%s", string(out)) } _, err, _ = utils.Exec("service", serviceName, "start") if err != nil { err := fmt.Sprintf("status=start-service, msg=%v", err) - sc.logger.Warning(err) + logging.Warning(err) return errors.New(err) } - sc.logger.Infof("status=success, servicePath=%s", servicePath) + logging.Infof("status=success, servicePath=%s", servicePath) return nil } @@ -96,11 +94,11 @@ func (sc *Service) SetupFor(servicePath, serviceName string, script *Script) err func (sc *Service) Uninstall() error { - sc.logger.Infof("status=begin") + logging.Infof("status=begin") var err error if out, err, _ := utils.Exec("service", DNS_PROXY_SERVER_SERVICE, "stop"); err != nil { - sc.logger.Infof("status=stop-fail, msg=maibe-no-running, out=%s", string(out)) + logging.Infof("status=stop-fail, msg=maibe-no-running, out=%s", string(out)) } if utils.Exists("update-rc.d") { @@ -108,14 +106,14 @@ func (sc *Service) Uninstall() error { } else if utils.Exists("chkconfig") { _, err, _ = utils.Exec("chkconfig", DNS_PROXY_SERVER_SERVICE, "off") } else { - sc.logger.Warningf("status=impossible to remove service") + logging.Warningf("status=impossible to remove service") } if err != nil { err := fmt.Sprintf("status=fatal-remove-service, msg=%v", err) - sc.logger.Warning(err) + logging.Warning(err) return errors.New(err) } - sc.logger.Infof("status=success") + logging.Infof("status=success") return nil } diff --git a/service/service_test.go b/service/service_test.go index 26c46426a..d755cf507 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -1,8 +1,7 @@ package service import ( - . "github.com/mageddo/dns-proxy-server/log" - log "github.com/mageddo/go-logging" + "github.com/mageddo/go-logging" "testing" "io/ioutil" "github.com/stretchr/testify/assert" @@ -15,13 +14,11 @@ import ( func TestSetupFor_NormalModeInstallStartSuccess(t *testing.T) { if !flags.IsTestVersion() { - LOGGER.Infof("status=test-skiped") + logging.Infof("status=test-skiped") return } - ctx := log.NewContext() - - sc := NewService(ctx) + sc := NewService() cmd := "'sh -c \"echo hi && sleep 20 && echo bye\"'" err := sc.SetupFor(DNS_PROXY_SERVER_PATH, DNS_PROXY_SERVER_SERVICE, &Script{cmd}) assert.Nil(t, err) diff --git a/test/dnsclient.go b/test/dnsclient.go index 1f15940bb..6b17e4923 100644 --- a/test/dnsclient.go +++ b/test/dnsclient.go @@ -1,11 +1,11 @@ package main import ( - . "github.com/mageddo/dns-proxy-server/log" "github.com/miekg/dns" "os" "net" - + + "github.com/mageddo/go-logging" ) // reference https://miek.nl/2014/August/16/go-dns-package/ @@ -23,17 +23,17 @@ func main(){ // if the answer not be returned if r == nil { - LOGGER.Fatalf("**** error: %s", err.Error()) + logging.Errorf("**** error: %s", err.Error()) } // what the code of the return message ? if r.Rcode != dns.RcodeSuccess { - LOGGER.Fatalf(" *** invalid answer name %s after MX query for %s", os.Args[1], os.Args[1]) + logging.Errorf(" *** invalid answer name %s after MX query for %s", os.Args[1], os.Args[1]) } // looping through the anwsers for _, a := range r.Answer { - LOGGER.Infof("%v", a) + logging.Infof("%v", a) } } diff --git a/test/dnsserver.go b/test/dnsserver.go index 48f52eb57..316130f65 100644 --- a/test/dnsserver.go +++ b/test/dnsserver.go @@ -32,7 +32,6 @@ package main import ( - . "github.com/mageddo/dns-proxy-server/log" "flag" "fmt" "os" @@ -43,6 +42,7 @@ import ( "github.com/miekg/dns" "net" "errors" + "github.com/mageddo/go-logging" ) var ( @@ -56,7 +56,7 @@ func handleReflect(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { defer func() { err := recover() if err != nil { - LOGGER.Errorf("status=error, error=%v", err) + logging.Errorf("status=error, error=%v", err) } }() @@ -67,7 +67,7 @@ func handleReflect(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { questionName = "null" } - LOGGER.Infof("questions=%d, 1stQuestion=%s", len(reqMsg.Question), questionName) + logging.Infof("questions=%d, 1stQuestion=%s", len(reqMsg.Question), questionName) resp := SolveName(questionName) resp.SetReply(reqMsg) @@ -79,7 +79,7 @@ func handleReflect(respWriter dns.ResponseWriter, reqMsg *dns.Msg) { firstAnswer = resp.Answer[0] } - LOGGER.Infof("resp=%v", firstAnswer) + logging.Infof("resp=%v", firstAnswer) respWriter.WriteMsg(resp) } @@ -112,7 +112,8 @@ func main2() { if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { - LOGGER.Fatal(err) + logging.Error(err) + os.Exit(-1) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() diff --git a/utils/exec.go b/utils/exec.go index 788aba49e..e87fdbbee 100644 --- a/utils/exec.go +++ b/utils/exec.go @@ -1,22 +1,22 @@ package utils import ( - . "github.com/mageddo/dns-proxy-server/log" "os/exec" "syscall" "reflect" + "github.com/mageddo/go-logging" ) func Exec(cmd string, args ...string) ( out []byte, err error, exitCode int ){ - LOGGER.Infof("cmd=%s, args=%v", cmd, args) + logging.Infof("cmd=%s, args=%v", cmd, args) execution := exec.Command(cmd, args...) // ja chama o run dentro dele out, err = execution.CombinedOutput() if err != nil { - LOGGER.Infof("status=error, type=%v, err=%v", reflect.TypeOf(err), err) + logging.Infof("status=error, type=%v, err=%v", reflect.TypeOf(err), err) if exitError, ok := err.(*exec.ExitError); ok { exitCode = exitError.Sys().(syscall.WaitStatus).ExitStatus() return @@ -29,10 +29,10 @@ func Exec(cmd string, args ...string) ( out []byte, err error, exitCode int ){ } if exitCode != 0 { - LOGGER.Warningf("status=bad-exit-code, status=%d", exitCode) + logging.Warningf("status=bad-exit-code, status=%d", exitCode) return } - LOGGER.Infof("status=success, cmd=%s", cmd) + logging.Infof("status=success, cmd=%s", cmd) return } diff --git a/utils/exitcodes/exitcodes.go b/utils/exitcodes/exitcodes.go index 4f77215bd..df0c2078b 100644 --- a/utils/exitcodes/exitcodes.go +++ b/utils/exitcodes/exitcodes.go @@ -2,9 +2,9 @@ package exitcodes import ( "os" - . "github.com/mageddo/dns-proxy-server/log" "github.com/mageddo/dns-proxy-server/utils" "syscall" + "github.com/mageddo/go-logging" ) const ( @@ -15,10 +15,10 @@ const ( ) func Exit(code int){ - LOGGER.Errorf("status=exiting, code=%d", code) + logging.Errorf("status=exiting, code=%d", code) if code != SUCCESS { utils.Sig <- syscall.Signal(code) - LOGGER.Info("status=msg-posted") + logging.Info("status=msg-posted") } else { os.Exit(code) } diff --git a/vendor/github.com/mageddo/go-httpmap/Gopkg.lock b/vendor/github.com/mageddo/go-httpmap/Gopkg.lock new file mode 100644 index 000000000..02dae8729 --- /dev/null +++ b/vendor/github.com/mageddo/go-httpmap/Gopkg.lock @@ -0,0 +1,19 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/mageddo/go-logging" + packages = [ + ".", + "native", + "pkg/trace" + ] + revision = "46139c893695361b79a476c1ec8a773f7ce9939f" + version = "v2.0" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "e3d3ec39101fec425d3f8c01342d004a97e6671b5933ce1e26ffbb8ee7991e81" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/mageddo/go-httpmap/Gopkg.toml b/vendor/github.com/mageddo/go-httpmap/Gopkg.toml new file mode 100644 index 000000000..a92971bc8 --- /dev/null +++ b/vendor/github.com/mageddo/go-httpmap/Gopkg.toml @@ -0,0 +1,34 @@ +# Gopkg.toml example +# +# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + + +[[constraint]] + name = "github.com/mageddo/go-logging" + version = "2.0.0" + +[prune] + go-tests = true + unused-packages = true diff --git a/vendor/github.com/mageddo/go-httpmap/README.md b/vendor/github.com/mageddo/go-httpmap/README.md new file mode 100644 index 000000000..08fa485a1 --- /dev/null +++ b/vendor/github.com/mageddo/go-httpmap/README.md @@ -0,0 +1,20 @@ +httpmap helps you map yours endpoints with a low overhead, it's just a wrapper that makes your work easier + +### Examples + +```go +Get("/users", func(ctx context.Context, w http.ResponseWriter, r *http.Request){ + ... +}) +Post("/users", func(ctx context.Context, w http.ResponseWriter, r *http.Request){ + ... +}) +Put("/users", func(ctx context.Context, w http.ResponseWriter, r *http.Request){ + ... +}) +``` + +### Installing new deps + + go get -v github.com/golang/dep/cmd/dep && dep ensure -v + diff --git a/vendor/github.com/mageddo/go-httpmap/index.go b/vendor/github.com/mageddo/go-httpmap/index.go new file mode 100644 index 000000000..ac72f3858 --- /dev/null +++ b/vendor/github.com/mageddo/go-httpmap/index.go @@ -0,0 +1,90 @@ +package httpmap + +import ( + "net/http" + "encoding/json" + "github.com/mageddo/go-logging" + "context" + "fmt" + "os" + "sync/atomic" +) + +type Method string +const ( + POST Method = "POST" + GET Method = "GET" + PUT Method = "PUT" + PATCH Method = "PATCH" + DELETE Method = "DELETE" +) + +type Message struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func BadRequest(w http.ResponseWriter, msg string){ + RespMessage(w, 400, msg) +} + +func RespMessage(w http.ResponseWriter, code int, msg string){ + w.WriteHeader(code) + json.NewEncoder(w).Encode(Message{Code:code, Message:msg}) +} + + +func Post(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + handle(POST, path, fn) +} + +func Get(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + handle(GET, path, fn) +} + +func Put(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + handle(PUT, path, fn) +} + +func Delete(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + handle(DELETE, path, fn) +} + +func Patch(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + handle(PATCH, path, fn) +} + +var m = make(map[string]func(context.Context, http.ResponseWriter, *http.Request)) +func handle(method Method, path string, fn func(context.Context, http.ResponseWriter, *http.Request)) { + key := getKey(string(method), path) + if _, ok := m[key]; ok { + logging.Errorf("status-already-registered, key=%s", key) + os.Exit(-1) + } + logging.Infof("status=registering, path=%s", key) + m[key] = fn + + if _, ok := m[path]; ok { + return + } + + http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { + fn, found := m[getKey(r.Method, r.URL.Path)] + logging.Debugf("method=%s, path=%s, found=%t", r.Method, r.URL.Path, found) + if found { + fn(NextId(r.Context()), w, r) + } else { + http.NotFound(w, r) + } + }) + m[path] = nil +} + +func getKey(m string, path string) string { + return fmt.Sprintf("%s %s", m, path) +} + +var counter int64 = 1 +func NextId(ctx context.Context) context.Context { + return context.WithValue(ctx, "ID", atomic.AddInt64(&counter, 1)) +} diff --git a/vendor/github.com/mageddo/go-logging/CHANGELOG.md b/vendor/github.com/mageddo/go-logging/CHANGELOG.md deleted file mode 100644 index 4b7d2335c..000000000 --- a/vendor/github.com/mageddo/go-logging/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# Changelog - -## 2.0.0-rc1 (2016-02-11) - -Time flies and it has been three years since this package was first released. -There have been a couple of API changes I have wanted to do for some time but -I've tried to maintain backwards compatibility. Some inconsistencies in the -API have started to show, proper vendor support in Go out of the box and -the fact that `go vet` will give warnings -- I have decided to bump the major -version. - -* Make eg. `Info` and `Infof` do different things. You want to change all calls - to `Info` with a string format go to `Infof` etc. In many cases, `go vet` will - guide you. -* `Id` in `Record` is now called `ID` - -## 1.0.0 (2013-02-21) - -Initial release diff --git a/vendor/github.com/mageddo/go-logging/CONTRIBUTORS b/vendor/github.com/mageddo/go-logging/CONTRIBUTORS deleted file mode 100644 index 958416ef1..000000000 --- a/vendor/github.com/mageddo/go-logging/CONTRIBUTORS +++ /dev/null @@ -1,5 +0,0 @@ -Alec Thomas -Guilhem Lettron -Ivan Daniluk -Nimi Wariboko Jr -Róbert Selvek diff --git a/vendor/github.com/mageddo/go-logging/LICENSE b/vendor/github.com/mageddo/go-logging/LICENSE deleted file mode 100644 index f1f6cfcef..000000000 --- a/vendor/github.com/mageddo/go-logging/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 Örjan Persson. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/mageddo/go-logging/README.md b/vendor/github.com/mageddo/go-logging/README.md index 0a7326b05..4595cb918 100644 --- a/vendor/github.com/mageddo/go-logging/README.md +++ b/vendor/github.com/mageddo/go-logging/README.md @@ -1,93 +1,31 @@ -## Golang logging library +A really simple and fast logger implementation independent -[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/op/go-logging) [![build](https://img.shields.io/travis/op/go-logging.svg?style=flat)](https://travis-ci.org/op/go-logging) +Compability -Package logging implements a logging infrastructure for Go. Its output format -is customizable and supports different logging backends like syslog, file and -memory. Multiple backends can be utilized with different log levels per backend -and logger. +* Compatible with go 1.9 +* Works with go 1.7 but line numbers will be not accurate -**_NOTE:_** backwards compatibility promise have been dropped for master. Please -vendor this package or use `gopkg.in/op/go-logging.v1` for previous version. See -[changelog](CHANGELOG.md) for details. - -## Example - -Let's have a look at an [example](examples/example.go) which demonstrates most -of the features found in this library. - -[![Example Output](examples/example.png)](examples/example.go) +Example ```go -package main - -import ( - "os" - - "github.com/op/go-logging" -) - -var log = logging.MustGetLogger("example") - -// Example format string. Everything except the message has a custom color -// which is dependent on the log level. Many fields have a custom output -// formatting too, eg. the time returns the hour down to the milli second. -var format = logging.MustStringFormatter( - `%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`, -) - -// Password is just an example type implementing the Redactor interface. Any -// time this is logged, the Redacted() function will be called. -type Password string - -func (p Password) Redacted() interface{} { - return logging.Redact(string(p)) -} - -func main() { - // For demo purposes, create two backend for os.Stderr. - backend1 := logging.NewLogBackend(os.Stderr, "", 0) - backend2 := logging.NewLogBackend(os.Stderr, "", 0) - - // For messages written to backend2 we want to add some additional - // information to the output, including the used log level and the name of - // the function. - backend2Formatter := logging.NewBackendFormatter(backend2, format) - - // Only errors and more severe messages should be sent to backend1 - backend1Leveled := logging.AddModuleLevel(backend1) - backend1Leveled.SetLevel(logging.ERROR, "") - - // Set the backends to be used. - logging.SetBackend(backend1Leveled, backend2Formatter) - - log.Debugf("debug %s", Password("secret")) - log.Info("info") - log.Notice("notice") - log.Warning("warning") - log.Error("err") - log.Critical("crit") -} +import "github.com/mageddo/go-logging" +... +logging.Debugf("hey %s", "Mark") +logging.Infof("hey %s", "Mark") +logging.Warnf("hey %s", "Mark") +logging.Errorf("hey %s", "Mark") ``` -## Installing - -### Using *go get* - - $ go get github.com/op/go-logging - -After this command *go-logging* is ready to use. Its source will be in: - - $GOPATH/src/pkg/github.com/op/go-logging - -You can use `go get -u` to update the package. - -## Documentation - -For docs, see http://godoc.org/github.com/op/go-logging or run: - - $ godoc github.com/op/go-logging +Out +``` +2018/05/05 22:36:27 DEBUG f=main.go:8 pkg=main m=main hey Mark +2018/05/05 22:36:27 INFO f=main.go:9 pkg=main m=main hey Mark +2018/05/05 22:36:27 WARNING f=main.go:10 pkg=main m=main hey Mark +2018/05/05 22:36:27 ERROR f=main.go:12 pkg=main m=main hey Mark +``` -## Additional resources +Testing it -* [wslog](https://godoc.org/github.com/cryptix/exp/wslog) -- exposes log messages through a WebSocket. +``` +docker-compose up --abort-on-container-exit ci-build-test +``` \ No newline at end of file diff --git a/vendor/github.com/mageddo/go-logging/backend.go b/vendor/github.com/mageddo/go-logging/backend.go deleted file mode 100644 index 74d920108..000000000 --- a/vendor/github.com/mageddo/go-logging/backend.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -// defaultBackend is the backend used for all logging calls. -var defaultBackend LeveledBackend - -// Backend is the interface which a log backend need to implement to be able to -// be used as a logging backend. -type Backend interface { - Log(Level, int, *Record) error -} - -// SetBackend replaces the backend currently set with the given new logging -// backend. -func SetBackend(backends ...Backend) LeveledBackend { - var backend Backend - if len(backends) == 1 { - backend = backends[0] - } else { - backend = MultiLogger(backends...) - } - - defaultBackend = AddModuleLevel(backend) - return defaultBackend -} - -// SetLevel sets the logging level for the specified module. The module -// corresponds to the string specified in GetLogger. -func SetLevel(level Level, module string) { - defaultBackend.SetLevel(level, module) -} - -// GetLevel returns the logging level for the specified module. -func GetLevel(module string) Level { - return defaultBackend.GetLevel(module) -} diff --git a/vendor/github.com/mageddo/go-logging/contextlogger.go b/vendor/github.com/mageddo/go-logging/contextlogger.go deleted file mode 100644 index 2103b1336..000000000 --- a/vendor/github.com/mageddo/go-logging/contextlogger.go +++ /dev/null @@ -1,144 +0,0 @@ -package logging - -import ( - "context" - "sync/atomic" - "os" - "fmt" - "strings" - "bytes" -) - -type ContextLogger struct { - logger Log - ctx context.Context - id uint64 -} - -func (l *ContextLogger) Critical(args ...interface{}) { - l.logger.Critical(getArgs(l, args...)...) -} -func (l *ContextLogger) Criticalf(format string, args ...interface{}) { - l.logger.Criticalf(getIdConcat(l, format, -1), args...) -} -func (l *ContextLogger) Debug(args ...interface{}) { - l.logger.Debug(getArgs(l, args...)...) -} -func (l *ContextLogger) Debugf(format string, args ...interface{}) { - l.logger.Debugf(getIdConcat(l, format, -1), args...) -} -func (l *ContextLogger) Error(args ...interface{}) { - l.logger.Error(getArgs(l, args...)...) -} -func (l *ContextLogger) Errorf(format string, args ...interface{}) { - l.logger.Errorf(getIdConcat(l, format, -1), args...) -} -func (l *ContextLogger) Fatal(args ...interface{}) { - l.logger.Fatal(getArgs(l, args...)...) - os.Exit(1) -} -func (l *ContextLogger) Fatalf(format string, args ...interface{}) { - l.logger.Fatalf(getIdConcat(l, format, -1), args...) - os.Exit(1) -} -func (l *ContextLogger) Info(args ...interface{}) { - l.logger.Info(getArgs(l, args...)...) -} -func (l *ContextLogger) Infof(format string, args ...interface{}) { - l.logger.Infof(getIdConcat(l, format, -1), args...) - -} - -func (l *ContextLogger) Notice(args ...interface{}) { - l.logger.Notice(getArgs(l, args...)...) -} -func (l *ContextLogger) Noticef(format string, args ...interface{}) { - l.logger.Noticef(getIdConcat(l, format, -1), args...) -} -func (l *ContextLogger) Panic(args ...interface{}) { - l.logger.Panic(args) - panic(fmt.Sprint(args...)) -} -func (l *ContextLogger) Panicf(format string, args ...interface{}) { - l.logger.Panicf(getIdConcat(l, format, -1), args...) - panic(fmt.Sprintf(format, args...)) -} - -func (l *ContextLogger) Warning(args ...interface{}) { - l.logger.Warning(getArgs(l, args...)...) -} -func (l *ContextLogger) Warningf(format string, args ...interface{}) { - l.logger.Warningf(getIdConcat(l, format, -1), args...) -} - - -func getArgs(l *ContextLogger, args ...interface{}) []interface{} { - var ar []interface{} - ar = append(ar, strings.Trim(getId(l), " ")) - ar = append(ar, args...) - return ar; -} - -func getId(l *ContextLogger) string { - return getIdConcat(l, "", 4) -} - -func getIdConcat(l *ContextLogger, append string, level int ) string { - if level == -1{ - level = 2 - } - var buffer bytes.Buffer - buffer.WriteString("id=") - buffer.WriteString(fmt.Sprintf("%d, ", l.id)) - buffer.WriteString("m=") - buffer.WriteString(GetCallerFunctionNameSkippingAnnonymous(level)) - buffer.WriteString(" ") - buffer.WriteString(append) - return buffer.String() -} - -var logger Log; -var instanced int32 = 0 -func NewLog(ctx context.Context) Log { - if(atomic.CompareAndSwapInt32(&instanced, 0, 1)){ - logger = MustGetLogger("main") - } - return NewLogWithContext(ctx, logger) -} -func NewLogWithLogger(logger Log) Log { - - ctx := NewContext() - var ctxLogger ContextLogger - if id := ctx.Value(idKey); id != nil { - ctxLogger = ContextLogger{logger, ctx, id.(uint64)} - } else { - ctxContext := ContextWithId(ctx) - ctxLogger = ContextLogger{logger, ctxContext, ctxContext.Value(id).(uint64)} - } - return &ctxLogger -} - -func NewLogWithContext(ctx context.Context, logger Log) Log { - - var ctxLogger ContextLogger - if id := ctx.Value(idKey); id != nil { - ctxLogger = ContextLogger{logger, ctx, id.(uint64)} - } else { - ctxContext := ContextWithId(ctx) - ctxLogger = ContextLogger{logger, ctxContext, ctxContext.Value(id).(uint64)} - } - return &ctxLogger -} - -const idKey = "ctx_id" -var id uint64 = 0; -func NewContext() context.Context { - return ContextWithId(context.Background()) -} - -func ContextWithId(parent context.Context) context.Context { - newId := atomic.AddUint64(&id, 1) - ctx := context.WithValue(parent, idKey, newId) - return ctx -} - diff --git a/vendor/github.com/mageddo/go-logging/docker-compose.yml b/vendor/github.com/mageddo/go-logging/docker-compose.yml new file mode 100644 index 000000000..ccd284c92 --- /dev/null +++ b/vendor/github.com/mageddo/go-logging/docker-compose.yml @@ -0,0 +1,13 @@ +version: '2' +services: + go-logging: + container_name: go-logging + image: golang:1.9 + volumes: + - $PWD:/go/src/github.com/mageddo/go-logging + working_dir: /go/src/github.com/mageddo/go-logging + command: tail -f /dev/null + ci-build-test: + extends: go-logging + container_name: ci-build-test + command: go test -v -run . -bench . github.com/mageddo/go-logging/... diff --git a/vendor/github.com/mageddo/go-logging/format.go b/vendor/github.com/mageddo/go-logging/format.go deleted file mode 100644 index 7160674a8..000000000 --- a/vendor/github.com/mageddo/go-logging/format.go +++ /dev/null @@ -1,414 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "path" - "path/filepath" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -// TODO see Formatter interface in fmt/print.go -// TODO try text/template, maybe it have enough performance -// TODO other template systems? -// TODO make it possible to specify formats per backend? -type fmtVerb int - -const ( - fmtVerbTime fmtVerb = iota - fmtVerbLevel - fmtVerbID - fmtVerbPid - fmtVerbProgram - fmtVerbModule - fmtVerbMessage - fmtVerbLongfile - fmtVerbShortfile - fmtVerbLongpkg - fmtVerbShortpkg - fmtVerbLongfunc - fmtVerbShortfunc - fmtVerbCallpath - fmtVerbLevelColor - - // Keep last, there are no match for these below. - fmtVerbUnknown - fmtVerbStatic -) - -var fmtVerbs = []string{ - "time", - "level", - "id", - "pid", - "program", - "module", - "message", - "longfile", - "shortfile", - "longpkg", - "shortpkg", - "longfunc", - "shortfunc", - "callpath", - "color", -} - -const rfc3339Milli = "2006-01-02T15:04:05.999Z07:00" - -var defaultVerbsLayout = []string{ - rfc3339Milli, - "s", - "d", - "d", - "s", - "s", - "s", - "s", - "s", - "s", - "s", - "s", - "s", - "0", - "", -} - -var ( - pid = os.Getpid() - program = filepath.Base(os.Args[0]) -) - -func getFmtVerbByName(name string) fmtVerb { - for i, verb := range fmtVerbs { - if name == verb { - return fmtVerb(i) - } - } - return fmtVerbUnknown -} - -// Formatter is the required interface for a custom log record formatter. -type Formatter interface { - Format(calldepth int, r *Record, w io.Writer) error -} - -// formatter is used by all backends unless otherwise overriden. -var formatter struct { - sync.RWMutex - def Formatter -} - -func getFormatter() Formatter { - formatter.RLock() - defer formatter.RUnlock() - return formatter.def -} - -var ( - // DefaultFormatter is the default formatter used and is only the message. - DefaultFormatter = MustStringFormatter("%{message}") - - // GlogFormatter mimics the glog format - GlogFormatter = MustStringFormatter("%{level:.1s}%{time:0102 15:04:05.999999} %{pid} %{shortfile}] %{message}") -) - -// SetFormatter sets the default formatter for all new backends. A backend will -// fetch this value once it is needed to format a record. Note that backends -// will cache the formatter after the first point. For now, make sure to set -// the formatter before logging. -func SetFormatter(f Formatter) { - formatter.Lock() - defer formatter.Unlock() - formatter.def = f -} - -var formatRe = regexp.MustCompile(`%{([a-z]+)(?::(.*?[^\\]))?}`) - -type part struct { - verb fmtVerb - layout string -} - -// stringFormatter contains a list of parts which explains how to build the -// formatted string passed on to the logging backend. -type stringFormatter struct { - parts []part -} - -// NewStringFormatter returns a new Formatter which outputs the log record as a -// string based on the 'verbs' specified in the format string. -// -// The verbs: -// -// General: -// %{id} Sequence number for log message (uint64). -// %{pid} Process id (int) -// %{time} Time when log occurred (time.Time) -// %{level} Log level (Level) -// %{module} Module (string) -// %{program} Basename of os.Args[0] (string) -// %{message} Message (string) -// %{longfile} Full file name and line number: /a/b/c/d.go:23 -// %{shortfile} Final file name element and line number: d.go:23 -// %{callpath} Callpath like main.a.b.c...c "..." meaning recursive call ~. meaning truncated path -// %{color} ANSI color based on log level -// -// For normal types, the output can be customized by using the 'verbs' defined -// in the fmt package, eg. '%{id:04d}' to make the id output be '%04d' as the -// format string. -// -// For time.Time, use the same layout as time.Format to change the time format -// when output, eg "2006-01-02T15:04:05.999Z-07:00". -// -// For the 'color' verb, the output can be adjusted to either use bold colors, -// i.e., '%{color:bold}' or to reset the ANSI attributes, i.e., -// '%{color:reset}' Note that if you use the color verb explicitly, be sure to -// reset it or else the color state will persist past your log message. e.g., -// "%{color:bold}%{time:15:04:05} %{level:-8s}%{color:reset} %{message}" will -// just colorize the time and level, leaving the message uncolored. -// -// For the 'callpath' verb, the output can be adjusted to limit the printing -// the stack depth. i.e. '%{callpath:3}' will print '~.a.b.c' -// -// Colors on Windows is unfortunately not supported right now and is currently -// a no-op. -// -// There's also a couple of experimental 'verbs'. These are exposed to get -// feedback and needs a bit of tinkering. Hence, they might change in the -// future. -// -// Experimental: -// %{longpkg} Full package path, eg. github.com/go-logging -// %{shortpkg} Base package path, eg. go-logging -// %{longfunc} Full function name, eg. littleEndian.PutUint32 -// %{shortfunc} Base function name, eg. PutUint32 -// %{callpath} Call function path, eg. main.a.b.c -func NewStringFormatter(format string) (Formatter, error) { - var fmter = &stringFormatter{} - - // Find the boundaries of all %{vars} - matches := formatRe.FindAllStringSubmatchIndex(format, -1) - if matches == nil { - return nil, errors.New("logger: invalid log format: " + format) - } - - // Collect all variables and static text for the format - prev := 0 - for _, m := range matches { - start, end := m[0], m[1] - if start > prev { - fmter.add(fmtVerbStatic, format[prev:start]) - } - - name := format[m[2]:m[3]] - verb := getFmtVerbByName(name) - if verb == fmtVerbUnknown { - return nil, errors.New("logger: unknown variable: " + name) - } - - // Handle layout customizations or use the default. If this is not for the - // time, color formatting or callpath, we need to prefix with %. - layout := defaultVerbsLayout[verb] - if m[4] != -1 { - layout = format[m[4]:m[5]] - } - if verb != fmtVerbTime && verb != fmtVerbLevelColor && verb != fmtVerbCallpath { - layout = "%" + layout - } - - fmter.add(verb, layout) - prev = end - } - end := format[prev:] - if end != "" { - fmter.add(fmtVerbStatic, end) - } - - // Make a test run to make sure we can format it correctly. - t, err := time.Parse(time.RFC3339, "2010-02-04T21:00:57-08:00") - if err != nil { - panic(err) - } - testFmt := "hello %s" - r := &Record{ - ID: 12345, - Time: t, - Module: "logger", - Args: []interface{}{"go"}, - fmt: &testFmt, - } - if err := fmter.Format(0, r, &bytes.Buffer{}); err != nil { - return nil, err - } - - return fmter, nil -} - -// MustStringFormatter is equivalent to NewStringFormatter with a call to panic -// on error. -func MustStringFormatter(format string) Formatter { - f, err := NewStringFormatter(format) - if err != nil { - panic("Failed to initialized string formatter: " + err.Error()) - } - return f -} - -func (f *stringFormatter) add(verb fmtVerb, layout string) { - f.parts = append(f.parts, part{verb, layout}) -} - -func (f *stringFormatter) Format(calldepth int, r *Record, output io.Writer) error { - for _, part := range f.parts { - if part.verb == fmtVerbStatic { - output.Write([]byte(part.layout)) - } else if part.verb == fmtVerbTime { - output.Write([]byte(r.Time.Format(part.layout))) - } else if part.verb == fmtVerbLevelColor { - doFmtVerbLevelColor(part.layout, r.Level, output) - } else if part.verb == fmtVerbCallpath { - depth, err := strconv.Atoi(part.layout) - if err != nil { - depth = 0 - } - output.Write([]byte(formatCallpath(calldepth+1, depth))) - } else { - var v interface{} - switch part.verb { - case fmtVerbLevel: - v = r.Level - break - case fmtVerbID: - v = r.ID - break - case fmtVerbPid: - v = pid - break - case fmtVerbProgram: - v = program - break - case fmtVerbModule: - v = r.Module - break - case fmtVerbMessage: - v = r.Message() - break - case fmtVerbLongfile, fmtVerbShortfile: - _, file, line, ok := runtime.Caller(calldepth + 1) - if !ok { - file = "???" - line = 0 - } else if part.verb == fmtVerbShortfile { - file = filepath.Base(file) - } - v = fmt.Sprintf("%s:%d", file, line) - case fmtVerbLongfunc, fmtVerbShortfunc, - fmtVerbLongpkg, fmtVerbShortpkg: - // TODO cache pc - v = "???" - if pc, _, _, ok := runtime.Caller(calldepth + 1); ok { - if f := runtime.FuncForPC(pc); f != nil { - v = formatFuncName(part.verb, f.Name()) - } - } - default: - panic("unhandled format part") - } - fmt.Fprintf(output, part.layout, v) - } - } - return nil -} - -// formatFuncName tries to extract certain part of the runtime formatted -// function name to some pre-defined variation. -// -// This function is known to not work properly if the package path or name -// contains a dot. -func formatFuncName(v fmtVerb, f string) string { - i := strings.LastIndex(f, "/") - j := strings.Index(f[i+1:], ".") - if j < 1 { - return "???" - } - pkg, fun := f[:i+j+1], f[i+j+2:] - switch v { - case fmtVerbLongpkg: - return pkg - case fmtVerbShortpkg: - return path.Base(pkg) - case fmtVerbLongfunc: - return fun - case fmtVerbShortfunc: - i = strings.LastIndex(fun, ".") - return fun[i+1:] - } - panic("unexpected func formatter") -} - -func formatCallpath(calldepth int, depth int) string { - v := "" - callers := make([]uintptr, 64) - n := runtime.Callers(calldepth+2, callers) - oldPc := callers[n-1] - - start := n - 3 - if depth > 0 && start >= depth { - start = depth - 1 - v += "~." - } - recursiveCall := false - for i := start; i >= 0; i-- { - pc := callers[i] - if oldPc == pc { - recursiveCall = true - continue - } - oldPc = pc - if recursiveCall { - recursiveCall = false - v += ".." - } - if i < start { - v += "." - } - if f := runtime.FuncForPC(pc); f != nil { - v += formatFuncName(fmtVerbShortfunc, f.Name()) - } - } - return v -} - -// backendFormatter combines a backend with a specific formatter making it -// possible to have different log formats for different backends. -type backendFormatter struct { - b Backend - f Formatter -} - -// NewBackendFormatter creates a new backend which makes all records that -// passes through it beeing formatted by the specific formatter. -func NewBackendFormatter(b Backend, f Formatter) Backend { - return &backendFormatter{b, f} -} - -// Log implements the Log function required by the Backend interface. -func (bf *backendFormatter) Log(level Level, calldepth int, r *Record) error { - // Make a shallow copy of the record and replace any formatter - r2 := *r - r2.formatter = bf.f - return bf.b.Log(level, calldepth+1, &r2) -} diff --git a/vendor/github.com/mageddo/go-logging/level.go b/vendor/github.com/mageddo/go-logging/level.go deleted file mode 100644 index 98dd19187..000000000 --- a/vendor/github.com/mageddo/go-logging/level.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -import ( - "errors" - "strings" - "sync" -) - -// ErrInvalidLogLevel is used when an invalid log level has been used. -var ErrInvalidLogLevel = errors.New("logger: invalid log level") - -// Level defines all available log levels for log messages. -type Level int - -// Log levels. -const ( - CRITICAL Level = iota - ERROR - WARNING - NOTICE - INFO - DEBUG -) - -var levelNames = []string{ - "CRITICAL", - "ERROR", - "WARNING", - "NOTICE", - "INFO", - "DEBUG", -} - -// String returns the string representation of a logging level. -func (p Level) String() string { - return levelNames[p] -} - -// LogLevel returns the log level from a string representation. -func LogLevel(level string) (Level, error) { - for i, name := range levelNames { - if strings.EqualFold(name, level) { - return Level(i), nil - } - } - return ERROR, ErrInvalidLogLevel -} - -// Leveled interface is the interface required to be able to add leveled -// logging. -type Leveled interface { - GetLevel(string) Level - SetLevel(Level, string) - IsEnabledFor(Level, string) bool -} - -// LeveledBackend is a log backend with additional knobs for setting levels on -// individual modules to different levels. -type LeveledBackend interface { - Backend - Leveled -} - -type moduleLeveled struct { - levels map[string]Level - backend Backend - formatter Formatter - once sync.Once -} - -// AddModuleLevel wraps a log backend with knobs to have different log levels -// for different modules. -func AddModuleLevel(backend Backend) LeveledBackend { - var leveled LeveledBackend - var ok bool - if leveled, ok = backend.(LeveledBackend); !ok { - leveled = &moduleLeveled{ - levels: make(map[string]Level), - backend: backend, - } - } - return leveled -} - -// GetLevel returns the log level for the given module. -func (l *moduleLeveled) GetLevel(module string) Level { - level, exists := l.levels[module] - if exists == false { - level, exists = l.levels[""] - // no configuration exists, default to debug - if exists == false { - level = DEBUG - } - } - return level -} - -// SetLevel sets the log level for the given module. -func (l *moduleLeveled) SetLevel(level Level, module string) { - l.levels[module] = level -} - -// IsEnabledFor will return true if logging is enabled for the given module. -func (l *moduleLeveled) IsEnabledFor(level Level, module string) bool { - return level <= l.GetLevel(module) -} - -func (l *moduleLeveled) Log(level Level, calldepth int, rec *Record) (err error) { - if l.IsEnabledFor(level, rec.Module) { - // TODO get rid of traces of formatter here. BackendFormatter should be used. - rec.formatter = l.getFormatterAndCacheCurrent() - err = l.backend.Log(level, calldepth+1, rec) - } - return -} - -func (l *moduleLeveled) getFormatterAndCacheCurrent() Formatter { - l.once.Do(func() { - if l.formatter == nil { - l.formatter = getFormatter() - } - }) - return l.formatter -} diff --git a/vendor/github.com/mageddo/go-logging/log_nix.go b/vendor/github.com/mageddo/go-logging/log_nix.go deleted file mode 100644 index 4ff2ab1ab..000000000 --- a/vendor/github.com/mageddo/go-logging/log_nix.go +++ /dev/null @@ -1,109 +0,0 @@ -// +build !windows - -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -import ( - "bytes" - "fmt" - "io" - "log" -) - -type color int - -const ( - ColorBlack = iota + 30 - ColorRed - ColorGreen - ColorYellow - ColorBlue - ColorMagenta - ColorCyan - ColorWhite -) - -var ( - colors = []string{ - CRITICAL: ColorSeq(ColorMagenta), - ERROR: ColorSeq(ColorRed), - WARNING: ColorSeq(ColorYellow), - NOTICE: ColorSeq(ColorGreen), - DEBUG: ColorSeq(ColorCyan), - } - boldcolors = []string{ - CRITICAL: ColorSeqBold(ColorMagenta), - ERROR: ColorSeqBold(ColorRed), - WARNING: ColorSeqBold(ColorYellow), - NOTICE: ColorSeqBold(ColorGreen), - DEBUG: ColorSeqBold(ColorCyan), - } -) - -// LogBackend utilizes the standard log module. -type LogBackend struct { - Logger *log.Logger - Color bool - ColorConfig []string -} - -// NewLogBackend creates a new LogBackend. -func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend { - return &LogBackend{Logger: log.New(out, prefix, flag)} -} - -// Log implements the Backend interface. -func (b *LogBackend) Log(level Level, calldepth int, rec *Record) error { - if b.Color { - col := colors[level] - if len(b.ColorConfig) > int(level) && b.ColorConfig[level] != "" { - col = b.ColorConfig[level] - } - - buf := &bytes.Buffer{} - buf.Write([]byte(col)) - buf.Write([]byte(rec.Formatted(calldepth + 1))) - buf.Write([]byte("\033[0m")) - // For some reason, the Go logger arbitrarily decided "2" was the correct - // call depth... - return b.Logger.Output(calldepth+2, buf.String()) - } - - return b.Logger.Output(calldepth+2, rec.Formatted(calldepth+1)) -} - -// ConvertColors takes a list of ints representing colors for log levels and -// converts them into strings for ANSI color formatting -func ConvertColors(colors []int, bold bool) []string { - converted := []string{} - for _, i := range colors { - if bold { - converted = append(converted, ColorSeqBold(color(i))) - } else { - converted = append(converted, ColorSeq(color(i))) - } - } - - return converted -} - -func ColorSeq(color color) string { - return fmt.Sprintf("\033[%dm", int(color)) -} - -func ColorSeqBold(color color) string { - return fmt.Sprintf("\033[%d;1m", int(color)) -} - -func doFmtVerbLevelColor(layout string, level Level, output io.Writer) { - if layout == "bold" { - output.Write([]byte(boldcolors[level])) - } else if layout == "reset" { - output.Write([]byte("\033[0m")) - } else { - output.Write([]byte(colors[level])) - } -} diff --git a/vendor/github.com/mageddo/go-logging/log_windows.go b/vendor/github.com/mageddo/go-logging/log_windows.go deleted file mode 100644 index b8dc92c67..000000000 --- a/vendor/github.com/mageddo/go-logging/log_windows.go +++ /dev/null @@ -1,107 +0,0 @@ -// +build windows -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -import ( - "bytes" - "io" - "log" - "syscall" -) - -var ( - kernel32DLL = syscall.NewLazyDLL("kernel32.dll") - setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") -) - -// Character attributes -// Note: -// -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). -// Clearing all foreground or background colors results in black; setting all creates white. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. -const ( - fgBlack = 0x0000 - fgBlue = 0x0001 - fgGreen = 0x0002 - fgCyan = 0x0003 - fgRed = 0x0004 - fgMagenta = 0x0005 - fgYellow = 0x0006 - fgWhite = 0x0007 - fgIntensity = 0x0008 - fgMask = 0x000F -) - -var ( - colors = []uint16{ - INFO: fgWhite, - CRITICAL: fgMagenta, - ERROR: fgRed, - WARNING: fgYellow, - NOTICE: fgGreen, - DEBUG: fgCyan, - } - boldcolors = []uint16{ - INFO: fgWhite | fgIntensity, - CRITICAL: fgMagenta | fgIntensity, - ERROR: fgRed | fgIntensity, - WARNING: fgYellow | fgIntensity, - NOTICE: fgGreen | fgIntensity, - DEBUG: fgCyan | fgIntensity, - } -) - -type file interface { - Fd() uintptr -} - -// LogBackend utilizes the standard log module. -type LogBackend struct { - Logger *log.Logger - Color bool - - // f is set to a non-nil value if the underlying writer which logs writes to - // implements the file interface. This makes us able to colorise the output. - f file -} - -// NewLogBackend creates a new LogBackend. -func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend { - b := &LogBackend{Logger: log.New(out, prefix, flag)} - - // Unfortunately, the API used only takes an io.Writer where the Windows API - // need the actual fd to change colors. - if f, ok := out.(file); ok { - b.f = f - } - - return b -} - -func (b *LogBackend) Log(level Level, calldepth int, rec *Record) error { - if b.Color && b.f != nil { - buf := &bytes.Buffer{} - setConsoleTextAttribute(b.f, colors[level]) - buf.Write([]byte(rec.Formatted(calldepth + 1))) - err := b.Logger.Output(calldepth+2, buf.String()) - setConsoleTextAttribute(b.f, fgWhite) - return err - } - return b.Logger.Output(calldepth+2, rec.Formatted(calldepth+1)) -} - -// setConsoleTextAttribute sets the attributes of characters written to the -// console screen buffer by the WriteFile or WriteConsole function. -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. -func setConsoleTextAttribute(f file, attribute uint16) bool { - ok, _, _ := setConsoleTextAttributeProc.Call(f.Fd(), uintptr(attribute), 0) - return ok != 0 -} - -func doFmtVerbLevelColor(layout string, level Level, output io.Writer) { - // TODO not supported on Windows since the io.Writer here is actually a - // bytes.Buffer. -} diff --git a/vendor/github.com/mageddo/go-logging/logger.go b/vendor/github.com/mageddo/go-logging/logger.go deleted file mode 100644 index 5428623e4..000000000 --- a/vendor/github.com/mageddo/go-logging/logger.go +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package logging implements a logging infrastructure for Go. It supports -// different logging backends like syslog, file and memory. Multiple backends -// can be utilized with different log levels per backend and logger. -package logging - -import ( - "bytes" - "fmt" - "log" - "os" - "strings" - "sync/atomic" - "time" -) - -// Redactor is an interface for types that may contain sensitive information -// (like passwords), which shouldn't be printed to the log. The idea was found -// in relog as part of the vitness project. -type Redactor interface { - Redacted() interface{} -} - -// Redact returns a string of * having the same length as s. -func Redact(s string) string { - return strings.Repeat("*", len(s)) -} - -var ( - // Sequence number is incremented and utilized for all log records created. - sequenceNo uint64 - - // timeNow is a customizable for testing purposes. - timeNow = time.Now -) - -// Record represents a log record and contains the timestamp when the record -// was created, an increasing id, filename and line and finally the actual -// formatted log line. -type Record struct { - ID uint64 - Time time.Time - Module string - Level Level - Args []interface{} - - // message is kept as a pointer to have shallow copies update this once - // needed. - message *string - fmt *string - formatter Formatter - formatted string -} - -// Formatted returns the formatted log record string. -func (r *Record) Formatted(calldepth int) string { - if r.formatted == "" { - var buf bytes.Buffer - r.formatter.Format(calldepth+1, r, &buf) - r.formatted = buf.String() - } - return r.formatted -} - -// Message returns the log record message. -func (r *Record) Message() string { - if r.message == nil { - // Redact the arguments that implements the Redactor interface - for i, arg := range r.Args { - if redactor, ok := arg.(Redactor); ok == true { - r.Args[i] = redactor.Redacted() - } - } - var buf bytes.Buffer - if r.fmt != nil { - fmt.Fprintf(&buf, *r.fmt, r.Args...) - } else { - // use Fprintln to make sure we always get space between arguments - fmt.Fprintln(&buf, r.Args...) - buf.Truncate(buf.Len() - 1) // strip newline - } - msg := buf.String() - r.message = &msg - } - return *r.message -} - - -type Log interface { - Critical(args ...interface{}) - Criticalf(format string, args ...interface{}) - Debug(args ...interface{}) - Debugf(format string, args ...interface{}) - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Info(args ...interface{}) - Infof(format string, args ...interface{}) - Notice(args ...interface{}) - Noticef(format string, args ...interface{}) - Panic(args ...interface{}) - Panicf(format string, args ...interface{}) - Warning(args ...interface{}) - Warningf(format string, args ...interface{}) -} - -// Logger is the actual logger which creates log records based on the functions -// called and passes them to the underlying logging backend. -type Logger struct { - Module string - backend LeveledBackend - haveBackend bool - - // ExtraCallDepth can be used to add additional call depth when getting the - // calling function. This is normally used when wrapping a logger. - ExtraCalldepth int -} - -// SetBackend overrides any previously defined backend for this logger. -func (l *Logger) SetBackend(backend LeveledBackend) { - l.backend = backend - l.haveBackend = true -} - -// TODO call NewLogger and remove MustGetLogger? - -// GetLogger creates and returns a Logger object based on the module name. -func GetLogger(module string) (*Logger, error) { - return &Logger{Module: module}, nil -} - -// MustGetLogger is like GetLogger but panics if the logger can't be created. -// It simplifies safe initialization of a global logger for eg. a package. -func MustGetLogger(module string) *Logger { - logger, err := GetLogger(module) - if err != nil { - panic("logger: " + module + ": " + err.Error()) - } - return logger -} - -// Reset restores the internal state of the logging library. -func Reset() { - // TODO make a global Init() method to be less magic? or make it such that - // if there's no backends at all configured, we could use some tricks to - // automatically setup backends based if we have a TTY or not. - sequenceNo = 0 - b := SetBackend(NewLogBackend(os.Stderr, "", log.LstdFlags)) - b.SetLevel(DEBUG, "") - SetFormatter(DefaultFormatter) - timeNow = time.Now -} - -// IsEnabledFor returns true if the logger is enabled for the given level. -func (l *Logger) IsEnabledFor(level Level) bool { - return defaultBackend.IsEnabledFor(level, l.Module) -} - -func (l *Logger) log(lvl Level, format *string, args ...interface{}) { - if !l.IsEnabledFor(lvl) { - return - } - - // Create the logging record and pass it in to the backend - record := &Record{ - ID: atomic.AddUint64(&sequenceNo, 1), - Time: timeNow(), - Module: l.Module, - Level: lvl, - fmt: format, - Args: args, - } - - // TODO use channels to fan out the records to all backends? - // TODO in case of errors, do something (tricky) - - // calldepth=2 brings the stack up to the caller of the level - // methods, Info(), Fatal(), etc. - // ExtraCallDepth allows this to be extended further up the stack in case we - // are wrapping these methods, eg. to expose them package level - if l.haveBackend { - l.backend.Log(lvl, 2+l.ExtraCalldepth, record) - return - } - - defaultBackend.Log(lvl, 2+l.ExtraCalldepth, record) -} - -// Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1). -func (l *Logger) Fatal(args ...interface{}) { - l.log(CRITICAL, nil, args...) - os.Exit(1) -} - -// Fatalf is equivalent to l.Critical followed by a call to os.Exit(1). -func (l *Logger) Fatalf(format string, args ...interface{}) { - l.log(CRITICAL, &format, args...) - os.Exit(1) -} - -// Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic(). -func (l *Logger) Panic(args ...interface{}) { - l.log(CRITICAL, nil, args...) - panic(fmt.Sprint(args...)) -} - -// Panicf is equivalent to l.Critical followed by a call to panic(). -func (l *Logger) Panicf(format string, args ...interface{}) { - l.log(CRITICAL, &format, args...) - panic(fmt.Sprintf(format, args...)) -} - -// Critical logs a message using CRITICAL as log level. -func (l *Logger) Critical(args ...interface{}) { - l.log(CRITICAL, nil, args...) -} - -// Criticalf logs a message using CRITICAL as log level. -func (l *Logger) Criticalf(format string, args ...interface{}) { - l.log(CRITICAL, &format, args...) -} - -// Error logs a message using ERROR as log level. -func (l *Logger) Error(args ...interface{}) { - l.log(ERROR, nil, args...) -} - -// Errorf logs a message using ERROR as log level. -func (l *Logger) Errorf(format string, args ...interface{}) { - l.log(ERROR, &format, args...) -} - -// Warning logs a message using WARNING as log level. -func (l *Logger) Warning(args ...interface{}) { - l.log(WARNING, nil, args...) -} - -// Warningf logs a message using WARNING as log level. -func (l *Logger) Warningf(format string, args ...interface{}) { - l.log(WARNING, &format, args...) -} - -// Notice logs a message using NOTICE as log level. -func (l *Logger) Notice(args ...interface{}) { - l.log(NOTICE, nil, args...) -} - -// Noticef logs a message using NOTICE as log level. -func (l *Logger) Noticef(format string, args ...interface{}) { - l.log(NOTICE, &format, args...) -} - -// Info logs a message using INFO as log level. -func (l *Logger) Info(args ...interface{}) { - l.log(INFO, nil, args...) -} - -// Infof logs a message using INFO as log level. -func (l *Logger) Infof(format string, args ...interface{}) { - l.log(INFO, &format, args...) -} - -// Debug logs a message using DEBUG as log level. -func (l *Logger) Debug(args ...interface{}) { - l.log(DEBUG, nil, args...) -} - -// Debugf logs a message using DEBUG as log level. -func (l *Logger) Debugf(format string, args ...interface{}) { - l.log(DEBUG, &format, args...) -} - -func init() { - Reset() -} diff --git a/vendor/github.com/mageddo/go-logging/logging.go b/vendor/github.com/mageddo/go-logging/logging.go new file mode 100644 index 000000000..c52e9c860 --- /dev/null +++ b/vendor/github.com/mageddo/go-logging/logging.go @@ -0,0 +1,89 @@ +package logging + +// +// Who write the logs to output +// +import ( + "os" + "log" + "io" + "github.com/mageddo/go-logging/native" +) + +type Printer interface { + Printf(format string, args ...interface{}) + Println(args ...interface{}) + SetOutput(w io.Writer) +} + +// +// The package logger interface, you can create as many impl as you want +// +type Log interface { + + Debug(args ...interface{}) + Debugf(format string, args ...interface{}) + + Info(args ...interface{}) + Infof(format string, args ...interface{}) + + Warning(args ...interface{}) + Warningf(format string, args ...interface{}) + + Error(args ...interface{}) + Errorf(format string, args ...interface{}) + + Printer() Printer + +} + +var l Log = New(native.NewGologPrinter(os.Stdout, "", log.LstdFlags), 3) +func Debug(args ...interface{}) { + l.Debug(args...) +} + +func Debugf(format string, args ...interface{}){ + l.Debugf(format, args...) +} + +func Info(args ...interface{}){ + l.Info(args...) +} + +func Infof(format string, args ...interface{}){ + l.Infof(format, args...) +} + +func Warning(args ...interface{}){ + l.Warning(args...) +} + +func Warningf(format string, args ...interface{}) { + l.Warningf(format, args...) +} + +func Error(args ...interface{}){ + l.Error(args...) +} + +func Errorf(format string, args ...interface{}){ + l.Errorf(format, args...) +} + +func SetOutput(w io.Writer) { + l.Printer().SetOutput(w) +} + +// +// Change actual logger +// +func SetLog(logger Log){ + l = logger +} + +// +// Returns current logs +// +func GetLog() Log { + return l +} \ No newline at end of file diff --git a/vendor/github.com/mageddo/go-logging/memory.go b/vendor/github.com/mageddo/go-logging/memory.go deleted file mode 100644 index 8d5152c0b..000000000 --- a/vendor/github.com/mageddo/go-logging/memory.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine - -package logging - -import ( - "sync" - "sync/atomic" - "time" - "unsafe" -) - -// TODO pick one of the memory backends and stick with it or share interface. - -// InitForTesting is a convenient method when using logging in a test. Once -// called, the time will be frozen to January 1, 1970 UTC. -func InitForTesting(level Level) *MemoryBackend { - Reset() - - memoryBackend := NewMemoryBackend(10240) - - leveledBackend := AddModuleLevel(memoryBackend) - leveledBackend.SetLevel(level, "") - SetBackend(leveledBackend) - - timeNow = func() time.Time { - return time.Unix(0, 0).UTC() - } - return memoryBackend -} - -// Node is a record node pointing to an optional next node. -type node struct { - next *node - Record *Record -} - -// Next returns the next record node. If there's no node available, it will -// return nil. -func (n *node) Next() *node { - return n.next -} - -// MemoryBackend is a simple memory based logging backend that will not produce -// any output but merly keep records, up to the given size, in memory. -type MemoryBackend struct { - size int32 - maxSize int32 - head, tail unsafe.Pointer -} - -// NewMemoryBackend creates a simple in-memory logging backend. -func NewMemoryBackend(size int) *MemoryBackend { - return &MemoryBackend{maxSize: int32(size)} -} - -// Log implements the Log method required by Backend. -func (b *MemoryBackend) Log(level Level, calldepth int, rec *Record) error { - var size int32 - - n := &node{Record: rec} - np := unsafe.Pointer(n) - - // Add the record to the tail. If there's no records available, tail and - // head will both be nil. When we successfully set the tail and the previous - // value was nil, it's safe to set the head to the current value too. - for { - tailp := b.tail - swapped := atomic.CompareAndSwapPointer( - &b.tail, - tailp, - np, - ) - if swapped == true { - if tailp == nil { - b.head = np - } else { - (*node)(tailp).next = n - } - size = atomic.AddInt32(&b.size, 1) - break - } - } - - // Since one record was added, we might have overflowed the list. Remove - // a record if that is the case. The size will fluctate a bit, but - // eventual consistent. - if b.maxSize > 0 && size > b.maxSize { - for { - headp := b.head - head := (*node)(b.head) - if head.next == nil { - break - } - swapped := atomic.CompareAndSwapPointer( - &b.head, - headp, - unsafe.Pointer(head.next), - ) - if swapped == true { - atomic.AddInt32(&b.size, -1) - break - } - } - } - return nil -} - -// Head returns the oldest record node kept in memory. It can be used to -// iterate over records, one by one, up to the last record. -// -// Note: new records can get added while iterating. Hence the number of records -// iterated over might be larger than the maximum size. -func (b *MemoryBackend) Head() *node { - return (*node)(b.head) -} - -type event int - -const ( - eventFlush event = iota - eventStop -) - -// ChannelMemoryBackend is very similar to the MemoryBackend, except that it -// internally utilizes a channel. -type ChannelMemoryBackend struct { - maxSize int - size int - incoming chan *Record - events chan event - mu sync.Mutex - running bool - flushWg sync.WaitGroup - stopWg sync.WaitGroup - head, tail *node -} - -// NewChannelMemoryBackend creates a simple in-memory logging backend which -// utilizes a go channel for communication. -// -// Start will automatically be called by this function. -func NewChannelMemoryBackend(size int) *ChannelMemoryBackend { - backend := &ChannelMemoryBackend{ - maxSize: size, - incoming: make(chan *Record, 1024), - events: make(chan event), - } - backend.Start() - return backend -} - -// Start launches the internal goroutine which starts processing data from the -// input channel. -func (b *ChannelMemoryBackend) Start() { - b.mu.Lock() - defer b.mu.Unlock() - - // Launch the goroutine unless it's already running. - if b.running != true { - b.running = true - b.stopWg.Add(1) - go b.process() - } -} - -func (b *ChannelMemoryBackend) process() { - defer b.stopWg.Done() - for { - select { - case rec := <-b.incoming: - b.insertRecord(rec) - case e := <-b.events: - switch e { - case eventStop: - return - case eventFlush: - for len(b.incoming) > 0 { - b.insertRecord(<-b.incoming) - } - b.flushWg.Done() - } - } - } -} - -func (b *ChannelMemoryBackend) insertRecord(rec *Record) { - prev := b.tail - b.tail = &node{Record: rec} - if prev == nil { - b.head = b.tail - } else { - prev.next = b.tail - } - - if b.maxSize > 0 && b.size >= b.maxSize { - b.head = b.head.next - } else { - b.size++ - } -} - -// Flush waits until all records in the buffered channel have been processed. -func (b *ChannelMemoryBackend) Flush() { - b.flushWg.Add(1) - b.events <- eventFlush - b.flushWg.Wait() -} - -// Stop signals the internal goroutine to exit and waits until it have. -func (b *ChannelMemoryBackend) Stop() { - b.mu.Lock() - if b.running == true { - b.running = false - b.events <- eventStop - } - b.mu.Unlock() - b.stopWg.Wait() -} - -// Log implements the Log method required by Backend. -func (b *ChannelMemoryBackend) Log(level Level, calldepth int, rec *Record) error { - b.incoming <- rec - return nil -} - -// Head returns the oldest record node kept in memory. It can be used to -// iterate over records, one by one, up to the last record. -// -// Note: new records can get added while iterating. Hence the number of records -// iterated over might be larger than the maximum size. -func (b *ChannelMemoryBackend) Head() *node { - return b.head -} diff --git a/vendor/github.com/mageddo/go-logging/multi.go b/vendor/github.com/mageddo/go-logging/multi.go deleted file mode 100644 index 3731653e6..000000000 --- a/vendor/github.com/mageddo/go-logging/multi.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logging - -// TODO remove Level stuff from the multi logger. Do one thing. - -// multiLogger is a log multiplexer which can be used to utilize multiple log -// backends at once. -type multiLogger struct { - backends []LeveledBackend -} - -// MultiLogger creates a logger which contain multiple loggers. -func MultiLogger(backends ...Backend) LeveledBackend { - var leveledBackends []LeveledBackend - for _, backend := range backends { - leveledBackends = append(leveledBackends, AddModuleLevel(backend)) - } - return &multiLogger{leveledBackends} -} - -// Log passes the log record to all backends. -func (b *multiLogger) Log(level Level, calldepth int, rec *Record) (err error) { - for _, backend := range b.backends { - if backend.IsEnabledFor(level, rec.Module) { - // Shallow copy of the record for the formatted cache on Record and get the - // record formatter from the backend. - r2 := *rec - if e := backend.Log(level, calldepth+1, &r2); e != nil { - err = e - } - } - } - return -} - -// GetLevel returns the highest level enabled by all backends. -func (b *multiLogger) GetLevel(module string) Level { - var level Level - for _, backend := range b.backends { - if backendLevel := backend.GetLevel(module); backendLevel > level { - level = backendLevel - } - } - return level -} - -// SetLevel propagates the same level to all backends. -func (b *multiLogger) SetLevel(level Level, module string) { - for _, backend := range b.backends { - backend.SetLevel(level, module) - } -} - -// IsEnabledFor returns true if any of the backends are enabled for it. -func (b *multiLogger) IsEnabledFor(level Level, module string) bool { - for _, backend := range b.backends { - if backend.IsEnabledFor(level, module) { - return true - } - } - return false -} diff --git a/vendor/github.com/mageddo/go-logging/native/gologprinter.go b/vendor/github.com/mageddo/go-logging/native/gologprinter.go new file mode 100644 index 000000000..e874dc2a0 --- /dev/null +++ b/vendor/github.com/mageddo/go-logging/native/gologprinter.go @@ -0,0 +1,33 @@ +package native + +import ( + "log" + "io" +) + +// +// log using log package +// +type Printer struct { + log *log.Logger +} + +func(p *Printer) Printf(format string, args ...interface{}) { + p.log.Printf(format, args...) +} + +func(p *Printer) Println(args ...interface{}) { + p.log.Println(args...) +} + +func(p *Printer) SetFlags(flags int){ + p.log.SetFlags(flags) +} + +func(p *Printer) SetOutput(out io.Writer){ + p.log.SetOutput(out) +} + +func NewGologPrinter(out io.Writer, prefix string, flag int) *Printer { + return &Printer{log: log.New(out, prefix, flag)} +} diff --git a/vendor/github.com/mageddo/go-logging/nativelogger.go b/vendor/github.com/mageddo/go-logging/nativelogger.go new file mode 100644 index 000000000..038ef37a6 --- /dev/null +++ b/vendor/github.com/mageddo/go-logging/nativelogger.go @@ -0,0 +1,106 @@ +package logging + +import ( + "bytes" + "github.com/mageddo/go-logging/pkg/trace" + "fmt" + "runtime/debug" + "strconv" +) + +type defaultLogger struct { + writer Printer + level int +} + +func New(p Printer, level ...int) *defaultLogger { + if len(level) > 0 { + return &defaultLogger{p, level[0]} + } + return &defaultLogger{p, 2} +} + +func (l *defaultLogger) Debug(args ...interface{}) { + args = append([]interface{}{withCallerMethod(withLevel(new(bytes.Buffer), "DEBUG"), l.level).String()}, args...) + l.Printer().Println(args...) +} + +func (l *defaultLogger) Debugf(format string, args ...interface{}) { + l.Printer().Printf(withFormat(withCallerMethod(withLevel(new(bytes.Buffer), "DEBUG"), l.level), format).String(), args...) +} + +func (l *defaultLogger) Info(args ...interface{}) { + args = append([]interface{}{withCallerMethod(withLevel(new(bytes.Buffer), "INFO"), l.level).String()}, args...) + l.Printer().Println(args...) +} +func (l *defaultLogger) Infof(format string, args ...interface{}) { + l.Printer().Printf(withFormat(withCallerMethod(withLevel(new(bytes.Buffer), "INFO"), l.level), format).String(), args...) +} + +func (l *defaultLogger) Warning(args ...interface{}) { + args = append([]interface{}{withCallerMethod(withLevel(new(bytes.Buffer), "WARNING"), l.level).String()}, args...) + l.Printer().Println(args...) +} +func (l *defaultLogger) Warningf(format string, args ...interface{}) { + l.Printer().Printf(withFormat(withCallerMethod(withLevel(new(bytes.Buffer), "WARNING"), l.level), format).String(), args...) +} + +func (l *defaultLogger) Error(args ...interface{}) { + transformErrorInStackTrace(args, nil) + args = append([]interface{}{withCallerMethod(withLevel(new(bytes.Buffer), "ERROR"), l.level).String()}, args...) + l.Printer().Println(args...) +} +func (l *defaultLogger) Errorf(format string, args ...interface{}) { + vfmt := withFormat(withCallerMethod(withLevel(new(bytes.Buffer), "ERROR"), l.level), format) + r := transformErrorInStackTrace(args, vfmt) + l.Printer().Printf(vfmt.String(), r...) +} + +func (l *defaultLogger) Printer() Printer { + return l.writer +} + +func transformErrorInStackTrace(args []interface{}, buf *bytes.Buffer) []interface{} { + size := len(args) + if size > 0 { + last, ok := args[size - 1].(error) + if ok { + stack := fmt.Sprintf("\n%s\n%s", last.Error(), debug.Stack()) + if buf == nil { + args[size - 1] = stack + } else { + buf.WriteString(stack) + return args[:size-1] + } + } + } + return args +} + +// add method caller name to message +func withCallerMethod(buff *bytes.Buffer, level int) *bytes.Buffer { + s := trace.GetCallerFunction(level) + buff.WriteString("f=") + buff.WriteString(s.FileName) + buff.WriteString(":") + buff.WriteString(strconv.Itoa(s.Line)) + buff.WriteString(" pkg=") + buff.WriteString(s.PackageName) + buff.WriteString(" m=") + buff.WriteString(s.Funcname) + buff.WriteString(" ") + return buff +} + +// adding level to message +func withLevel(buff *bytes.Buffer, lvl string) *bytes.Buffer { + buff.WriteString(lvl) + buff.WriteString(" ") + return buff +} + +// adding format string to message +func withFormat(buff *bytes.Buffer, format string) *bytes.Buffer { + buff.WriteString(format) + return buff +} diff --git a/vendor/github.com/mageddo/go-logging/pkg/trace/trace.go b/vendor/github.com/mageddo/go-logging/pkg/trace/trace.go new file mode 100644 index 000000000..c8fc7d2ad --- /dev/null +++ b/vendor/github.com/mageddo/go-logging/pkg/trace/trace.go @@ -0,0 +1,53 @@ +package trace + +import ( + "runtime" + "strings" + "regexp" +) + +// +// Return the caller function name +// 0 -> returns the current caller function +// 1 -> returns the current caller parent +// etc. +// + +type stack struct { + FilePath string + FileName string + Line int + FullFuncName string + PackageName string + Funcname string +} + +var rx, _ = regexp.Compile(`\.func\d+$`) +func GetCallerFunction(backLevel int) *stack { + + var pc, tryAgain = make([]uintptr, backLevel + 4), true + runtime.Callers(0, pc) // pass skip did different results for different go version eg 1.7 and 1.9 + + var fn *runtime.Func + pc = pc[backLevel + 2:] + i:=0 + for ; i < len(pc) && tryAgain; i++ { + fn = runtime.FuncForPC(pc[i]) + tryAgain = rx.MatchString(fn.Name()) + } + if index := strings.LastIndex(fn.Name(), "."); index != -1 { + f, l := fn.FileLine(pc[i-1]) + return &stack{f, f[strings.LastIndex(f, "/")+1:], l, + fn.Name(), fn.Name()[:index], fn.Name()[index + 1:], + } + } + return nil +} + +func GetCallerFunctionName(backLevel int) string { + s := GetCallerFunction(backLevel + 1) + if s == nil { + return "" + } + return s.Funcname +} diff --git a/vendor/github.com/mageddo/go-logging/syslog.go b/vendor/github.com/mageddo/go-logging/syslog.go deleted file mode 100644 index 4faa53170..000000000 --- a/vendor/github.com/mageddo/go-logging/syslog.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//+build !windows,!plan9 - -package logging - -import "log/syslog" - -// SyslogBackend is a simple logger to syslog backend. It automatically maps -// the internal log levels to appropriate syslog log levels. -type SyslogBackend struct { - Writer *syslog.Writer -} - -// NewSyslogBackend connects to the syslog daemon using UNIX sockets with the -// given prefix. If prefix is not given, the prefix will be derived from the -// launched command. -func NewSyslogBackend(prefix string) (b *SyslogBackend, err error) { - var w *syslog.Writer - w, err = syslog.New(syslog.LOG_CRIT, prefix) - return &SyslogBackend{w}, err -} - -// NewSyslogBackendPriority is the same as NewSyslogBackend, but with custom -// syslog priority, like syslog.LOG_LOCAL3|syslog.LOG_DEBUG etc. -func NewSyslogBackendPriority(prefix string, priority syslog.Priority) (b *SyslogBackend, err error) { - var w *syslog.Writer - w, err = syslog.New(priority, prefix) - return &SyslogBackend{w}, err -} - -// Log implements the Backend interface. -func (b *SyslogBackend) Log(level Level, calldepth int, rec *Record) error { - line := rec.Formatted(calldepth + 1) - switch level { - case CRITICAL: - return b.Writer.Crit(line) - case ERROR: - return b.Writer.Err(line) - case WARNING: - return b.Writer.Warning(line) - case NOTICE: - return b.Writer.Notice(line) - case INFO: - return b.Writer.Info(line) - case DEBUG: - return b.Writer.Debug(line) - default: - } - panic("unhandled log level") -} diff --git a/vendor/github.com/mageddo/go-logging/syslog_fallback.go b/vendor/github.com/mageddo/go-logging/syslog_fallback.go deleted file mode 100644 index 91bc18de6..000000000 --- a/vendor/github.com/mageddo/go-logging/syslog_fallback.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013, Örjan Persson. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//+build windows plan9 - -package logging - -import ( - "fmt" -) - -type Priority int - -type SyslogBackend struct { -} - -func NewSyslogBackend(prefix string) (b *SyslogBackend, err error) { - return nil, fmt.Errorf("Platform does not support syslog") -} - -func NewSyslogBackendPriority(prefix string, priority Priority) (b *SyslogBackend, err error) { - return nil, fmt.Errorf("Platform does not support syslog") -} - -func (b *SyslogBackend) Log(level Level, calldepth int, rec *Record) error { - return fmt.Errorf("Platform does not support syslog") -} diff --git a/vendor/github.com/mageddo/go-logging/trace.go b/vendor/github.com/mageddo/go-logging/trace.go deleted file mode 100644 index a6c5f598a..000000000 --- a/vendor/github.com/mageddo/go-logging/trace.go +++ /dev/null @@ -1,47 +0,0 @@ -package logging - -// returns full package and function name -// 0 for the caller name, 1 for a up level, etc... -import ( - "runtime" - "strings" - "regexp" -) - -func GetCallerName(backLevel int) string { - - pc := make([]uintptr, 10) // at least 1 entry needed - runtime.Callers(backLevel + 2, pc) - f := runtime.FuncForPC(pc[0]) - return f.Name(); - -} - -// returns only function name -func GetCallerFunctionName(backLevel int) string { - caller := GetCallerName(backLevel + 1) - sp := strings.Split(caller, ".") - - if (len(sp) == 0) { - return "" - } - - return sp[len(sp) - 1] -} - - -// retorna o nome da funcao chamadora mas se for uma funcao anonima -// entao busca em um level acima -func GetCallerFunctionNameSkippingAnnonymous(backlevel int) string { - - var name string = ""; - counter := 0 - for tryAgain := true; tryAgain; counter++ { - name = GetCallerFunctionName(backlevel + 1 + counter) - rx, _ := regexp.Compile("^func\\d+") - tryAgain = rx.MatchString(name) - } - - return name - -} \ No newline at end of file diff --git a/vendor/vendor.json b/vendor/vendor.json index 1a0a2f14d..02d477fd4 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -159,10 +159,28 @@ "revisionTime": "2016-08-13T22:13:03Z" }, { - "checksumSHA1": "NYMQv/xaka0eXZ6nFLHrRzpjigk=", + "checksumSHA1": "dgp/yzViJU2D1VjVBye1jFxTv0M=", + "path": "github.com/mageddo/go-httpmap", + "revision": "51aa467628f65b9dfcd8c4888a7cbf33dd7b0982", + "revisionTime": "2018-05-06T17:23:18Z" + }, + { + "checksumSHA1": "ALgMULpOi2xSp6n7gvva7Wqmf3U=", "path": "github.com/mageddo/go-logging", - "revision": "7a44b89dd8729895685b465e309f2c8253be6a42", - "revisionTime": "2017-08-26T21:24:42Z" + "revision": "8a9fe7be7eb3a469ebd798a23ca0706cfc2be869", + "revisionTime": "2018-05-06T01:37:09Z" + }, + { + "checksumSHA1": "3a2Cl6bL2Q6uYapCm6w+t2gPrEQ=", + "path": "github.com/mageddo/go-logging/native", + "revision": "8a9fe7be7eb3a469ebd798a23ca0706cfc2be869", + "revisionTime": "2018-05-06T01:37:09Z" + }, + { + "checksumSHA1": "lfX48z2cH3wjbmocIz9KCMmFN0s=", + "path": "github.com/mageddo/go-logging/pkg/trace", + "revision": "8a9fe7be7eb3a469ebd798a23ca0706cfc2be869", + "revisionTime": "2018-05-06T01:37:09Z" }, { "checksumSHA1": "cavsxjKtP9+BRItaR8LAealFNjA=",