Merge branch 'nicolas-martin-new-logger' into development

This commit is contained in:
Dimitri Herzog 2021-02-25 23:37:04 +01:00
commit 01c1a4a0a9
29 changed files with 207 additions and 181 deletions

View File

@ -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")
}

View File

@ -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)
}
}
}

View File

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

View File

@ -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")
}

View File

@ -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)
}

View File

@ -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

View File

@ -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"})

View File

@ -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("_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/")
}

View File

@ -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
}

View File

@ -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")
}

View File

@ -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())

View File

@ -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)
}
}))
}

View File

@ -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

View File

@ -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")
}

62
log/logger.go Normal file
View File

@ -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{})
}
}

View File

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

View File

@ -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",

View File

@ -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

View File

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

View File

@ -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 {

View File

@ -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")
}

View File

@ -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,
}),

View File

@ -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)
}
})

View File

@ -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")
}

View File

@ -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
}

View File

@ -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")
}

View File

@ -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)
}
}

View File

@ -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"))

View File

@ -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")
}