Skip to content

Commit

Permalink
Merge pull request #13 from nugget/additional-cleanup
Browse files Browse the repository at this point in the history
Additional cleanup
  • Loading branch information
nugget authored Dec 29, 2024
2 parents 99510a2 + 5bb483e commit 4f368ed
Show file tree
Hide file tree
Showing 4 changed files with 234 additions and 155 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ linters-settings:
# - "default": report only the default slog logger
# https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global
# Default: ""
no-global: "all"
no-global: "default"
# Enforce using methods that accept a context.
# Values:
# - "": disabled
Expand Down
37 changes: 30 additions & 7 deletions examples/vehiclestats/vehiclestats.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,27 @@ import (
"github.com/nugget/roadtrip-go/roadtrip"
)

func main() {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
var (
logger *slog.Logger
logLevel *slog.LevelVar
)

func setupLogs() {
logLevel = new(slog.LevelVar)
logLevel.Set(slog.LevelInfo)

handlerOptions := &slog.HandlerOptions{
Level: logLevel,
}

logger = slog.New(slog.NewTextHandler(os.Stdout, handlerOptions))

slog.SetDefault(logger)
slog.SetLogLoggerLevel(slog.LevelInfo)
}

func main() {
setupLogs()

var debugMode = flag.Bool("v", false, "Verbose logging")
var filename = flag.String("file", "", "Road Trip vehicle CSV file")
Expand All @@ -24,13 +42,13 @@ func main() {
}

options := roadtrip.VehicleOptions{
Logger: logger,
LogLevel: slog.LevelInfo,
Logger: logger,
}

if *debugMode {
// AddSource: true here
options.LogLevel = slog.LevelDebug
slog.SetLogLoggerLevel(slog.LevelDebug)
logLevel.Set(slog.LevelDebug)
}

// Create a [roadtrip.Vehicle] object with contents from a Road Trip data file.
Expand All @@ -42,13 +60,18 @@ func main() {
os.Exit(1)
}

// logger.Info("Loaded vehicle", "vehicle", vehicle)
logger.Info("Loaded vehicle", "vehicle", vehicle)

totalFuelCost := 0.00

for _, f := range vehicle.FuelRecords {
for i, f := range vehicle.FuelRecords {
logger.Debug("Fuel Record",
"index", i,
"fuel", f,
)
totalFuelCost += f.TotalPrice
}

fmt.Printf("%s\n", vehicle.Vehicles[0].Name)
fmt.Printf("Spent %0.02f on fuel in %d fillups\n", totalFuelCost, len(vehicle.FuelRecords))
}
84 changes: 26 additions & 58 deletions roadtrip/roadtrip.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"log/slog"
"os"
"reflect"
"time"

cvslib "github.com/tiendc/go-csvlib"
)
Expand All @@ -32,8 +31,7 @@ type RawSectionData []byte

// VehicleOptions contain the options to be used when creating a new Vehicle object.
type VehicleOptions struct {
Logger *slog.Logger
LogLevel slog.Level
Logger *slog.Logger
}

// A Vehicle holds the parsed sections contained in a Road Trip vehicle data file.
Expand All @@ -50,7 +48,29 @@ type Vehicle struct {
Valuations []ValuationRecord `roadtrip:"VALUATIONS"`
Raw RawFileData
logger *slog.Logger
logLevel slog.Level
}

// LogValue is the handler for [log.slog] to emit structured output for the
// [Vehicle] object when logging.
func (v Vehicle) LogValue() slog.Value {
var value slog.Value

if len(v.Vehicles) == 1 {
value = slog.GroupValue(
slog.String("name", v.Vehicles[0].Name),
slog.Int("version", v.Version),
slog.String("filename", v.Filename),
slog.Int("filesize", len(v.Raw)),
slog.Int("vehicles", len(v.Vehicles)),
slog.Int("fuelRecords", len(v.FuelRecords)),
slog.Int("mainteanceRecords", len(v.MaintenanceRecords)),
slog.Int("trips", len(v.Trips)),
slog.Int("tires", len(v.Tires)),
slog.Int("valuations", len(v.Valuations)),
)
}

return value
}

// NewVehicle returns a new, empty [Vehicle] object.
Expand All @@ -62,7 +82,6 @@ func NewVehicle(options VehicleOptions) Vehicle {
}

v.logger = options.Logger
v.logLevel = options.LogLevel

return v
}
Expand Down Expand Up @@ -181,36 +200,6 @@ func (fileData *RawFileData) UnmarshalRoadtripSection(target any) error {
// debugging.
func (v *Vehicle) SetLogger(l *slog.Logger) {
v.logger = l
v.logLevel = slog.LevelInfo
}

// SetLogLoggerLevel optionally sets the [Vehicle] logger level for internal
// package debugging.
func (v *Vehicle) SetLogLoggerLevel(levelInfo slog.Level) slog.Level {
v.logLevel = levelInfo
return slog.SetLogLoggerLevel(levelInfo)
}

// LogValue is the handler for [log.slog] to emit structured output for the
// [Vehicle] object when logging.
func (v *Vehicle) LogValue() slog.Value {
var value slog.Value

if len(v.Vehicles) == 1 {
if v.logLevel > -slog.LevelInfo {
value = slog.GroupValue(
slog.String("name", v.Vehicles[0].Name),
)
} else {
value = slog.GroupValue(
slog.String("name", v.Vehicles[0].Name),
slog.Int("version", v.Version),
slog.String("filename", v.Filename),
)
}
}

return value
}

// LoadFile reads and parses a file into the [Vehicle] object.
Expand Down Expand Up @@ -257,30 +246,9 @@ func (v *Vehicle) UnmarshalRoadtrip(data RawFileData) error {
}
}

v.logger.Info("Loaded Road Trip vehicle data file",
"filename", v.Filename,
"bytes", len(data),
"vehicleRecords", len(v.Vehicles),
"fuelRecords", len(v.FuelRecords),
"mainteanceRecords", len(v.MaintenanceRecords),
"trips", len(v.Trips),
"tireLogs", len(v.Tires),
"valuations", len(v.Valuations),
v.logger.Debug("Loaded Road Trip vehicle data file",
"vehicle", v,
)

return nil
}

// ParseDate parses a Road Trip styled date string and turns it into a proper
// Go [time.Time] value.
func ParseDate(dateString string) (time.Time, error) {
t, err := time.Parse("2006-1-2 15:04", dateString)
if err != nil {
t, err = time.Parse("2006-1-2", dateString)
if err != nil {
return time.Time{}, fmt.Errorf("unable to parse date '%s': %w", dateString, err)
}
}

return t, nil
}
Loading

0 comments on commit 4f368ed

Please sign in to comment.