Skip to content

Commit

Permalink
chore: add additional logging internal functions
Browse files Browse the repository at this point in the history
Don't want to fetch each time.
  • Loading branch information
kashalls committed Jun 13, 2024
1 parent ea555ee commit 1662d8f
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 48 deletions.
3 changes: 1 addition & 2 deletions cmd/webhook/init/configuration/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ type Config struct {
// Init sets up configuration by reading set environmental variables
func Init() Config {
cfg := Config{}
logger := logging.GetLogger()
if err := env.Parse(&cfg); err != nil {
logger.Error("error reading configuration from environment", zap.Error(err))
logging.Error("error reading configuration from environment", zap.Error(err))
}
return cfg
}
3 changes: 1 addition & 2 deletions cmd/webhook/init/dnsprovider/dnsprovider.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ func Init(config configuration.Config) (provider.Provider, error) {
if strings.HasSuffix(createMsg, "with ") {
createMsg += "no kind of domain filters"
}
logger := logging.GetLogger()
logger.Info(createMsg)
logging.Info(createMsg)

unifiConfig := unifi.Config{}
if err := env.Parse(&unifiConfig); err != nil {
Expand Down
24 changes: 18 additions & 6 deletions cmd/webhook/init/logging/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,22 @@ func Init() {
defer logger.Sync()
}

// GetLogger returns the initialized logger instance
func GetLogger() *zap.Logger {
if logger == nil {
Init() // Initialize if not already done
}
return logger
func Info(message string, fields ...zap.Field) {
logger.Info(message, fields...)
}

func Debug(message string, fields ...zap.Field) {
logger.Debug(message, fields...)
}

func Error(message string, fields ...zap.Field) {
logger.Error(message, fields...)
}

func Fatal(message string, fields ...zap.Field) {
logger.Fatal(message, fields...)
}

func With(fields ...zap.Field) *zap.Logger {
return logger.With(fields...)
}
18 changes: 7 additions & 11 deletions cmd/webhook/init/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ func ReadinessHandler(w http.ResponseWriter, r *http.Request) {

// Init initializes the http server
func Init(config configuration.Config, p *webhook.Webhook) (*http.Server, *http.Server) {
logger := logging.GetLogger()

mainRouter := chi.NewRouter()
mainRouter.Get("/", p.Negotiate)
mainRouter.Get("/records", p.Records)
Expand All @@ -43,9 +41,9 @@ func Init(config configuration.Config, p *webhook.Webhook) (*http.Server, *http.

mainServer := createHTTPServer(fmt.Sprintf("%s:%d", config.ServerHost, config.ServerPort), mainRouter, config.ServerReadTimeout, config.ServerWriteTimeout)
go func() {
logger.Info("starting webhook server", zap.String("address", mainServer.Addr))
logging.Info("starting webhook server", zap.String("address", mainServer.Addr))
if err := mainServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("unable to start webhook server", zap.String("address", mainServer.Addr), zap.Error(err))
logging.Error("unable to start webhook server", zap.String("address", mainServer.Addr), zap.Error(err))
}
}()

Expand All @@ -56,9 +54,9 @@ func Init(config configuration.Config, p *webhook.Webhook) (*http.Server, *http.

healthServer := createHTTPServer("0.0.0.0:8080", healthRouter, config.ServerReadTimeout, config.ServerWriteTimeout)
go func() {
logger.Info("starting health server", zap.String("address", healthServer.Addr))
logging.Info("starting health server", zap.String("address", healthServer.Addr))
if err := healthServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("unable to start health server", zap.String("address", healthServer.Addr), zap.Error(err))
logging.Error("unable to start health server", zap.String("address", healthServer.Addr), zap.Error(err))
}
}()

Expand All @@ -76,21 +74,19 @@ func createHTTPServer(addr string, hand http.Handler, readTimeout, writeTimeout

// ShutdownGracefully gracefully shutdown the http server
func ShutdownGracefully(mainServer *http.Server, healthServer *http.Server) {
logger := logging.GetLogger()

sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-sigCh

logger.Info("shutting down servers due to received signal", zap.Any("signal", sig))
logging.Info("shutting down servers due to received signal", zap.Any("signal", sig))
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

if err := mainServer.Shutdown(ctx); err != nil {
logger.Error("error shutting down main server", zap.Error(err))
logging.Error("error shutting down main server", zap.Error(err))
}

if err := healthServer.Shutdown(ctx); err != nil {
logger.Error("error shutting down health server", zap.Error(err))
logging.Error("error shutting down health server", zap.Error(err))
}
}
3 changes: 1 addition & 2 deletions cmd/webhook/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,11 @@ func main() {
fmt.Printf(banner, Version, Gitsha)

logging.Init()
logger := logging.GetLogger()

config := configuration.Init()
provider, err := dnsprovider.Init(config)
if err != nil {
logger.Error("failed to initialize provider", zap.Error(err))
logging.Error("failed to initialize provider", zap.Error(err))
}

main, health := server.Init(config, webhook.New(provider))
Expand Down
21 changes: 8 additions & 13 deletions internal/unifi/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ func newUnifiClient(config *Config) (*httpClient, error) {

// login performs a login request to the UniFi controller.
func (c *httpClient) login() error {
logger := logging.GetLogger()
jsonBody, err := json.Marshal(Login{
Username: c.Config.User,
Password: c.Config.Password,
Expand All @@ -81,7 +80,7 @@ func (c *httpClient) login() error {
// Check if the login was successful
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
logger.Error("login failed", zap.String("status", resp.Status), zap.String("response", string(respBody)))
logging.Error("login failed", zap.String("status", resp.Status), zap.String("response", string(respBody)))
return fmt.Errorf("login failed: %s", resp.Status)
}

Expand All @@ -95,8 +94,7 @@ func (c *httpClient) login() error {

// doRequest makes an HTTP request to the UniFi controller.
func (c *httpClient) doRequest(method, path string, body io.Reader) (*http.Response, error) {
logger := logging.GetLogger()
logger.Debug(fmt.Sprintf("making %s request to %s", method, path))
logging.Debug(fmt.Sprintf("making %s request to %s", method, path))

req, err := http.NewRequest(method, path, body)
if err != nil {
Expand All @@ -114,11 +112,11 @@ func (c *httpClient) doRequest(method, path string, body io.Reader) (*http.Respo
c.csrf = csrf
}

logger.Debug(fmt.Sprintf("response code from %s request to %s: %d", method, path, resp.StatusCode))
logging.Debug(fmt.Sprintf("response code from %s request to %s: %d", method, path, resp.StatusCode))

// If the status code is 401, re-login and retry the request
if resp.StatusCode == http.StatusUnauthorized {
logger.Debug("Received 401 Unauthorized, re-login required")
logging.Debug("Received 401 Unauthorized, re-login required")
if err := c.login(); err != nil {
return nil, err
}
Expand All @@ -140,7 +138,6 @@ func (c *httpClient) doRequest(method, path string, body io.Reader) (*http.Respo

// GetEndpoints retrieves the list of DNS records from the UniFi controller.
func (c *httpClient) GetEndpoints() ([]DNSRecord, error) {
logger := logging.GetLogger()
resp, err := c.doRequest(
http.MethodGet,
FormatUrl(unifiRecordPath, c.Config.Host, c.Config.Site),
Expand All @@ -156,14 +153,13 @@ func (c *httpClient) GetEndpoints() ([]DNSRecord, error) {
return nil, err
}

logger.Debug(fmt.Sprintf("retrieved records: %+v", records))
logging.Debug(fmt.Sprintf("retrieved records: %+v", records))

return records, nil
}

// CreateEndpoint creates a new DNS record in the UniFi controller.
func (c *httpClient) CreateEndpoint(endpoint *endpoint.Endpoint) (*DNSRecord, error) {
logger := logging.GetLogger()
jsonBody, err := json.Marshal(DNSRecord{
Enabled: true,
Key: endpoint.DNSName,
Expand All @@ -189,7 +185,7 @@ func (c *httpClient) CreateEndpoint(endpoint *endpoint.Endpoint) (*DNSRecord, er
return nil, err
}

logger.Debug(fmt.Sprintf("created record: %+v", record))
logging.Debug(fmt.Sprintf("created record: %+v", record))

return &record, nil
}
Expand Down Expand Up @@ -230,7 +226,6 @@ func (c *httpClient) lookupIdentifier(key, recordType string) (*DNSRecord, error

// setHeaders sets the headers for the HTTP request.
func (c *httpClient) setHeaders(req *http.Request) {
logger := logging.GetLogger()
// Add the saved CSRF header.
req.Header.Set("X-CSRF-Token", c.csrf)
req.Header.Add("Accept", "application/json")
Expand All @@ -239,8 +234,8 @@ func (c *httpClient) setHeaders(req *http.Request) {
// Log the request URL and cookies
if c.Client.Jar != nil {
parsedURL, _ := url.Parse(req.URL.String())
logger.Debug(fmt.Sprintf("Requesting %s cookies: %d", req.URL, len(c.Client.Jar.Cookies(parsedURL))))
logging.Debug(fmt.Sprintf("Requesting %s cookies: %d", req.URL, len(c.Client.Jar.Cookies(parsedURL))))
} else {
logger.Debug(fmt.Sprintf("Requesting %s", req.URL))
logging.Debug(fmt.Sprintf("Requesting %s", req.URL))
}
}
17 changes: 5 additions & 12 deletions pkg/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ const (
contentTypePlaintext = "text/plain"
acceptHeader = "Accept"
varyHeader = "Vary"
logFieldRequestPath = "requestPath"
logFieldRequestMethod = "requestMethod"
logFieldError = "error"
)

// Webhook for external dns provider
Expand Down Expand Up @@ -157,14 +154,12 @@ func (p *Webhook) ApplyChanges(w http.ResponseWriter, r *http.Request) {

// AdjustEndpoints handles the post request for adjusting endpoints
func (p *Webhook) AdjustEndpoints(w http.ResponseWriter, r *http.Request) {
logger := logging.GetLogger()

if err := p.contentTypeHeaderCheck(w, r); err != nil {
logger.Error("content-type header check failed", zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
logging.Error("content-type header check failed", zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
return
}
if err := p.acceptHeaderCheck(w, r); err != nil {
logger.Error("accept header check failed", zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
logging.Error("accept header check failed", zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
return
}

Expand All @@ -181,7 +176,7 @@ func (p *Webhook) AdjustEndpoints(w http.ResponseWriter, r *http.Request) {
return
}

logger.Debug("requesting adjust endpoints count", zap.Int("endpoints", len(pve)))
logging.Debug("requesting adjust endpoints count", zap.Int("endpoints", len(pve)))
pve, err := p.provider.AdjustEndpoints(pve)
if err != nil {
w.Header().Set(contentTypeHeader, contentTypePlaintext)
Expand All @@ -190,7 +185,7 @@ func (p *Webhook) AdjustEndpoints(w http.ResponseWriter, r *http.Request) {
}
out, _ := json.Marshal(&pve)

logger.Debug("return adjust endpoints response", zap.Int("endpoints", len(pve)))
logging.Debug("return adjust endpoints response", zap.Int("endpoints", len(pve)))

w.Header().Set(contentTypeHeader, string(mediaTypeVersion1))
w.Header().Set(varyHeader, contentTypeHeader)
Expand Down Expand Up @@ -221,7 +216,5 @@ func (p *Webhook) Negotiate(w http.ResponseWriter, r *http.Request) {
}

func requestLog(r *http.Request) *zap.Logger {
logger := logging.GetLogger()

return logger.With(zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
return logging.With(zap.String("req_method", r.Method), zap.String("req_path", r.URL.Path))
}

0 comments on commit 1662d8f

Please sign in to comment.