Skip to content

Commit

Permalink
chore(log): use github.com/qdm12/log
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Dec 7, 2022
1 parent 3ad972b commit 727f3ff
Show file tree
Hide file tree
Showing 17 changed files with 146 additions and 70 deletions.
30 changes: 18 additions & 12 deletions cmd/updater/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ import (
"github.com/qdm12/ddns-updater/internal/update"
"github.com/qdm12/ddns-updater/pkg/publicip"
"github.com/qdm12/golibs/connectivity"
"github.com/qdm12/golibs/logging"
"github.com/qdm12/golibs/params"
"github.com/qdm12/goshutdown"
"github.com/qdm12/gosplash"
"github.com/qdm12/log"
)

//nolint:gochecknoglobals
Expand All @@ -49,7 +49,7 @@ func main() {
BuildDate: buildDate,
}
env := params.New()
logger := logging.New(logging.Settings{Writer: os.Stdout})
logger := log.New()

ctx := context.Background()
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
Expand Down Expand Up @@ -96,7 +96,7 @@ var (
errShoutrrrSetup = errors.New("failed setting up Shoutrrr")
)

func _main(ctx context.Context, env params.Interface, args []string, logger logging.ParentLogger,
func _main(ctx context.Context, env params.Interface, args []string, logger log.LoggerInterface,
buildInfo models.BuildInformation, timeNow func() time.Time) (err error) {
if health.IsClientMode(args) {
// Running the program in a separate instance through the Docker
Expand Down Expand Up @@ -145,10 +145,10 @@ func _main(ctx context.Context, env params.Interface, args []string, logger logg
}

// Setup logger
loggerSettings := logging.Settings{
Level: config.Logger.Level,
Caller: config.Logger.Caller}
logger = logging.New(loggerSettings)
logger.Patch(log.SetLevel(config.Logger.Level))
if config.Logger.Caller {
logger.Patch(log.SetCallerFile(true), log.SetCallerLine(true))
}

sender, err := shoutrrr.CreateSender(config.Shoutrrr.Addresses...)
if err != nil {
Expand Down Expand Up @@ -242,22 +242,23 @@ func _main(ctx context.Context, env params.Interface, args []string, logger logg
go runner.ForceUpdate(ctx)

isHealthy := health.MakeIsHealthy(db, resolver)
healthLogger := logger.New(log.SetComponent("healthcheck server"))
healthServer := health.NewServer(config.Health.ServerAddress,
logger.NewChild(logging.Settings{Prefix: "healthcheck server: "}),
isHealthy)
healthLogger, isHealthy)
healthServerHandler, healthServerCtx, healthServerDone := goshutdown.NewGoRoutineHandler("health server")
go healthServer.Run(healthServerCtx, healthServerDone)

address := ":" + strconv.Itoa(int(config.Server.Port))
serverLogger := logger.NewChild(logging.Settings{Prefix: "http server: "})
serverLogger := logger.New(log.SetComponent("http server"))
server := server.New(ctx, address, config.Server.RootURL, db, serverLogger, runner)
serverHandler, serverCtx, serverDone := goshutdown.NewGoRoutineHandler("server")
go server.Run(serverCtx, serverDone)
notify("Launched with " + strconv.Itoa(len(records)) + " records to watch")

backupHandler, backupCtx, backupDone := goshutdown.NewGoRoutineHandler("backup")
backupLogger := logger.New(log.SetComponent("backup"))
go backupRunLoop(backupCtx, backupDone, config.Backup.Period, config.Paths.DataDir, config.Backup.Directory,
logger.NewChild(logging.Settings{Prefix: "backup: "}), timeNow)
backupLogger, timeNow)

shutdownGroup := goshutdown.NewGroupHandler("")
shutdownGroup.Add(runnerHandler, healthServerHandler, serverHandler, backupHandler)
Expand All @@ -271,8 +272,13 @@ func _main(ctx context.Context, env params.Interface, args []string, logger logg
return nil
}

type InfoErroer interface {
Info(s string)
Error(s string)
}

func backupRunLoop(ctx context.Context, done chan<- struct{}, backupPeriod time.Duration,
dataDir, outputDir string, logger logging.Logger, timeNow func() time.Time) {
dataDir, outputDir string, logger InfoErroer, timeNow func() time.Time) {
defer close(done)
if backupPeriod == 0 {
logger.Info("disabled")
Expand Down
9 changes: 5 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ require (
github.com/qdm12/golibs v0.0.0-20210822203818-5c568b0777b6
github.com/qdm12/goshutdown v0.3.0
github.com/qdm12/gosplash v0.1.0
github.com/stretchr/testify v1.7.0
github.com/qdm12/log v0.1.0
github.com/stretchr/testify v1.7.1
google.golang.org/api v0.96.0
)

require (
cloud.google.com/go/compute v1.7.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fatih/color v1.12.0 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
github.com/golang/protobuf v1.5.2 // indirect
Expand All @@ -28,8 +29,8 @@ require (
github.com/googleapis/gax-go/v2 v2.4.0 // indirect
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mattn/go-colorable v0.1.9 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/nxadm/tail v1.4.6 // indirect
Expand Down
14 changes: 10 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,9 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
github.com/fatih/color v1.6.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc=
github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
Expand Down Expand Up @@ -290,13 +291,15 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN
github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.1.42 h1:gWGe42RGaIqXQZ+r3WUGEKBEtvPHY2SXo4dqixDNxuY=
github.com/miekg/dns v1.1.42/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
Expand Down Expand Up @@ -348,6 +351,8 @@ github.com/qdm12/goshutdown v0.3.0 h1:pqBpJkdwlZlfTEx4QHtS8u8CXx6pG0fVo6S1N0MpSE
github.com/qdm12/goshutdown v0.3.0/go.mod h1:EqZ46No00kCTZ5qzdd3qIzY6ayhMt24QI8Mh8LVQYmM=
github.com/qdm12/gosplash v0.1.0 h1:Sfl+zIjFZFP7b0iqf2l5UkmEY97XBnaKkH3FNY6Gf7g=
github.com/qdm12/gosplash v0.1.0/go.mod h1:+A3fWW4/rUeDXhY3ieBzwghKdnIPFJgD8K3qQkenJlw=
github.com/qdm12/log v0.1.0 h1:jYBd/xscHYpblzZAd2kjZp2YmuYHjAAfbTViJWxoPTw=
github.com/qdm12/log v0.1.0/go.mod h1:Vchi5M8uBvHfPNIblN4mjXn/oSbiWguQIbsgF1zdQPI=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
Expand Down Expand Up @@ -381,8 +386,9 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/twitchyliquid64/golang-asm v0.0.0-20190126203739-365674df15fc/go.mod h1:NoCfSFWosfqMqmmD7hApkirIK9ozpHjxRnRxs1l413A=
Expand Down
3 changes: 2 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ func (c *Config) Get(env params.Interface) (warnings []string, err error) {
return warnings, err
}

if err := c.Logger.get(env); err != nil {
c.Logger, err = readLog()
if err != nil {
return warnings, err
}

Expand Down
66 changes: 56 additions & 10 deletions internal/config/logger.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,73 @@
package config

import (
"errors"
"fmt"
"os"
"strings"

"github.com/qdm12/golibs/logging"
"github.com/qdm12/golibs/params"
"github.com/qdm12/log"
)

type Logger struct {
Caller logging.Caller
Level logging.Level
Caller bool
Level log.Level
}

func (l *Logger) get(env params.Interface) (err error) {
l.Caller, err = env.LogCaller("LOG_CALLER", params.Default("hidden"))
var (
ErrLogCallerNotValid = errors.New("LOG_CALLER value is not valid")
)

func readLog() (settings Logger, err error) {
callerString := os.Getenv("LOG_CALLER")
switch callerString {
case "":
case "hidden":
case "short":
settings.Caller = true
default:
return settings, fmt.Errorf("%w: "+
`%q must be one of "", "hidden" or "short"`,
ErrLogCallerNotValid, callerString)
}

settings.Level, err = readLogLevel()
if err != nil {
return fmt.Errorf("%w: for environment variable LOG_CALLER", err)
return settings, err
}

return settings, nil
}

func readLogLevel() (level log.Level, err error) {
s := os.Getenv("LOG_LEVEL")
if s == "" {
return log.LevelInfo, nil
}

l.Level, err = env.LogLevel("LOG_LEVEL", params.Default("info"))
level, err = parseLogLevel(s)
if err != nil {
return fmt.Errorf("%w: for environment variable LOG_LEVEL", err)
return level, fmt.Errorf("environment variable LOG_LEVEL: %w", err)
}

return err
return level, nil
}

var ErrLogLevelUnknown = errors.New("log level is unknown")

func parseLogLevel(s string) (level log.Level, err error) {
switch strings.ToLower(s) {
case "debug":
return log.LevelDebug, nil
case "info":
return log.LevelInfo, nil
case "warning":
return log.LevelWarn, nil
case "error":
return log.LevelError, nil
default:
return level, fmt.Errorf(
"%w: %q is not valid and can be one of debug, info, warning or error",
ErrLogLevelUnknown, s)
}
}
6 changes: 6 additions & 0 deletions internal/health/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,9 @@ type AllSelecter interface {
type LookupIPer interface {
LookupIP(ctx context.Context, network, host string) (ips []net.IP, err error)
}

type Logger interface {
Info(s string)
Warn(s string)
Error(s string)
}
6 changes: 2 additions & 4 deletions internal/health/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@ import (
"context"
"net/http"
"time"

"github.com/qdm12/golibs/logging"
)

type Server struct {
address string
logger logging.Logger
logger Logger
handler http.Handler
}

func NewServer(address string, logger logging.Logger, healthcheck func() error) *Server {
func NewServer(address string, logger Logger, healthcheck func() error) *Server {
handler := newHandler(healthcheck)
return &Server{
address: address,
Expand Down
10 changes: 7 additions & 3 deletions internal/params/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,22 @@ import (
"io/fs"
"os"

"github.com/qdm12/golibs/logging"
"github.com/qdm12/golibs/params"
)

type Reader struct {
logger logging.Logger
logger Logger
env envInterface
readFile func(filename string) ([]byte, error)
writeFile func(filename string, data []byte, perm fs.FileMode) (err error)
}

func NewReader(logger logging.Logger) *Reader {
type Logger interface {
Info(s string)
Debug(s string)
}

func NewReader(logger Logger) *Reader {
return &Reader{
logger: logger,
env: params.New(),
Expand Down
6 changes: 6 additions & 0 deletions internal/server/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@ type Database interface {
type UpdateForcer interface {
ForceUpdate(ctx context.Context) (errors []error)
}

type Logger interface {
Info(s string)
Warn(s string)
Error(s string)
}
6 changes: 2 additions & 4 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ import (
"context"
"net/http"
"time"

"github.com/qdm12/golibs/logging"
)

type Server struct {
address string
logger logging.Logger
logger Logger
handler http.Handler
}

func New(ctx context.Context, address, rootURL string, db Database,
logger logging.Logger, runner UpdateForcer) *Server {
logger Logger, runner UpdateForcer) *Server {
handler := newHandler(ctx, rootURL, db, runner)
return &Server{
address: address,
Expand Down
3 changes: 1 addition & 2 deletions internal/update/getip.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import (
"strconv"

"github.com/qdm12/ddns-updater/pkg/publicip/ipversion"
"github.com/qdm12/golibs/logging"
)

type getIPFunc func(ctx context.Context) (ip net.IP, err error)

func tryAndRepeatGettingIP(ctx context.Context, getIPFunc getIPFunc,
logger logging.Logger, version ipversion.IPVersion) (ip net.IP, err error) {
logger Logger, version ipversion.IPVersion) (ip net.IP, err error) {
const tries = 3
logMessagePrefix := "obtaining " + version.String() + " address"
for try := 0; try < tries; try++ {
Expand Down
7 changes: 7 additions & 0 deletions internal/update/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,10 @@ type Database interface {
type LookupIPer interface {
LookupIP(ctx context.Context, network, host string) (ips []net.IP, err error)
}

type Logger interface {
DebugLogger
Info(s string)
Warn(s string)
Error(s string)
}
8 changes: 4 additions & 4 deletions internal/update/logclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import (
"github.com/qdm12/ddns-updater/internal/settings/utils"
)

//go:generate mockgen -destination=mock_$GOPACKAGE/$GOFILE . Logger
//go:generate mockgen -destination=mock_$GOPACKAGE/$GOFILE . DebugLogger

type Logger interface {
type DebugLogger interface {
Debug(s string)
}

func makeLogClient(client *http.Client, logger Logger) (newClient *http.Client) {
func makeLogClient(client *http.Client, logger DebugLogger) (newClient *http.Client) {
newClient = &http.Client{
Timeout: client.Timeout,
}
Expand All @@ -43,7 +43,7 @@ func makeLogClient(client *http.Client, logger Logger) (newClient *http.Client)

type loggingRoundTripper struct {
proxied http.RoundTripper
logger Logger
logger DebugLogger
}

func (lrt *loggingRoundTripper) RoundTrip(request *http.Request) (
Expand Down
Loading

0 comments on commit 727f3ff

Please sign in to comment.