package simplelog import ( "context" "encoding/json" "fmt" "log/slog" "os" ) // JSONHandler writes each log record to stdout as a JSON document. type JSONHandler struct{} // NewJSONHandler returns a new JSONHandler. func NewJSONHandler() *JSONHandler { return &JSONHandler{} } // Handle marshals the record to JSON and writes it to stdout. func (j *JSONHandler) Handle(_ context.Context, record slog.Record) error { jsonData, err := json.Marshal(record) if err != nil { return err } _, _ = fmt.Fprintln(os.Stdout, string(jsonData)) return nil } // Enabled reports whether the handler processes records at the given // level; it always returns true. func (j *JSONHandler) Enabled(_ context.Context, _ slog.Level) bool { return true } // WithAttrs returns the handler unchanged; attributes are not rendered. func (j *JSONHandler) WithAttrs(_ []slog.Attr) slog.Handler { return j } // WithGroup returns the handler unchanged; groups are not rendered. func (j *JSONHandler) WithGroup(_ string) slog.Handler { return j }