Skip to content

Commit

Permalink
replace log.Print* with Zap logger
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmasek committed Feb 15, 2025
1 parent ecdf764 commit 64820f0
Show file tree
Hide file tree
Showing 12 changed files with 78 additions and 53 deletions.
5 changes: 4 additions & 1 deletion cmd/debug.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package cmd

import (
"fmt"

"github.com/davidmasek/beacon/logging"
"github.com/spf13/cobra"
"go.uber.org/zap"
)

var debugCmd = &cobra.Command{
Expand All @@ -14,7 +17,7 @@ var debugCmd = &cobra.Command{
logger.Debugw("Debug message", "foo", 42)
logger.Infow("Info message", "foo", 42)
logger.Warnw("Warn message", "foo", 42)
logger.Errorw("Error message", "foo", 42)
logger.Errorw("Error message", zap.Error(fmt.Errorf("big bad")))
cmd.Println("Done")
return nil
},
Expand Down
8 changes: 5 additions & 3 deletions conf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"time"

"github.com/caarlos0/env/v11"
"github.com/davidmasek/beacon/logging"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -220,6 +220,7 @@ func (tz *TzLocation) UnmarshalYAML(value *yaml.Node) error {

// Parse config from YAML and override using ENV variables
func ConfigFromBytes(data []byte) (*Config, error) {
logger := logging.Get()
config := NewConfig()
err := yaml.Unmarshal(data, config)
if err != nil {
Expand All @@ -231,12 +232,13 @@ func ConfigFromBytes(data []byte) (*Config, error) {
if err != nil {
return nil, err
}
log.Println(">>>>", config, "<<<<")
logger.Infow("loaded config", "config", config)
return config, err
}

func configFromFile(configFile string) (*Config, error) {
log.Printf("reading config from %q\n", configFile)
logger := logging.Get()
logger.Infow("reading config from file", "path", configFile)
data, err := os.ReadFile(configFile)
if err != nil {
return nil, err
Expand Down
6 changes: 4 additions & 2 deletions handlers/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import (
"embed"
"html/template"
"io"
"log"
"os"

"github.com/davidmasek/beacon/logging"
)

//go:embed report.template.html
Expand All @@ -27,7 +28,8 @@ func WriteReport(reports []ServiceReport, wr io.Writer) error {
}

func WriteReportToFile(reports []ServiceReport, filename string) error {
log.Printf("Writing report to %s", filename)
logger := logging.Get()
logger.Infow("Writing report to file", "path", filename)
// Create or truncate the output file
file, err := os.Create(filename)
if err != nil {
Expand Down
12 changes: 7 additions & 5 deletions handlers/mail.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@ import (
"bytes"
"crypto/tls"
"fmt"
"log"
"strings"

"github.com/davidmasek/beacon/conf"
"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/monitor"
"github.com/wneessen/go-mail"
"go.uber.org/zap"
)

func SendReport(reports []ServiceReport, emailConfig *conf.EmailConfig) error {
var buffer bytes.Buffer

log.Printf("[SMTPMailer] Generating report")
logger := logging.Get()
logger.Info("Generating report")
err := WriteReport(reports, &buffer)
if err != nil {
return err
Expand Down Expand Up @@ -52,7 +53,8 @@ func SendReport(reports []ServiceReport, emailConfig *conf.EmailConfig) error {
}

func SendMail(emailConfig *conf.EmailConfig, subject string, body string) error {
log.Printf("Sending email with subject %q to %q", subject, emailConfig.SendTo)
logger := logging.Get()
logger.Infow("Sending email", "subject", subject, "to", emailConfig.SendTo)

message := mail.NewMsg()
if err := message.From(emailConfig.Sender); err != nil {
Expand Down Expand Up @@ -87,7 +89,7 @@ func SendMail(emailConfig *conf.EmailConfig, subject string, body string) error
err = client.DialAndSend(message)

if err != nil {
log.Printf("Failed to send email: %v", err)
logger.Errorw("Failed to send email", "subject", subject, "to", emailConfig.SendTo, zap.Error(err))
}
return err
}
10 changes: 6 additions & 4 deletions handlers/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package handlers
import (
"errors"
"fmt"
"log"
"strings"
"time"

"github.com/davidmasek/beacon/conf"
"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/monitor"
"github.com/davidmasek/beacon/storage"
"go.uber.org/zap"
)

// Calculate when the next report should happen based on last report time.
Expand Down Expand Up @@ -43,6 +44,7 @@ func NextReportTime(config *conf.Config, lastReportTime time.Time) time.Time {
}

func GenerateReport(db storage.Storage, config *conf.Config) ([]ServiceReport, error) {
logger := logging.Get()
reports := make([]ServiceReport, 0)

services := config.AllServices()
Expand All @@ -52,16 +54,16 @@ func GenerateReport(db storage.Storage, config *conf.Config) ([]ServiceReport, e
}

for _, service := range services {
log.Println("Checking service", service)

healthCheck, err := db.LatestHealthCheck(service.Id)
var serviceStatus monitor.ServiceStatus
if err == nil {
serviceStatus = checkConfig.GetServiceStatus(healthCheck)
} else {
log.Println("[ERROR]", err)
logger.Errorw("error checking service status", "service", service, zap.Error(err))
serviceStatus = monitor.STATUS_OTHER
}
log.Println(" - Service status:", serviceStatus)
logger.Debug("Checked service", "service", service, "status", serviceStatus)

reports = append(reports, ServiceReport{
ServiceId: service.Id, ServiceStatus: serviceStatus, LatestHealthCheck: healthCheck,
Expand Down
6 changes: 3 additions & 3 deletions handlers/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ package handlers

import (
"fmt"
"log"
"net/http"

"github.com/davidmasek/beacon/conf"
"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/monitor"
"github.com/davidmasek/beacon/storage"
)

func StartServer(db storage.Storage, config *conf.Config) (*http.Server, error) {
logger := logging.Get()
mux := http.NewServeMux()

mux.HandleFunc("/{$}", handleIndex(db, config))
Expand All @@ -27,8 +28,7 @@ func StartServer(db storage.Storage, config *conf.Config) (*http.Server, error)
go func() {
fmt.Printf("Starting UI server on http://localhost:%d\n", port)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Print(err)
panic(err)
logger.Panic(err)
}
}()
return server, nil
Expand Down
21 changes: 12 additions & 9 deletions handlers/server_gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"runtime/debug"
"time"

"github.com/davidmasek/beacon/conf"
"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/monitor"
"github.com/davidmasek/beacon/storage"
"go.uber.org/zap"
)

//go:embed templates/*
Expand All @@ -21,6 +22,7 @@ var TEMPLATES embed.FS
// Show services status
func handleIndex(db storage.Storage, config *conf.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger := logging.Get()
// Prepare a map to hold services and their heartbeats
type ServiceStatus struct {
// Needed as HealthCheck can be nil
Expand All @@ -31,10 +33,10 @@ func handleIndex(db storage.Storage, config *conf.Config) http.HandlerFunc {
var services []ServiceStatus
serviceChecker := DefaultServiceChecker()
for _, serviceCfg := range config.AllServices() {
log.Println("Querying", serviceCfg.Id)
logger.Debugw("Querying", "service", serviceCfg.Id)
healthCheck, err := db.LatestHealthCheck(serviceCfg.Id)
if err != nil {
log.Printf("Failed to load health check: %s", err)
logger.Errorw("Failed to load health check", "service", serviceCfg.Id, zap.Error(err))
http.Error(w, "Failed to load health check", http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -73,7 +75,7 @@ func handleIndex(db storage.Storage, config *conf.Config) http.HandlerFunc {
filepath.Join("templates", "common.css"),
)
if err != nil {
log.Printf("Error parsing template: %v", err)
logger.Errorw("Error parsing template", zap.Error(err))
http.Error(w, "Failed to render page", http.StatusInternalServerError)
return
}
Expand All @@ -83,7 +85,7 @@ func handleIndex(db storage.Storage, config *conf.Config) http.HandlerFunc {
"CurrentPage": "home",
})
if err != nil {
log.Println("Failed to render", err)
logger.Errorw("Error rendering template", zap.Error(err))
http.Error(w, "Failed to render page", http.StatusInternalServerError)
}
}
Expand All @@ -92,22 +94,23 @@ func handleIndex(db storage.Storage, config *conf.Config) http.HandlerFunc {
// Show services status
func handleAbout(db storage.Storage, config *conf.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger := logging.Get()
tmpl := template.New("about.html")
tmpl, err := tmpl.ParseFS(TEMPLATES,
filepath.Join("templates", "about.html"),
filepath.Join("templates", "header.html"),
filepath.Join("templates", "common.css"),
)
if err != nil {
log.Printf("Error parsing template: %v", err)
logger.Errorw("Error parsing template", zap.Error(err))
http.Error(w, "Failed to render page", http.StatusInternalServerError)
return
}

timeFormat := "15:04 Monday 02 January"
lastReport, err := db.LatestTaskLog("report")
if err != nil {
log.Println("DB error", err)
logger.Errorw("DB error", zap.Error(err))
http.Error(w, "Server error, please try again later", http.StatusInternalServerError)
return
}
Expand All @@ -128,7 +131,7 @@ func handleAbout(db storage.Storage, config *conf.Config) http.HandlerFunc {
if lastReport == nil {
lastReportTime = "never"
nextReportAfter = "error"
log.Println("DB not properly initialized! No report task found")
logger.Error("DB not properly initialized! No report task found")
} else if lastReport.Status == string(TASK_SENTINEL) {
lastReportTime = "never"
nextReportAfter = NextReportTime(config, lastReport.Timestamp).
Expand Down Expand Up @@ -160,7 +163,7 @@ func handleAbout(db storage.Storage, config *conf.Config) http.HandlerFunc {
"BeaconVersion": beaconVersion,
})
if err != nil {
log.Println("Failed to render", err)
logger.Errorw("Failed to render", zap.Error(err))
http.Error(w, "Failed to render page", http.StatusInternalServerError)
}
}
Expand Down
11 changes: 6 additions & 5 deletions handlers/status.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package handlers

import (
"log"
"time"

"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/monitor"
"github.com/davidmasek/beacon/storage"
)
Expand All @@ -22,25 +22,26 @@ func DefaultServiceChecker() ServiceChecker {
//
// TODO: maybe should be used like HealthCheck.GetStatus(config) or smth
func (config *ServiceChecker) GetServiceStatus(latestHealthCheck *storage.HealthCheck) monitor.ServiceStatus {
logger := logging.Get()
if latestHealthCheck == nil {
log.Println("[GetServiceStatus] no health check found")
logger.Debug("[GetServiceStatus] no health check found")
return monitor.STATUS_FAIL
}
timeAgo := time.Since(latestHealthCheck.Timestamp)
log.Printf("timeout: %s, timeAgo: %s", config.Timeout.String(), timeAgo.String())
logger.Debug("timeout: %s, timeAgo: %s", config.Timeout.String(), timeAgo.String())
if timeAgo > config.Timeout {
return monitor.STATUS_FAIL
}

if errorMeta, exists := latestHealthCheck.Metadata["error"]; exists {
if errorMeta != "" {
log.Printf("[GetServiceStatus] error found: %q", errorMeta)
logger.Debug("[GetServiceStatus] error found: %q", errorMeta)
return monitor.STATUS_FAIL
}
}
if statusMeta, exists := latestHealthCheck.Metadata["status"]; exists {
if statusMeta != string(monitor.STATUS_OK) {
log.Printf("[GetServiceStatus] status not OK: %q != %q", statusMeta, string(monitor.STATUS_OK))
logger.Debug("[GetServiceStatus] status not OK: %q != %q", statusMeta, string(monitor.STATUS_OK))
return monitor.STATUS_FAIL
}
}
Expand Down
8 changes: 5 additions & 3 deletions monitor/heartbeat_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package monitor

import (
"encoding/json"
"log"
"net/http"
"time"

_ "github.com/mattn/go-sqlite3"

"github.com/davidmasek/beacon/logging"
"github.com/davidmasek/beacon/storage"
)

Expand All @@ -29,6 +29,7 @@ func RegisterHeartbeatHandlers(db storage.Storage, mux *http.ServeMux) {

func handleBeat(db storage.Storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger := logging.Get()
serviceId := r.PathValue("service_id")
if serviceId == "" {
http.Error(w, "Missing service_id", http.StatusBadRequest)
Expand All @@ -38,7 +39,7 @@ func handleBeat(db storage.Storage) http.HandlerFunc {
// Log the heartbeat to the database
nowStr, err := db.RecordHeartbeat(serviceId, now)
if err != nil {
log.Println("[ERROR]", err)
logger.Error(err)
http.Error(w, "Failed to log heartbeat", http.StatusInternalServerError)
return
}
Expand All @@ -57,6 +58,7 @@ func handleBeat(db storage.Storage) http.HandlerFunc {

func handleStatus(db storage.Storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger := logging.Get()
serviceId := r.PathValue("service_id")
if serviceId == "" {
http.Error(w, "Missing service_id", http.StatusBadRequest)
Expand All @@ -66,7 +68,7 @@ func handleStatus(db storage.Storage) http.HandlerFunc {
// Query the database for the latest heartbeat
timestamps, err := db.GetLatestHeartbeats(serviceId, 1)
if err != nil {
log.Println("[ERROR]", err)
logger.Error(err)
http.Error(w, "Failed to query database", http.StatusInternalServerError)
return
}
Expand Down
Loading

0 comments on commit 64820f0

Please sign in to comment.