- Added detailed comments to clarify the purpose of various functions and types in the Discord bot and HA gateway. - Introduced new methods in the CommandApp for handling light and switch operations, including HandleLightOn, HandleLightOff, HandleLightToggle, and their respective autocomplete functions. - Updated the HAClient interface to include methods for fetching states and calling services, enhancing the interaction with Home Assistant. - Improved the structure of entity and light domain models to include additional attributes and clearer documentation. - Implemented logging enhancements in both the Discord bot and HA gateway to ensure better traceability and context in logs. - Refactored the configuration loading process to streamline environment variable handling and defaults. - Stubbed out switch control methods in the gRPC adapter, indicating future implementation plans. - Enhanced telemetry setup to ensure proper initialization and shutdown procedures for observability.
39 lines
1013 B
Go
39 lines
1013 B
Go
package logger
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
)
|
|
|
|
type contextKey struct{}
|
|
|
|
// New constructs a root logger for the configured format and level.
|
|
func New(format, level string) *slog.Logger {
|
|
var parsed slog.Level
|
|
if err := parsed.UnmarshalText([]byte(level)); err != nil {
|
|
_, _ = fmt.Fprintf(os.Stderr, "invalid log level %q, falling back to info\n", level)
|
|
parsed = slog.LevelInfo
|
|
}
|
|
|
|
opts := &slog.HandlerOptions{Level: parsed}
|
|
if format == "json" {
|
|
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
|
|
}
|
|
return slog.New(slog.NewTextHandler(os.Stdout, opts))
|
|
}
|
|
|
|
// WithLogger attaches a logger to the provided context.
|
|
func WithLogger(ctx context.Context, l *slog.Logger) context.Context {
|
|
return context.WithValue(ctx, contextKey{}, l)
|
|
}
|
|
|
|
// FromContext retrieves a logger from context and falls back to slog.Default().
|
|
func FromContext(ctx context.Context) *slog.Logger {
|
|
if l, ok := ctx.Value(contextKey{}).(*slog.Logger); ok && l != nil {
|
|
return l
|
|
}
|
|
return slog.Default()
|
|
}
|