refactor: use slog instead of log
Some checks are pending
Go CI Pipeline / ci (push) Waiting to run
Release Builds / GoReleaser build (push) Successful in 1m4s

This commit is contained in:
Patryk Hegenberg 2025-06-11 22:41:48 +02:00
parent fcffccc145
commit d8743e54c1
8 changed files with 180 additions and 165 deletions

View file

@ -3,7 +3,7 @@ package main
import (
"database/sql"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
@ -37,7 +37,7 @@ func NewTimeStore(cfg Config) (*TimeStore, error) {
return nil, fmt.Errorf("could not determine database path: %w", err)
}
log.Printf("INFO: Using database at: %s", dbPath)
slog.Info(fmt.Sprintf("Using database at: %s", dbPath))
db, err := sql.Open("sqlite", fmt.Sprintf("%s?_pragma=journal_mode(WAL)", dbPath))
if err != nil {
@ -66,7 +66,7 @@ func NewTimeStore(cfg Config) (*TimeStore, error) {
createIndexSQL := `CREATE INDEX IF NOT EXISTS idx_time_entries_start_time ON time_entries (start_time);`
if _, err = db.Exec(createIndexSQL); err != nil {
log.Printf("WARN: Failed to create index on start_time: %v", err)
slog.Warn(fmt.Sprintf("Failed to create index on start_time: %v", err))
}
return &TimeStore{db: db, dbPath: dbPath}, nil
@ -80,7 +80,7 @@ func ensureDatabasePath(_ Config) (string, error) {
workConfigDir := filepath.Join(configDir, "work")
dbPath := filepath.Join(workConfigDir, "worktime.sqlite")
if err := os.MkdirAll(workConfigDir, 0750); err != nil {
if err := os.MkdirAll(workConfigDir, 0o750); err != nil {
return "", fmt.Errorf("failed to create config directory '%s': %w", workConfigDir, err)
}
@ -89,7 +89,7 @@ func ensureDatabasePath(_ Config) (string, error) {
func (ts *TimeStore) Close() error {
if ts.db != nil {
log.Printf("INFO: Closing database connection to %s", ts.dbPath)
slog.Info(fmt.Sprintf("Closing database connection to %s", ts.dbPath))
return ts.db.Close()
}
return nil
@ -108,7 +108,7 @@ func (ts *TimeStore) stopCurrentEntry(now time.Time) (bool, error) {
}
if rowsAffected > 1 {
log.Printf("WARN: Stopped %d entries. Expected 0 or 1. Manual DB check might be needed.", rowsAffected)
slog.Warn(fmt.Sprintf("Stopped %d entries. Expected 0 or 1. Manual DB check might be needed.", rowsAffected))
}
return rowsAffected > 0, nil
}
@ -124,7 +124,7 @@ func (ts *TimeStore) StartTracking(tag string) error {
return err
}
if stopped {
log.Println("INFO: Stopped previous time entry.")
slog.Info("Stopped previous time entry.")
}
query := `INSERT INTO time_entries (tag, start_time, end_time) VALUES (?, ?, NULL);`
@ -132,7 +132,7 @@ func (ts *TimeStore) StartTracking(tag string) error {
if err != nil {
return fmt.Errorf("failed to start tracking tag '%s': %w", tag, err)
}
log.Printf("INFO: Started tracking: %s at %s", tag, now.Format(time.RFC3339))
slog.Info(fmt.Sprintf("Started tracking: %s at %s", tag, now.Format(time.RFC3339)))
return nil
}
@ -143,9 +143,9 @@ func (ts *TimeStore) StopTracking() error {
return err
}
if stopped {
log.Printf("INFO: Stopped tracking at %s", now.Format(time.RFC3339))
slog.Info(fmt.Sprintf("Stopped tracking at %s", now.Format(time.RFC3339)))
} else {
log.Println("INFO: No active time entry found to stop.")
slog.Info("No active time entry found to stop.")
}
return nil
}
@ -273,7 +273,7 @@ func getTimeRangeFromPeriod(period string) (time.Time, time.Time) {
end := start.AddDate(0, 0, 1)
return start, end
}
log.Printf("WARN: Unrecognized period string '%s'. Cannot calculate time range.", period)
slog.Warn(fmt.Sprintf("Unrecognized period string '%s'. Cannot calculate time range.", period))
return time.Time{}, time.Time{}
}
}
@ -329,14 +329,14 @@ func (ts *TimeStore) ShowSummary(period string) error {
}
func (ts *TimeStore) ExportSummary(filename string) error {
log.Printf("INFO: Starting export to '%s'...", filename)
slog.Info(fmt.Sprintf("Starting export to '%s'...", filename))
currentYear := time.Now().Year()
location := time.Local
yearStart := time.Date(currentYear, 1, 1, 0, 0, 0, 0, location)
yearEnd := yearStart.AddDate(1, 0, 0)
log.Printf("INFO: Exporting data for year %d (%s to %s)", currentYear, yearStart.Format("2006-01-02"), yearEnd.Format("2006-01-02"))
slog.Info(fmt.Sprintf("Exporting data for year %d (%s to %s)", currentYear, yearStart.Format("2006-01-02"), yearEnd.Format("2006-01-02")))
query := `
SELECT id, tag, start_time, end_time
@ -362,7 +362,7 @@ func (ts *TimeStore) ExportSummary(filename string) error {
if err = rows.Err(); err != nil {
return fmt.Errorf("error during export row iteration: %w", err)
}
log.Printf("INFO: Found %d potentially relevant time entries for year %d.", len(entries), currentYear)
slog.Info(fmt.Sprintf("Found %d potentially relevant time entries for year %d.", len(entries), currentYear))
dailySummaries, err := aggregateEntriesToDailySummaries(entries, yearStart, yearEnd)
if err != nil {
@ -372,17 +372,17 @@ func (ts *TimeStore) ExportSummary(filename string) error {
excelEntries := convertDailyToExcelEntries(dailySummaries)
if len(excelEntries) == 0 {
log.Println("WARN: No daily summaries generated for the export period.")
slog.Warn("No daily summaries generated for the export period.")
fmt.Println("No data available to generate the export for the specified period.")
return nil
}
log.Printf("INFO: Generated %d daily entries for the Excel export.", len(excelEntries))
slog.Info(fmt.Sprintf("Generated %d daily entries for the Excel export.", len(excelEntries)))
if err := writeExcelSheet(excelEntries, filename); err != nil { // Aufruf der geänderten Funktion
return fmt.Errorf("failed to write excel sheet '%s': %w", filename, err)
}
log.Printf("INFO: Successfully exported timetable to %s", filename)
slog.Info(fmt.Sprintf("Successfully exported timetable to %s", filename))
fmt.Printf("Successfully exported timetable to %s\n", filename)
return nil
}
@ -399,16 +399,16 @@ func (ts *TimeStore) LogFullDay(tag string, date time.Time) error {
dayEnd := dayStart.Add(24 * time.Hour)
dayStr := dayStart.Format("2006-01-02")
log.Printf("INFO: Attempting to log '%s' for the full day %s", tag, dayStr)
slog.Info(fmt.Sprintf("Attempting to log '%s' for the full day %s", tag, dayStr))
// 1. Stoppe den aktuell laufenden Timer (falls vorhanden)
// Wir verwenden dayStart als Zeitpunkt für das Stoppen, um Konsistenz zu wahren
stopped, err := ts.stopCurrentEntry(dayStart)
if err != nil {
// Nur loggen, weitermachen. Der Nutzer will diesen Tag ja explizit setzen.
log.Printf("WARN: Failed to stop current entry before logging full day '%s': %v", tag, err)
slog.Warn(fmt.Sprintf("Failed to stop current entry before logging full day '%s': %v", tag, err))
} else if stopped {
log.Printf("INFO: Stopped active timer before logging '%s' for %s.", tag, dayStr)
slog.Info(fmt.Sprintf("Stopped active timer before logging '%s' for %s.", tag, dayStr))
}
tx, err := ts.db.Begin()
@ -436,7 +436,7 @@ func (ts *TimeStore) LogFullDay(tag string, date time.Time) error {
}
titleCaser := cases.Title(language.English)
log.Printf("INFO: Successfully logged full day entry: Tag='%s', Start='%s', End='%s'", tag, dayStart.Format(time.RFC3339), dayEnd.Format(time.RFC3339))
slog.Info(fmt.Sprintf("Successfully logged full day entry: Tag='%s', Start='%s', End='%s'", tag, dayStart.Format(time.RFC3339), dayEnd.Format(time.RFC3339)))
fmt.Printf("Successfully logged '%s' for %s.\n", titleCaser.String(tag), dayStr) // Benutzerfeedback
return nil
}