diff --git a/api/api_suite_test.go b/api/api_suite_test.go index 92601177..7ed8a379 100644 --- a/api/api_suite_test.go +++ b/api/api_suite_test.go @@ -1,15 +1,15 @@ package api_test import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/sirupsen/logrus" ) func TestResolver(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "API Suite") } diff --git a/cmd/blocking.go b/cmd/blocking.go index 8befaf67..f17560cb 100644 --- a/cmd/blocking.go +++ b/cmd/blocking.go @@ -7,7 +7,8 @@ import ( "fmt" "net/http" - log "github.com/sirupsen/logrus" + "blocky/log" + "github.com/spf13/cobra" ) @@ -48,15 +49,15 @@ func newBlockingCommand() *cobra.Command { func enableBlocking(_ *cobra.Command, _ []string) { resp, err := http.Get(apiURL(api.PathBlockingEnablePath)) if err != nil { - log.Fatal("can't execute", err) + log.Log().Fatal("can't execute", err) return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { - log.Info("OK") + log.Log().Info("OK") } else { - log.Fatal("NOK: ", resp.Status) + log.Log().Fatal("NOK: ", resp.Status) } } @@ -65,28 +66,28 @@ func disableBlocking(cmd *cobra.Command, _ []string) { resp, err := http.Get(fmt.Sprintf("%s?duration=%s", apiURL(api.PathBlockingDisablePath), duration)) if err != nil { - log.Fatal("can't execute", err) + log.Log().Fatal("can't execute", err) return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { - log.Info("OK") + log.Log().Info("OK") } else { - log.Fatal("NOK: ", resp.Status) + log.Log().Fatal("NOK: ", resp.Status) } } func statusBlocking(_ *cobra.Command, _ []string) { resp, err := http.Get(apiURL(api.PathBlockingStatusPath)) if err != nil { - log.Fatal("can't execute", err) + log.Log().Fatal("can't execute", err) return } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - log.Fatal("NOK: ", resp.Status) + log.Log().Fatal("NOK: ", resp.Status) return } @@ -96,12 +97,12 @@ func statusBlocking(_ *cobra.Command, _ []string) { util.FatalOnError("can't read response: ", err) if result.Enabled { - log.Info("blocking enabled") + log.Log().Info("blocking enabled") } else { if result.AutoEnableInSec == 0 { - log.Info("blocking disabled") + log.Log().Info("blocking disabled") } else { - log.Infof("blocking disabled for %d seconds", result.AutoEnableInSec) + log.Log().Infof("blocking disabled for %d seconds", result.AutoEnableInSec) } } } diff --git a/cmd/cmd_suite_test.go b/cmd/cmd_suite_test.go index c5e5561f..99f24b2c 100644 --- a/cmd/cmd_suite_test.go +++ b/cmd/cmd_suite_test.go @@ -1,12 +1,12 @@ package cmd import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" ) @@ -17,12 +17,13 @@ var ( func TestCmd(t *testing.T) { BeforeSuite(func() { - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } loggerHook = test.NewGlobal() + Log().AddHook(loggerHook) }) AfterSuite(func() { - logrus.StandardLogger().ExitFunc = nil + Log().ExitFunc = nil loggerHook.Reset() }) RegisterFailHandler(Fail) diff --git a/cmd/lists.go b/cmd/lists.go index 1ea39f29..c2fc2c03 100644 --- a/cmd/lists.go +++ b/cmd/lists.go @@ -2,12 +2,11 @@ package cmd import ( "blocky/api" + "blocky/log" "io/ioutil" "net/http" "github.com/spf13/cobra" - - log "github.com/sirupsen/logrus" ) func NewListsCommand() *cobra.Command { @@ -32,7 +31,7 @@ func newRefreshCommand() *cobra.Command { func refreshList(_ *cobra.Command, _ []string) { resp, err := http.Post(apiURL(api.PathListsRefresh), "application/json", nil) if err != nil { - log.Fatal("can't execute", err) + log.Log().Fatal("can't execute", err) return } @@ -40,10 +39,10 @@ func refreshList(_ *cobra.Command, _ []string) { if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) - log.Fatalf("NOK: %s %s", resp.Status, string(body)) + log.Log().Fatalf("NOK: %s %s", resp.Status, string(body)) return } - log.Info("OK") + log.Log().Info("OK") } diff --git a/cmd/query.go b/cmd/query.go index f25573a5..b8d8bb82 100644 --- a/cmd/query.go +++ b/cmd/query.go @@ -8,10 +8,10 @@ import ( "io/ioutil" "net/http" + "blocky/log" + "github.com/miekg/dns" "github.com/spf13/cobra" - - log "github.com/sirupsen/logrus" ) func NewQueryCommand() *cobra.Command { @@ -32,7 +32,7 @@ func query(cmd *cobra.Command, args []string) { qType := dns.StringToType[typeFlag] if qType == dns.TypeNone { - log.Fatalf("unknown query type '%s'", typeFlag) + log.Log().Fatalf("unknown query type '%s'", typeFlag) return } @@ -45,7 +45,7 @@ func query(cmd *cobra.Command, args []string) { resp, err := http.Post(apiURL(api.PathQueryPath), "application/json", bytes.NewBuffer(jsonValue)) if err != nil { - log.Fatal("can't execute", err) + log.Log().Fatal("can't execute", err) return } @@ -53,7 +53,7 @@ func query(cmd *cobra.Command, args []string) { if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) - log.Fatalf("NOK: %s %s", resp.Status, string(body)) + log.Log().Fatalf("NOK: %s %s", resp.Status, string(body)) return } @@ -63,9 +63,9 @@ func query(cmd *cobra.Command, args []string) { util.FatalOnError("can't read response: ", err) - log.Infof("Query result for '%s' (%s):", apiRequest.Query, apiRequest.Type) - log.Infof("\treason: %20s", result.Reason) - log.Infof("\tresponse type: %20s", result.ResponseType) - log.Infof("\tresponse: %20s", result.Response) - log.Infof("\treturn code: %20s", result.ReturnCode) + log.Log().Infof("Query result for '%s' (%s):", apiRequest.Query, apiRequest.Type) + log.Log().Infof("\treason: %20s", result.Reason) + log.Log().Infof("\tresponse type: %20s", result.ResponseType) + log.Log().Infof("\tresponse: %20s", result.Response) + log.Log().Infof("\treturn code: %20s", result.ReturnCode) } diff --git a/cmd/root.go b/cmd/root.go index ed258efc..df823496 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -2,13 +2,11 @@ package cmd import ( "blocky/config" + "blocky/log" "fmt" "os" "github.com/spf13/cobra" - prefixed "github.com/x-cray/logrus-prefixed-formatter" - - log "github.com/sirupsen/logrus" ) //nolint:gochecknoglobals @@ -57,39 +55,9 @@ func init() { cobra.OnInitialize(initConfig) } -func configureLog(cfg *config.Config) { - if level, err := log.ParseLevel(cfg.LogLevel); err != nil { - log.Fatalf("invalid log level %s %v", cfg.LogLevel, err) - } else { - log.SetLevel(level) - } - - if cfg.LogFormat == config.CfgLogFormatText { - logFormatter := &prefixed.TextFormatter{ - TimestampFormat: "2006-01-02 15:04:05", - FullTimestamp: true, - ForceFormatting: true, - ForceColors: true, - QuoteEmptyFields: true} - - logFormatter.SetColorScheme(&prefixed.ColorScheme{ - PrefixStyle: "blue+b", - TimestampStyle: "white+h", - }) - - log.SetFormatter(logFormatter) - } - - if cfg.LogFormat == config.CfgLogFormatJSON { - log.SetFormatter(&log.JSONFormatter{}) - } - - log.SetOutput(os.Stdout) -} - func initConfig() { cfg = config.NewConfig(configPath) - configureLog(&cfg) + log.ConfigureLogger(cfg.LogLevel, cfg.LogFormat) if apiPort == 0 { apiPort = cfg.HTTPPort diff --git a/cmd/root_test.go b/cmd/root_test.go index 0c2e48fe..57f0f7b8 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -1,14 +1,15 @@ package cmd import ( + "blocky/log" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/sirupsen/logrus" ) var _ = Describe("Version command", func() { When("Version command is called", func() { - logrus.StandardLogger().ExitFunc = nil + log.Log().ExitFunc = nil It("should execute without error", func() { c := NewRootCommand() c.SetArgs([]string{"help"}) diff --git a/cmd/serve.go b/cmd/serve.go index 157862e1..891cdcbe 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -14,7 +14,8 @@ import ( "syscall" "time" - log "github.com/sirupsen/logrus" + "blocky/log" + "github.com/spf13/cobra" ) @@ -49,7 +50,7 @@ func startServer(_ *cobra.Command, _ []string) { go func() { <-signals - log.Infof("Terminating...") + log.Log().Infof("Terminating...") srv.Stop() done <- true }() @@ -62,7 +63,7 @@ func configureHTTPClient(cfg *config.Config) { if cfg.BootstrapDNS != (config.Upstream{}) { if cfg.BootstrapDNS.Net == config.NetTCPUDP { dns := net.JoinHostPort(cfg.BootstrapDNS.Host, fmt.Sprint(cfg.BootstrapDNS.Port)) - log.Debugf("using %s as bootstrap dns server", dns) + log.Log().Debugf("using %s as bootstrap dns server", dns) r := &net.Resolver{ PreferGo: true, @@ -81,25 +82,25 @@ func configureHTTPClient(cfg *config.Config) { TLSHandshakeTimeout: 5 * time.Second, } } else { - log.Fatal("bootstrap dns net should be tcp+udp") + log.Log().Fatal("bootstrap dns net should be tcp+udp") } } } func printBanner() { - log.Info("_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/") - log.Info("_/ _/") - log.Info("_/ _/") - log.Info("_/ _/ _/ _/ _/") - log.Info("_/ _/_/_/ _/ _/_/ _/_/_/ _/ _/ _/ _/ _/") - log.Info("_/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/") - log.Info("_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/") - log.Info("_/ _/_/_/ _/ _/_/ _/_/_/ _/ _/ _/_/_/ _/") - log.Info("_/ _/ _/") - log.Info("_/ _/_/ _/") - log.Info("_/ _/") - log.Info("_/ _/") - log.Infof("_/ Version: %-18s Build time: %-18s _/", version, buildTime) - log.Info("_/ _/") - log.Info("_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/") + log.Log().Info("_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/") + log.Log().Info("_/ _/") + log.Log().Info("_/ _/") + log.Log().Info("_/ _/ _/ _/ _/") + log.Log().Info("_/ _/_/_/ _/ _/_/ _/_/_/ _/ _/ _/ _/ _/") + log.Log().Info("_/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/") + log.Log().Info("_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/") + log.Log().Info("_/ _/_/_/ _/ _/_/ _/_/_/ _/ _/ _/_/_/ _/") + log.Log().Info("_/ _/ _/") + log.Log().Info("_/ _/_/ _/") + log.Log().Info("_/ _/") + log.Log().Info("_/ _/") + log.Log().Infof("_/ Version: %-18s Build time: %-18s _/", version, buildTime) + log.Log().Info("_/ _/") + log.Log().Info("_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/") } diff --git a/config/config.go b/config/config.go index 7e46589a..3b57e22a 100644 --- a/config/config.go +++ b/config/config.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - log "github.com/sirupsen/logrus" + "blocky/log" "gopkg.in/yaml.v2" ) @@ -126,13 +126,13 @@ func ParseUpstream(upstream string) (result Upstream, err error) { func extractNet(upstream string) (string, string) { if strings.HasPrefix(upstream, NetTCP+":") { - log.Warnf("net prefix tcp is deprecated, using tcp+udp as default fallback") + log.Log().Warnf("net prefix tcp is deprecated, using tcp+udp as default fallback") return NetTCPUDP, strings.Replace(upstream, NetTCP+":", "", 1) } if strings.HasPrefix(upstream, NetUDP+":") { - log.Warnf("net prefix udp is deprecated, using tcp+udp as default fallback") + log.Log().Warnf("net prefix udp is deprecated, using tcp+udp as default fallback") return NetTCPUDP, strings.Replace(upstream, NetUDP+":", "", 1) } @@ -156,11 +156,6 @@ const ( cfgDefaultPrometheusPath = "/metrics" ) -const ( - CfgLogFormatText = "text" - CfgLogFormatJSON = "json" -) - // main configuration type Config struct { Upstream UpstreamConfig `yaml:"upstream"` @@ -236,16 +231,16 @@ func NewConfig(path string) Config { data, err := ioutil.ReadFile(path) if err != nil { - log.Fatal("Can't read config file: ", err) + log.Log().Fatal("Can't read config file: ", err) } err = yaml.UnmarshalStrict(data, &cfg) if err != nil { - log.Fatal("wrong file structure: ", err) + log.Log().Fatal("wrong file structure: ", err) } - if cfg.LogFormat != CfgLogFormatText && cfg.LogFormat != CfgLogFormatJSON { - log.Fatal("LogFormat should be 'text' or 'json'") + if cfg.LogFormat != log.CfgLogFormatText && cfg.LogFormat != log.CfgLogFormatJSON { + log.Log().Fatal("LogFormat should be 'text' or 'json'") } return cfg @@ -254,6 +249,6 @@ func NewConfig(path string) Config { func setDefaultValues(cfg *Config) { cfg.Port = cfgDefaultPort cfg.LogLevel = "info" - cfg.LogFormat = CfgLogFormatText + cfg.LogFormat = log.CfgLogFormatText cfg.Prometheus.Path = cfgDefaultPrometheusPath } diff --git a/config/config_suite_test.go b/config/config_suite_test.go index 9d94a59e..a97a5b9d 100644 --- a/config/config_suite_test.go +++ b/config/config_suite_test.go @@ -1,16 +1,15 @@ package config import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) func TestConfig(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "Text") RegisterFailHandler(Fail) RunSpecs(t, "Config Suite") } diff --git a/config/config_test.go b/config/config_test.go index a6840daa..b36cefe5 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -1,6 +1,7 @@ package config import ( + . "blocky/log" "io/ioutil" "net" "os" @@ -8,8 +9,6 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) var _ = Describe("Config", func() { @@ -52,11 +51,11 @@ var _ = Describe("Config", func() { err = ioutil.WriteFile("config.yml", []byte("malformed_config"), 0644) Expect(err).Should(Succeed()) - defer func() { logrus.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } _ = NewConfig("config.yml") Expect(fatal).Should(BeTrue()) @@ -67,11 +66,11 @@ var _ = Describe("Config", func() { err := os.Chdir("../..") Expect(err).Should(Succeed()) - defer func() { logrus.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } _ = NewConfig("config.yml") Expect(fatal).Should(BeTrue()) diff --git a/helpertest/helper.go b/helpertest/helper.go index 033ad724..c5e7ca11 100644 --- a/helpertest/helper.go +++ b/helpertest/helper.go @@ -4,11 +4,12 @@ import ( "bytes" "fmt" "io/ioutil" - "log" "net/http" "net/http/httptest" "os" + "blocky/log" + "github.com/miekg/dns" "github.com/onsi/gomega/types" ) @@ -17,12 +18,12 @@ import ( func TempFile(data string) *os.File { f, err := ioutil.TempFile("", "prefix") if err != nil { - log.Fatal(err) + log.Log().Fatal(err) } _, err = f.WriteString(data) if err != nil { - log.Fatal(err) + log.Log().Fatal(err) } return f @@ -33,7 +34,7 @@ func TestServer(data string) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { _, err := rw.Write([]byte(data)) if err != nil { - log.Fatal("can't write to buffer:", err) + log.Log().Fatal("can't write to buffer:", err) } })) } diff --git a/lists/list_cache.go b/lists/list_cache.go index 9f20f9ef..1ff7e3d6 100644 --- a/lists/list_cache.go +++ b/lists/list_cache.go @@ -14,6 +14,8 @@ import ( "sync" "time" + "blocky/log" + "github.com/sirupsen/logrus" ) @@ -146,7 +148,7 @@ func periodicUpdate(cache *ListCache) { } func logger() *logrus.Entry { - return logrus.WithField("prefix", "list_cache") + return log.PrefixedLog("list_cache") } // downloads and reads files with domain names and creates cache for them diff --git a/lists/list_suite_test.go b/lists/list_suite_test.go index 2c4d3bb3..4bf39053 100644 --- a/lists/list_suite_test.go +++ b/lists/list_suite_test.go @@ -1,16 +1,15 @@ package lists import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) func TestLists(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "Lists Suite") } diff --git a/log/logger.go b/log/logger.go new file mode 100644 index 00000000..0c8ad292 --- /dev/null +++ b/log/logger.go @@ -0,0 +1,62 @@ +package log + +import ( + "github.com/sirupsen/logrus" + prefixed "github.com/x-cray/logrus-prefixed-formatter" +) + +// Logger is the global logging instance +// nolint:gochecknoglobals +var logger *logrus.Logger + +const ( + CfgLogFormatText = "text" + CfgLogFormatJSON = "json" +) + +// nolint:gochecknoinits +func init() { + logger = logrus.New() + + ConfigureLogger("info", "text") +} + +func Log() *logrus.Logger { + return logger +} + +func PrefixedLog(prefix string) *logrus.Entry { + return logger.WithField("prefix", prefix) +} + +func ConfigureLogger(logLevel, logFormat string) { + if len(logLevel) == 0 { + logLevel = "info" + } + + if level, err := logrus.ParseLevel(logLevel); err != nil { + logger.Fatalf("invalid log level %s %v", logLevel, err) + } else { + logger.SetLevel(level) + } + + if logFormat == CfgLogFormatText { + logFormatter := &prefixed.TextFormatter{ + TimestampFormat: "2006-01-02 15:04:05", + FullTimestamp: true, + ForceFormatting: true, + ForceColors: true, + QuoteEmptyFields: true} + + logFormatter.SetColorScheme(&prefixed.ColorScheme{ + PrefixStyle: "blue+b", + TimestampStyle: "white+h", + }) + + logger.SetFormatter(logFormatter) + } + + if logFormat == CfgLogFormatJSON { + logger.SetFormatter(&logrus.JSONFormatter{}) + } +} diff --git a/resolver/blocking_resolver.go b/resolver/blocking_resolver.go index 1d87fa21..9062872d 100644 --- a/resolver/blocking_resolver.go +++ b/resolver/blocking_resolver.go @@ -14,8 +14,10 @@ import ( "strings" "time" + "blocky/log" + "github.com/miekg/dns" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) func createBlockHandler(cfg config.BlockingConfig) blockHandler { @@ -43,7 +45,7 @@ func createBlockHandler(cfg config.BlockingConfig) blockHandler { } } - log.Fatalf("unknown blockType, please use one of: ZeroIP, NxDomain or specify destination IP address(es)") + log.Log().Fatalf("unknown blockType, please use one of: ZeroIP, NxDomain or specify destination IP address(es)") return zeroIPBlockHandler{} } @@ -108,12 +110,12 @@ func (r *BlockingResolver) DisableBlocking(duration time.Duration) { s.disableEnd = time.Now().Add(duration) if duration == 0 { - log.Info("disable blocking") + log.Log().Info("disable blocking") } else { - log.Infof("disable blocking for %s", duration) + log.Log().Infof("disable blocking for %s", duration) s.enableTimer = time.AfterFunc(duration, func() { r.EnableBlocking() - log.Info("blocking enabled again") + log.Log().Info("blocking enabled again") }) } } @@ -146,7 +148,7 @@ func determineWhitelistOnlyGroups(cfg *config.BlockingConfig) (result []string) } // sets answer and/or return code for DNS response, if request should be blocked -func (r *BlockingResolver) handleBlocked(logger *log.Entry, +func (r *BlockingResolver) handleBlocked(logger *logrus.Entry, request *Request, question dns.Question, reason string) (*Response, error) { response := new(dns.Msg) response.SetReply(request.Req) @@ -188,7 +190,7 @@ func shouldHandle(question dns.Question) bool { } func (r *BlockingResolver) handleBlacklist(groupsToCheck []string, - request *Request, logger *log.Entry) (*Response, error) { + request *Request, logger *logrus.Entry) (*Response, error) { logger.WithField("groupsToCheck", strings.Join(groupsToCheck, "; ")).Debug("checking groups for request") whitelistOnlyAllowed := reflect.DeepEqual(groupsToCheck, r.whitelistOnlyGroups) diff --git a/resolver/blocking_resolver_test.go b/resolver/blocking_resolver_test.go index 90346035..f26932e3 100644 --- a/resolver/blocking_resolver_test.go +++ b/resolver/blocking_resolver_test.go @@ -5,6 +5,7 @@ import ( . "blocky/evt" . "blocky/helpertest" "blocky/lists" + . "blocky/log" "blocky/util" "os" @@ -13,7 +14,6 @@ import ( "github.com/miekg/dns" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/mock" ) @@ -561,9 +561,9 @@ badcnamedomain.com`) When("Wrong blockType is used", func() { var fatal bool It("should end with fatal exit", func() { - defer func() { logrus.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } _ = NewBlockingResolver(config.BlockingConfig{ BlockType: "wrong", diff --git a/resolver/conditionall_upstream_resolver_test.go b/resolver/conditionall_upstream_resolver_test.go index 5d1be8c7..1730beba 100644 --- a/resolver/conditionall_upstream_resolver_test.go +++ b/resolver/conditionall_upstream_resolver_test.go @@ -3,6 +3,7 @@ package resolver import ( "blocky/config" . "blocky/helpertest" + "blocky/log" "blocky/util" "github.com/miekg/dns" @@ -49,7 +50,7 @@ var _ = Describe("ConditionalUpstreamResolver", func() { When("Query is exact equal defined condition in mapping", func() { Context("first mapping entry", func() { It("Should resolve the IP of conditional DNS", func() { - resp, err = sut.Resolve(newRequest("fritz.box.", dns.TypeA, logrus.NewEntry(logrus.New()))) + resp, err = sut.Resolve(newRequest("fritz.box.", dns.TypeA, logrus.NewEntry(log.Log()))) Expect(resp.Res.Answer).Should(BeDNSRecord("fritz.box.", dns.TypeA, 123, "123.124.122.122")) // no call to next resolver diff --git a/resolver/query_logging_resolver_test.go b/resolver/query_logging_resolver_test.go index 8332d396..42b82fd2 100644 --- a/resolver/query_logging_resolver_test.go +++ b/resolver/query_logging_resolver_test.go @@ -2,6 +2,7 @@ package resolver import ( "blocky/config" + . "blocky/log" "blocky/util" "bufio" "encoding/csv" @@ -16,8 +17,6 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" - - log "github.com/sirupsen/logrus" ) var _ = Describe("QueryLoggingResolver", func() { @@ -179,11 +178,11 @@ var _ = Describe("QueryLoggingResolver", func() { When("Log directory does not exist", func() { It("should exit with error", func() { - defer func() { log.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - log.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } _ = NewQueryLoggingResolver(config.QueryLogConfig{Dir: "notExists"}) Expect(fatal).Should(BeTrue()) @@ -191,11 +190,11 @@ var _ = Describe("QueryLoggingResolver", func() { }) When("not existing log directory is configured, log retention is enabled", func() { It("should exit with error", func() { - defer func() { log.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - log.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } sut := NewQueryLoggingResolver(config.QueryLogConfig{ Dir: "wrongDir", @@ -254,7 +253,7 @@ func readCsv(file string) [][]string { if err == io.EOF { break } else if err != nil { - log.Fatal("can't read line", err) + Log().Fatal("can't read line", err) } result = append(result, line) diff --git a/resolver/resolver.go b/resolver/resolver.go index e675ab58..0e59bf80 100644 --- a/resolver/resolver.go +++ b/resolver/resolver.go @@ -1,6 +1,7 @@ package resolver import ( + "blocky/log" "blocky/util" "fmt" "net" @@ -40,7 +41,7 @@ func newRequest(question string, rType uint16, logger ...*logrus.Entry) *Request if len(logger) == 1 { loggerEntry = logger[0] } else { - loggerEntry = logrus.NewEntry(logrus.New()) + loggerEntry = logrus.NewEntry(log.Log()) } return &Request{ @@ -55,7 +56,7 @@ func newRequestWithClient(question string, rType uint16, ip string, clientNames ClientIP: net.ParseIP(ip), ClientNames: clientNames, Req: util.NewMsgWithQuestion(question, rType), - Log: logrus.NewEntry(logrus.New()), + Log: logrus.NewEntry(log.Log()), RequestTS: time.Time{}, Protocol: UDP, } @@ -111,7 +112,7 @@ func (r *NextResolver) GetNext() Resolver { } func logger(prefix string) *logrus.Entry { - return logrus.WithField("prefix", prefix) + return log.PrefixedLog(prefix) } func withPrefix(logger *logrus.Entry, prefix string) *logrus.Entry { diff --git a/resolver/resolver_suite_test.go b/resolver/resolver_suite_test.go index a7f9f87b..c813e7d8 100644 --- a/resolver/resolver_suite_test.go +++ b/resolver/resolver_suite_test.go @@ -1,15 +1,15 @@ package resolver_test import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/sirupsen/logrus" ) func TestResolver(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "Resolver Suite") } diff --git a/server/server.go b/server/server.go index 680f756e..a67f786e 100644 --- a/server/server.go +++ b/server/server.go @@ -3,6 +3,7 @@ package server import ( "blocky/api" "blocky/config" + "blocky/log" "blocky/metrics" "blocky/resolver" "net/http" @@ -31,7 +32,7 @@ type Server struct { } func logger() *logrus.Entry { - return logrus.WithField("prefix", "server") + return log.PrefixedLog("server") } func getServerAddress(cfg *config.Config) string { @@ -43,24 +44,16 @@ func getServerAddress(cfg *config.Config) string { return address } -func initLogging(cfg *config.Config) { - if level, err := logrus.ParseLevel(cfg.LogLevel); err != nil { - logrus.Fatalf("invalid log level %s %v", cfg.LogLevel, err) - } else { - logrus.SetLevel(level) - } -} - func NewServer(cfg *config.Config) (server *Server, err error) { address := getServerAddress(cfg) + log.ConfigureLogger(cfg.LogLevel, cfg.LogFormat) + udpServer := createUDPServer(address) tcpServer := createTCPServer(address) var httpListener, httpsListener net.Listener - initLogging(cfg) - router := createRouter(cfg) if cfg.HTTPPort > 0 { @@ -265,7 +258,7 @@ func newRequest(clientIP net.IP, protocol resolver.RequestProtocol, request *dns Protocol: protocol, Req: request, RequestTS: time.Now(), - Log: logrus.WithFields(logrus.Fields{ + Log: log.Log().WithFields(logrus.Fields{ "question": util.QuestionToString(request.Question), "client_ip": clientIP, }), diff --git a/server/server_endpoints.go b/server/server_endpoints.go index 370ce5b9..da45cc9a 100644 --- a/server/server_endpoints.go +++ b/server/server_endpoints.go @@ -3,6 +3,7 @@ package server import ( "blocky/api" "blocky/config" + "blocky/log" "blocky/resolver" "blocky/util" "blocky/web" @@ -19,7 +20,6 @@ import ( "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/miekg/dns" - "github.com/sirupsen/logrus" ) const ( @@ -247,7 +247,7 @@ func configureRootHandler(cfg *config.Config, router *chi.Mux) { err := t.Execute(writer, links) if err != nil { - logrus.Error("can't write index template: ", err) + log.Log().Error("can't write index template: ", err) writer.WriteHeader(http.StatusInternalServerError) } }) diff --git a/server/server_suite_test.go b/server/server_suite_test.go index 644f2d47..095e81f4 100644 --- a/server/server_suite_test.go +++ b/server/server_suite_test.go @@ -1,16 +1,15 @@ package server import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) func TestDNSServer(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "Server Suite") } diff --git a/server/server_test.go b/server/server_test.go index 3726110b..2e51027d 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -4,13 +4,13 @@ import ( "blocky/api" "blocky/config" . "blocky/helpertest" + . "blocky/log" "blocky/resolver" "blocky/util" "bytes" "encoding/base64" "encoding/json" "io/ioutil" - "log" "net" "net/http" "strings" @@ -20,7 +20,6 @@ import ( . "github.com/onsi/gomega" "github.com/miekg/dns" - "github.com/sirupsen/logrus" ) var _ = Describe("Running DNS server", func() { @@ -455,11 +454,11 @@ var _ = Describe("Running DNS server", func() { Describe("Server start", func() { When("Server start is called", func() { It("start was called 2 times, start should fail", func() { - defer func() { logrus.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } // create server server, err := NewServer(&config.Config{ @@ -499,11 +498,11 @@ var _ = Describe("Running DNS server", func() { Describe("Server stop", func() { When("Stop is called", func() { It("stop was called 2 times, start should fail", func() { - defer func() { logrus.StandardLogger().ExitFunc = nil }() + defer func() { Log().ExitFunc = nil }() var fatal bool - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } // create server server, err := NewServer(&config.Config{ @@ -564,18 +563,18 @@ var _ = Describe("Running DNS server", func() { func requestServer(request *dns.Msg) *dns.Msg { conn, err := net.Dial("udp", ":55555") if err != nil { - log.Fatal("could not connect to server: ", err) + Log().Fatal("could not connect to server: ", err) } defer conn.Close() msg, err := request.Pack() if err != nil { - log.Fatal("can't pack request: ", err) + Log().Fatal("can't pack request: ", err) } _, err = conn.Write(msg) if err != nil { - log.Fatal("can't send request to server: ", err) + Log().Fatal("can't send request to server: ", err) } out := make([]byte, 1024) @@ -585,13 +584,13 @@ func requestServer(request *dns.Msg) *dns.Msg { err := response.Unpack(out) if err != nil { - log.Fatal("can't unpack response: ", err) + Log().Fatal("can't unpack response: ", err) } return response } - log.Fatal("could not read from connection", err) + Log().Fatal("could not read from connection", err) return nil } diff --git a/stats/stats_suite_test.go b/stats/stats_suite_test.go index c1ccbd63..8acc76f8 100644 --- a/stats/stats_suite_test.go +++ b/stats/stats_suite_test.go @@ -1,16 +1,15 @@ package stats import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) func TestStats(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "Stats Suite") } diff --git a/util/common.go b/util/common.go index 347b0c1b..4ba4484b 100644 --- a/util/common.go +++ b/util/common.go @@ -6,8 +6,10 @@ import ( "sort" "strings" + "blocky/log" + "github.com/miekg/dns" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) func AnswerToString(answer []dns.RR) string { @@ -58,7 +60,7 @@ func CreateAnswerFromQuestion(question dns.Question, ip net.IP, remainingTTL uin return a, nil } - log.Errorf("Using fallback for unsupported query type %s", dns.TypeToString[question.Qtype]) + log.Log().Errorf("Using fallback for unsupported query type %s", dns.TypeToString[question.Qtype]) return dns.NewRR(fmt.Sprintf("%s %d %s %s %s", question.Name, remainingTTL, "IN", dns.TypeToString[question.Qtype], ip)) @@ -113,11 +115,11 @@ func IterateValueSorted(in map[string]int, fn func(string, int)) { func LogOnError(message string, err error) { if err != nil { - log.Error(message, err) + log.Log().Error(message, err) } } -func LogOnErrorWithEntry(logEntry *log.Entry, message string, err error) { +func LogOnErrorWithEntry(logEntry *logrus.Entry, message string, err error) { if err != nil { logEntry.Error(message, err) } @@ -125,7 +127,7 @@ func LogOnErrorWithEntry(logEntry *log.Entry, message string, err error) { func FatalOnError(message string, err error) { if err != nil { - log.Fatal(message, err) + log.Log().Fatal(message, err) } } diff --git a/util/common_test.go b/util/common_test.go index 34590d05..4b3b0ff5 100644 --- a/util/common_test.go +++ b/util/common_test.go @@ -1,6 +1,7 @@ package util import ( + . "blocky/log" "errors" "fmt" "net" @@ -175,6 +176,7 @@ var _ = Describe("Common function tests", func() { err := errors.New("test") It("should log", func() { hook := test.NewGlobal() + Log().AddHook(hook) defer hook.Reset() LogOnError("message ", err) Expect(hook.LastEntry().Message).Should(Equal("message test")) @@ -185,6 +187,7 @@ var _ = Describe("Common function tests", func() { err := errors.New("test") It("should log", func() { hook := test.NewGlobal() + Log().AddHook(hook) defer hook.Reset() logger, hook := test.NewNullLogger() entry := logrus.NewEntry(logger) @@ -197,10 +200,11 @@ var _ = Describe("Common function tests", func() { err := errors.New("test") It("should log and exit", func() { hook := test.NewGlobal() + Log().AddHook(hook) fatal := false - logrus.StandardLogger().ExitFunc = func(int) { fatal = true } + Log().ExitFunc = func(int) { fatal = true } defer func() { - logrus.StandardLogger().ExitFunc = nil + Log().ExitFunc = nil }() FatalOnError("message ", err) Expect(hook.LastEntry().Message).Should(Equal("message test")) diff --git a/util/util_suite_test.go b/util/util_suite_test.go index bb27285e..66280bc6 100644 --- a/util/util_suite_test.go +++ b/util/util_suite_test.go @@ -1,16 +1,15 @@ package util import ( + . "blocky/log" "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/sirupsen/logrus" ) func TestLists(t *testing.T) { - logrus.SetLevel(logrus.WarnLevel) + ConfigureLogger("Warn", "text") RegisterFailHandler(Fail) RunSpecs(t, "Util Suite") }