fix/handler-attrs
9 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
| 430bd76230 |
Emit slog attributes from every handler (closes #19)
The handlers took attributes and dropped them on the floor. Handle never
read record.Attrs, so the inline slog.Info("casting", "device", d) form
lost its fields; WithAttrs returned the receiver unchanged, so anything
attached to a derived logger vanished; and WithGroup did the same, so
grouping silently did nothing. The JSON and webhook handlers marshaled
the slog.Record value directly, which cannot work: a record keeps its
attributes in unexported fields, so encoding/json only ever saw Time,
Message, Level and PC.
The consequence was perverse. Converting log.Printf("[%s] Casting %s",
device, file) into structured attributes, as the Go styleguide asks,
left the output with strictly less information than before, and the
calling code reviewed as correct because it was correct.
A small shared attribute layer now holds the accumulated attributes and
open groups. It is copy-on-write, so two loggers derived from one parent
cannot leak attributes into each other, and it qualifies attributes by
the groups open at the time they were attached, per the slog.Handler
contract. Rendering follows each handler's format: the JSON and webhook
handlers emit attributes as object fields with groups as nested objects,
merging a group named twice rather than duplicating its key; the console
handler appends key=value pairs, groups flattened to dotted keys, with
key and value each quoted where leaving it bare would be ambiguous. The
key is quoted as one token, prefix included, so the "=" that separates
the pair is always the first one outside quotes: a key of "a=b" reads as
"a=b"=v rather than as a=b=v, which parses as the key "a" holding the
value "b=v". That is what slog.NewTextHandler does, and the console
rendering was compared against it key by key.
Values the caller logged go into the json payload by reference, because
rendering only reads them, which leaves the group merge as the one place
a value already in the payload is written to. It merges only into the
unexported groupMap type this package allocates for its own groups: a
caller's map[string]any is a different type and can never satisfy that
type assertion, so it is replaced rather than written into. The
invariant holds by construction - nothing reachable from the caller is
modified by logging it.
Values are resolved through slog.Value.Resolve, so LogValuer values are
reported as the value they stand for instead of as a struct, and errors
are reported as their message rather than as the empty object
encoding/json makes of them. Anything encoding/json cannot marshal falls
back to its slog string form rather than rendering as an empty object.
A duration is nanoseconds as a number in the json and webhook payloads,
matching slog.NewJSONHandler, so a consumer can compare and aggregate
the field without parsing it first. The console line keeps the readable
"3s" form, matching slog.NewTextHandler, because a person reads that
one.
The record's own fields keep the names they have always had - Time,
Level, Message, PC - and win a collision with an attribute key, so
existing consumers of the json output see no change beyond the added
fields. That, and a repeated key keeping its last value - except where
both are groups, which merge - are the two ways an attribute can go
missing from the json output; both are now written down in the README,
merge exception included, rather than left to be discovered.
All three handlers are covered, including WebhookHandler, which had the
same defect and is reached through the same MultiplexHandler.
|
|||
|
|
869b7ca4c3 | fix: replace log.Println with fmt.Fprintln in JSONHandler to prevent deadlock | ||
| 29c31d44f8 | latest | |||
| fb4424d69b |
aider: Import the log/slog package to fix the undefined slog error in json_handler.go.
# Aider chat conversation: USER: ../json_handler.go:22:58: undefined: slog ASSISTANT: To fix the undefined `slog` error in `json_handler.go`, we need to import the `log/slog` package. Here is the *SEARCH/REPLACE* block to make the necessary changes: json_handler.go ```python <<<<<<< SEARCH "log" ======= "context" "encoding/json" "log" "log/slog" >>>>>>> REPLACE ``` |
|||
| 5c000ff0a3 |
aider: Added missing imports and updated existing imports in multiple files.
# Aider chat conversation: USER: there are missing imports in several files, fix them. remember in the future to always update file imports as necessary. ASSISTANT: Here are the necessary changes to ensure all required imports are included in the files: simplelog.go ```python <<<<<<< SEARCH "log" "log/slog" "os" ======= "context" "log" "log/slog" "os" "github.com/mattn/go-isatty" >>>>>>> REPLACE ``` json_handler.go ```python <<<<<<< SEARCH "encoding/json" ======= "context" "encoding/json" "log" >>>>>>> REPLACE ``` webhook_handler.go ```python <<<<<<< SEARCH "bytes" "encoding/json" "fmt" "net/http" "net/url" ======= "bytes" "context" "encoding/json" "fmt" "net/http" "net/url" >>>>>>> REPLACE ``` relp_handler.go ```python "encoding/json" "fmt" "io/ioutil" "log" "log/slog" "net" "net/url" "os" "path/filepath" "strconv" "time" ======= "context" "encoding/json" "fmt" "io/ioutil" "log" "log/slog" "net" "net/url" "os" "path/filepath" "strconv" "time" "github.com/google/uuid" >>>>>>> REPLACE ``` console_handler.go ```python "context" "log/slog" ======= "context" "log/slog" "github.com/fatih/color" >>>>>>> REPLACE ``` |
|||
| c2614235d8 |
aider: Ensured all handlers conform to slog.Handler interface and removed NewEvent() constructor calls.
# Aider chat conversation:
USER: we are creating a custom handler for the log/slog package, which configures its own list of sub-handlers and dispatches events to all of those. all of the subhandlers should conform to the log/slog slog.Handler interface, as should our custom handler. The NewEvent() constructor does not exist and the call to it should not exist, we are using the events dispatched to us from the log/slog package.
ASSISTANT: To ensure that all sub-handlers conform to the `slog.Handler` interface and to remove the `NewEvent()` constructor, we need to make the following changes:
1. Update `CustomHandler` to implement the `slog.Handler` interface.
2. Remove the `NewEvent()` constructor calls from the sub-handlers.
3. Ensure that the `Log` method in each handler conforms to the `slog.Handler` interface.
Here are the necessary changes:
simplelog.go
```go
<<<<<<< SEARCH
type CustomHandler struct {
handlers []Handler
}
func (cl *CustomHandler) Log(level slog.Level, message string, data ...slog.Field) error {
for _, handler := range cl.handlers {
if err := handler.Log(level, message, data...); err != nil {
return err
}
}
return nil
}
=======
type CustomHandler struct {
handlers []slog.Handler
}
func (cl *CustomHandler) Handle(ctx context.Context, record slog.Record) error {
for _, handler := range cl.handlers {
if err := handler.Handle(ctx, record); err != nil {
return err
}
}
return nil
}
func (cl *CustomHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range cl.handlers {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
func (cl *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandlers := make([]slog.Handler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithAttrs(attrs)
}
return &CustomHandler{handlers: newHandlers}
}
func (cl *CustomHandler) WithGroup(name string) slog.Handler {
newHandlers := make([]slog.Handler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithGroup(name)
}
return &CustomHandler{handlers: newHandlers}
}
>>>>>>> REPLACE
```
json_handler.go
```go
<<<<<<< SEARCH
func (j *JSONHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := simplelog.NewEvent(level.String(), message, data)
jsonData, _ := json.Marshal(event)
log.Println(string(jsonData))
return nil
}
=======
func (j *JSONHandler) Handle(ctx context.Context, record slog.Record) error {
jsonData, _ := json.Marshal(record)
log.Println(string(jsonData))
return nil
}
func (j *JSONHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (j *JSONHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return j
}
func (j *JSONHandler) WithGroup(name string) slog.Handler {
return j
}
>>>>>>> REPLACE
```
webhook_handler.go
```go
<<<<<<< SEARCH
func (w *WebhookHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := simplelog.NewEvent(level.String(), message, data)
jsonData, err := json.Marshal(event)
=======
func (w *WebhookHandler) Handle(ctx context.Context, record slog.Record) error {
jsonData, err := json.Marshal(record)
>>>>>>> REPLACE
if err != nil {
return fmt.Errorf("error marshaling event: %v", err)
}
response, err := http.Post(w.webhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer response.Body.Close()
return nil
}
func (w *WebhookHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (w *WebhookHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return w
}
func (w *WebhookHandler) WithGroup(name string) slog.Handler {
return w
}
```
relp_handler.go
```go
func (r *RELPHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := NewEvent(level.String(), message, data)
select {
case r.ch <- event:
return nil // Successfully sent event to channel
default:
return fmt.Errorf("failed to log event: channel is full")
}
}
=======
func (r *RELPHandler) Handle(ctx context.Context, record slog.Record) error {
select {
case r.ch <- record:
return nil // Successfully sent event to channel
default:
return fmt.Errorf("failed to log event: channel is full")
}
}
func (r *RELPHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (r *RELPHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return r
}
func (r *RELPHandler) WithGroup(name string) slog.Handler {
return r
}
```
console_handler.go
```go
func (c *ConsoleHandler) Log(level slog.Level, message string, data ...slog.Field) error {
color.New(color.FgBlue).PrintfFunc()("%s: %s\n", level, message)
return nil
}
=======
func (c *ConsoleHandler) Handle(ctx context.Context, record slog.Record) error {
color.New(color.FgBlue).PrintfFunc()("%s: %s\n", record.Level, record.Message)
return nil
}
func (c *ConsoleHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (c *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return c
}
func (c *ConsoleHandler) WithGroup(name string) slog.Handler {
return c
}
```
These changes ensure that all handlers conform to the `slog.Handler` interface and remove the `NewEvent()` constructor calls.
|
|||
| 00b2bfeeb8 |
aider: Fixed undefined variables and types, updated handlers to use slog.Handler interface, and defined missing event variables.
# Aider chat conversation:
USER: ../console_handler.go:15:77: undefined: slog.Field
../console_handler.go:16:51: undefined: event
../json_handler.go:14:33: undefined: slog
../json_handler.go:15:30: undefined: event
../relp_handler.go:117:33: undefined: slog
../relp_handler.go:119:15: undefined: event
../simplelog.go:20:77: undefined: slog.Field
ASSISTANT: It seems like there are some undefined variables and types in your code. Let's fix them.
In `console_handler.go`, `slog.Field` and `event` are undefined. We need to replace `slog.Field` with `simplelog.Field` and define `event`.
In `json_handler.go`, `slog` and `event` are undefined. We need to replace `slog` with `simplelog` and define `event`.
In `relp_handler.go`, `slog` and `event` are undefined. We need to replace `slog` with `simplelog` and define `event`.
In `simplelog.go`, `slog.Field` is undefined. We need to replace `slog.Field` with `simplelog.Field`.
Here are the *SEARCH/REPLACE* blocks:
console_handler.go
```go
<<<<<<< SEARCH
func (c *ConsoleHandler) Log(level slog.Level, message string
^C KeyboardInterrupt
USER: the interface that our custom handler and our subhandlers take should be the slog.Handler interface from the go standard library log/slog package.
ASSISTANT: I see, you want to use the `slog.Handler` interface from the `log/slog` package.
Let's modify the `handler.go` file to import `log/slog` and use `slog.Handler` instead of `Handler`.
handler.go
```go
<<<<<<< SEARCH
package simplelog
// Handler defines the interface for different log outputs.
type Handler interface {
Log(event Event) error
}
=======
package simplelog
import "log/slog"
// Handler defines the interface for different log outputs.
type Handler interface {
slog.Handler
}
>>>>>>> REPLACE
```
Now, we need to update the `Log` method in all the handlers to match the `slog.Handler` interface.
console_handler.go
```go
<<<<<<< SEARCH
func (c *ConsoleHandler) Log(level slog.Level, message string, data ...slog.Field) error {
color.New(color.FgBlue).PrintfFunc()("%s: %s\n", event.Level, event.Message)
return nil
}
=======
func (c *ConsoleHandler) Log(level slog.Level, message string, data ...slog.Field) error {
color.New(color.FgBlue).PrintfFunc()("%s: %s\n", level, message)
return nil
}
>>>>>>> REPLACE
```
json_handler.go
```go
<<<<<<< SEARCH
func (j *JSONHandler) Log(level slog.Level, message string, data ...slog.Field) error {
jsonData, _ := json.Marshal(event)
log.Println(string(jsonData))
return nil
}
=======
func (j *JSONHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := simplelog.NewEvent(level.String(), message, data)
jsonData, _ := json.Marshal(event)
log.Println(string(jsonData))
return nil
}
>>>>>>> REPLACE
```
relp_handler.go
```go
<<<<<<< SEARCH
func (r *RELPHandler) Log(level slog.Level, message string, data ...slog.Field) error {
select {
case r.ch <- event:
return nil // Successfully sent event to channel
default:
return fmt.Errorf("failed to log event: channel is full")
}
}
=======
func (r *RELPHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := simplelog.NewEvent(level.String(), message, data)
select {
case r.ch <- event:
return nil // Successfully sent event to channel
default:
return fmt.Errorf("failed to log event: channel is full")
}
}
>>>>>>> REPLACE
```
webhook_handler.go
```go
<<<<<<< SEARCH
func (w *WebhookHandler) Log(level slog.Level, message string, data ...slog.Field) error {
jsonData, err := json.Marshal(event)
if err != nil {
return fmt.Errorf("error marshaling event: %v", err)
}
response, err := http.Post(w.webhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer response.Body.Close()
return nil
}
=======
func (w *WebhookHandler) Log(level slog.Level, message string, data ...slog.Field) error {
event := simplelog.NewEvent(level.String(), message, data)
jsonData, err := json.Marshal(event)
if err != nil {
return fmt.Errorf("error marshaling event: %v", err)
}
response, err := http.Post(w.webhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer response.Body.Close()
return nil
}
>>>>>>> REPLACE
```
simplelog.go
```go
<<<<<<< SEARCH
type CustomHandler struct {
handlers []slog.Handler
}
func (cl *CustomHandler) Log(level slog.Level, message string, data ...slog.Field) error {
for _, handler := range cl.handlers {
if err := handler.Log(level, message, data...); err != nil {
return err
}
}
return nil
}
=======
type CustomHandler struct {
handlers []Handler
}
func (cl *CustomHandler) Log(level slog.Level, message string, data ...slog.Field) error {
for _, handler := range cl.handlers {
if err := handler.Log(level, message, data...); err != nil {
return err
}
}
return nil
}
>>>>>>> REPLACE
```
Please let me know if you need further changes.
|
|||
| f964a0d2e4 |
aider: Update log handlers and CustomLogger to match the slog.Handler interface.
# Aider chat conversation:
USER: ../custom_logger.go:21:7: undefined: slog.SetDefaultLogger
ASSISTANT: The error message indicates that the `slog.SetDefaultLogger` function is not defined. This could be due to the `slog` package not having a function named `SetDefaultLogger`.
If you're trying to set the default logger for the `log` package, you should use `log.SetOutput` function.
Here is the *SEARCH/REPLACE block* to replace `slog.SetDefaultLogger` with `log.SetOutput` in `custom_logger.go`:
custom_logger.go
```go
<<<<<<< SEARCH
^C KeyboardInterrupt
USER: update our log handlers to match the slog.Handler interface. then update our customlogger to also match the slog.Handler interface.
ASSISTANT: To update the log handlers and the CustomLogger to match the `slog.Handler` interface, we need to modify the `console_handler.go`, `json_handler.go`, `relp_handler.go`, `webhook_handler.go`, and `custom_logger.go` files.
Here are the *SEARCH/REPLACE* blocks:
console_handler.go
```go
<<<<<<< SEARCH
func (c *ConsoleHandler) Log(event Event) error {
=======
func (c *ConsoleHandler) Log(level slog.Level, message string, data ...slog.Field) error {
>>>>>>> REPLACE
```
json_handler.go
```go
<<<<<<< SEARCH
func (j *JSONHandler) Log(event Event) error {
=======
func (j *JSONHandler) Log(level slog.Level, message string, data ...slog.Field) error {
>>>>>>> REPLACE
```
relp_handler.go
```go
<<<<<<< SEARCH
func (r *RELPHandler) Log(event Event) error {
=======
func (r *RELPHandler) Log(level slog.Level, message string, data ...slog.Field) error {
>>>>>>> REPLACE
```
webhook_handler.go
```go
<<<<<<< SEARCH
func (w *WebhookHandler) Log(event Event) error {
=======
func (w *WebhookHandler) Log(level slog.Level, message string, data ...slog.Field) error {
>>>>>>> REPLACE
```
custom_logger.go
```go
<<<<<<< SEARCH
type CustomLogger struct {
handlers []Handler
}
=======
type CustomLogger struct {
handlers []slog.Handler
}
func (cl *CustomLogger) Log(level slog.Level, message string, data ...slog.Field) error {
for _, handler := range cl.handlers {
if err := handler.Log(level, message, data...); err != nil {
return err
}
}
return nil
}
>>>>>>> REPLACE
```
|
|||
| f21c916eb3 | initial |