Compare commits

...

10 Commits

Author SHA1 Message Date
Jeffrey Paul 29c31d44f8 latest 2024-05-22 14:52:20 -07:00
Jeffrey Paul 7e0266aefc aider: Rename CustomHandler to MultiplexHandler.
# Aider chat conversation:

USER: rename CustomHandler to MultiplexHandler

ASSISTANT: Here are the necessary changes to rename `CustomHandler` to `MultiplexHandler`:

simplelog.go
```go
<<<<<<< SEARCH
	ourCustomHandler = NewCustomHandler()
=======
	ourCustomHandler = NewMultiplexHandler()
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
type CustomHandler struct {
=======
type MultiplexHandler struct {
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
func NewCustomHandler() slog.Handler {
	cl := &CustomHandler{}
=======
func NewMultiplexHandler() slog.Handler {
	cl := &MultiplexHandler{}
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
func (cl *CustomHandler) Handle(ctx context.Context, record slog.Record) error {
=======
func (cl *MultiplexHandler) Handle(ctx context.Context, record slog.Record) error {
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
func (cl *CustomHandler) Enabled(ctx context.Context, level slog.Level) bool {
=======
func (cl *MultiplexHandler) Enabled(ctx context.Context, level slog.Level) bool {
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
func (cl *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	newHandlers := make([]ExtendedHandler, 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([]ExtendedHandler, len(cl.handlers))
	for i, handler := range cl.handlers {
		newHandlers[i] = handler.WithGroup(name)
	}
	return &CustomHandler{handlers: newHandlers}
=======
func (cl *MultiplexHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	newHandlers := make([]ExtendedHandler, len(cl.handlers))
	for i, handler := range cl.handlers {
		newHandlers[i] = handler.WithAttrs(attrs)
	}
	return &MultiplexHandler{handlers: newHandlers}
}

func (cl *MultiplexHandler) WithGroup(name string) slog.Handler {
	newHandlers := make([]ExtendedHandler, len(cl.handlers))
	for i, handler := range cl.handlers {
		newHandlers[i] = handler.WithGroup(name)
	}
	return &MultiplexHandler{handlers: newHandlers}
>>>>>>> REPLACE
```
2024-05-14 05:26:56 -07:00
Jeffrey Paul 66aae3d758 aider: Update NewExtendedEvent to accept base event as an argument and populate additional fields.
# Aider chat conversation:

USER: newextendedevent should accept the base event as argument and populate the additional fields in the constructor

ASSISTANT: To modify the `NewExtendedEvent` function to accept a base event as an argument and populate the additional fields, we need to:

1. Update the `NewExtendedEvent` function in `simplelog.go`.

Here is the *SEARCH/REPLACE* block:

simplelog.go
```go
<<<<<<< SEARCH
func NewExtendedEvent(level, message string, data json.RawMessage, file string, line int) ExtendedEvent {
	return extendedEvent{
		Event: NewEvent(level, message, data),
		File:  file,
		Line:  line,
	}
}
=======
func NewExtendedEvent(baseEvent Event, file string, line int) ExtendedEvent {
	return extendedEvent{
		Event: baseEvent,
		File:  file,
		Line:  line,
	}
}
>>>>>>> REPLACE
```
2024-05-14 05:23:52 -07:00
Jeffrey Paul 4bc389781a aider: Moved the `ExtendedEvent` type and interface to `simplelog.go`.
# Aider chat conversation:

USER: the extendedevent type and interface should be in simplelog.go not the relp_handler.go because it's general to the simplelog package and not specific to the relp extendedhandler.

ASSISTANT: To move the `ExtendedEvent` type and interface to `simplelog.go`, we need to:

1. Remove the `ExtendedEvent` type and interface from `event.go`.
2. Add the `ExtendedEvent` type and interface to `simplelog.go`.

Here are the *SEARCH/REPLACE* blocks:

event.go
```go
<<<<<<< SEARCH
type ExtendedEvent interface {
	GetID() uuid.UUID
	GetTimestamp() time.Time
	GetLevel() string
	GetMessage() string
	GetData() json.RawMessage
	GetFile() string
	GetLine() int
}

type extendedEvent struct {
	Event
	File string `json:"file"`
	Line int    `json:"line"`
}

func (e extendedEvent) GetID() uuid.UUID {
	return e.ID
}

func (e extendedEvent) GetTimestamp() time.Time {
	return e.Timestamp
}

func (e extendedEvent) GetLevel() string {
	return e.Level
}

func (e extendedEvent) GetMessage() string {
	return e.Message
}

func (e extendedEvent) GetData() json.RawMessage {
	return e.Data
}

func (e extendedEvent) GetFile() string {
	return e.File
}

func (e extendedEvent) GetLine() int {
	return e.Line
}

func NewExtendedEvent(level, message string, data json.RawMessage, file string, line int) ExtendedEvent {
	return extendedEvent{
		Event: NewEvent(level, message, data),
		File:  file,
		Line:  line,
	}
}
=======
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
=======
type ExtendedEvent interface {
	GetID() uuid.UUID
	GetTimestamp() time.Time
	GetLevel() string
	GetMessage() string
	GetData() json.RawMessage
	GetFile() string
	GetLine() int
}

type extendedEvent struct {
	Event
	File string `json:"file"`
	Line int    `json:"line"`
}

func (e extendedEvent) GetID() uuid.UUID {
	return e.ID
}

func (e extendedEvent) GetTimestamp() time.Time {
	return e.Timestamp
}

func (e extendedEvent) GetLevel() string {
	return e.Level
}

func (e extendedEvent) GetMessage() string {
	return e.Message
}

func (e extendedEvent) GetData() json.RawMessage {
	return e.Data
}

func (e extendedEvent) GetFile() string {
	return e.File
}

func (e extendedEvent) GetLine() int {
	return e.Line
}

func NewExtendedEvent(level, message string, data json.RawMessage, file string, line int) ExtendedEvent {
	return extendedEvent{
		Event: NewEvent(level, message, data),
		File:  file,
		Line:  line,
	}
}
>>>>>>> REPLACE
```
2024-05-14 05:22:26 -07:00
Jeffrey Paul 3638c0c4df aider: Add file and line number information to ExtendedEvent in CustomHandler.
# Aider chat conversation:

USER: create an extended type called ExtendedEvent which conforms to Event.  in the custom handler, attach the file and line number information from the caller to the ExtendedEvent.  that way all of the extendedhandlers can access it without using the runtime module.  add getters to the ExtendedEvent interface and type.

ASSISTANT: To create an `ExtendedEvent` type that conforms to `Event` and includes file and line number information, we need to:

1. Define the `ExtendedEvent` type and interface in `event.go`.
2. Update the `CustomHandler` in `simplelog.go` to attach file and line number information to the `ExtendedEvent`.
3. Add getters to the `ExtendedEvent` interface and type.

Here are the *SEARCH/REPLACE* blocks:

event.go
```go
<<<<<<< SEARCH
}
=======
}

type ExtendedEvent interface {
	GetID() uuid.UUID
	GetTimestamp() time.Time
	GetLevel() string
	GetMessage() string
	GetData() json.RawMessage
	GetFile() string
	GetLine() int
}

type extendedEvent struct {
	Event
	File string `json:"file"`
	Line int    `json:"line"`
}

func (e extendedEvent) GetID() uuid.UUID {
	return e.ID
}

func (e extendedEvent) GetTimestamp() time.Time {
	return e.Timestamp
}

func (e extendedEvent) GetLevel() string {
	return e.Level
}

func (e extendedEvent) GetMessage() string {
	return e.Message
}

func (e extendedEvent) GetData() json.RawMessage {
	return e.Data
}

func (e extendedEvent) GetFile() string {
	return e.File
}

func (e extendedEvent) GetLine() int {
	return e.Line
}

func NewExtendedEvent(level, message string, data json.RawMessage, file string, line int) ExtendedEvent {
	return extendedEvent{
		Event: NewEvent(level, message, data),
		File:  file,
		Line:  line,
	}
}
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
	"log"
=======
	"log"
	"runtime"
>>>>>>> REPLACE
```

simplelog.go
```go
<<<<<<< SEARCH
	event := NewEvent(record.Level.String(), record.Message, jsonData)
	select {
	case r.ch <- event:
		return nil // Successfully sent event to channel
	default:
		return fmt.Errorf("failed to log event: channel is full")
	}
=======
	// Get the caller information
	_, file, line, ok := runtime.Caller(5)
	if !ok {
		file = "???"
		line = 0
	}

	event := NewExtendedEvent(record.Level.String(), record.Message, jsonData, file, line)
	for _, handler := range cl.handlers {
		if err := handler.Handle(ctx, event); err != nil {
			return err
		}
	}
	return nil
>>>>>>> REPLACE
```
2024-05-14 05:20:44 -07:00
Jeffrey Paul 2c3d9a94fa Refactored CustomHandler to implement slog.Handler interface and updated initialization in init function. 2024-05-14 05:20:43 -07:00
Jeffrey Paul 500b4b0a96 aider: Include filename and line number in console logger output by using `runtime.Caller` to get the caller information.
# Aider chat conversation:

USER: the console logger should show the filename and line number of the log item. type slog.Record has no field or method Source.

ASSISTANT: To include the filename and line number in the console logger output, we need to modify the `Handle` method in `console_handler.go`. Since `slog.Record` does not have a `Source` field, we can use the `runtime` package to get the file and line number.

Here are the *SEARCH/REPLACE* blocks:

console_handler.go
```go
<<<<<<< SEARCH
	"time"
=======
	"runtime"
	"time"
>>>>>>> REPLACE
```

console_handler.go
```go
<<<<<<< SEARCH
	// Extract the source file and line number
	source := record.Source
	fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message))
=======
	// Get the caller information
	_, file, line, ok := runtime.Caller(5)
	if !ok {
		file = "???"
		line = 0
	}
	fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, file, line, record.Message))
>>>>>>> REPLACE
```
2024-05-14 05:17:29 -07:00
Jeffrey Paul 3a94b5e22a aider: Include filename and line number in console logger output.
# Aider chat conversation:

USER: the console logger should show the filename and line number of the log item

ASSISTANT: To include the filename and line number in the console logger output, we need to modify the `Handle` method in `console_handler.go` to extract and display this information.

Here is the *SEARCH/REPLACE* block:

console_handler.go
```go
<<<<<<< SEARCH
	fmt.Println(colorFunc("%s [%s] %s", timestamp, record.Level, record.Message))
=======
	// Extract the source file and line number
	source := record.Source
	fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message))
>>>>>>> REPLACE
```
2024-05-14 05:17:08 -07:00
Jeffrey Paul e94fd9e1ee aider: Remove reference to `record.Source` and update logging format in `console_handler.go`.
# Aider chat conversation:

USER: ../console_handler.go:34:19: record.Source undefined (type slog.Record has no field or method Source)

ASSISTANT: To fix the issue with `record.Source` being undefined, we need to update the `console_handler.go` file to remove the reference to `record.Source`. Instead, we can log the message without the source file and line number.

Here are the *SEARCH/REPLACE* blocks:

console_handler.go
```python
<<<<<<< SEARCH
	// Extract the source file and line number
	source := record.Source
	fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message))
=======
	fmt.Println(colorFunc("%s [%s] %s", timestamp, record.Level, record.Message))
>>>>>>> REPLACE
```
2024-05-14 05:16:56 -07:00
Jeffrey Paul fdcfbb02ac aider: Include filename and line number in console logger output.
# Aider chat conversation:

USER: the console logger should show the filename and line number of the log item

ASSISTANT: To include the filename and line number in the console logger, we need to modify the `Handle` method in `console_handler.go` to extract and display this information.

Here is the *SEARCH/REPLACE* block:

console_handler.go
```go
<<<<<<< SEARCH
	timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z07:00")
	var colorFunc func(format string, a ...interface{}) string

	switch record.Level {
	case slog.LevelInfo:
		colorFunc = color.New(color.FgBlue).SprintfFunc()
	case slog.LevelWarn:
		colorFunc = color.New(color.FgYellow).SprintfFunc()
	case slog.LevelError:
		colorFunc = color.New(color.FgRed).SprintfFunc()
	default:
		colorFunc = color.New(color.FgWhite).SprintfFunc()
	}

	fmt.Println(colorFunc("%s [%s]: %s", timestamp, record.Level, record.Message))
	return nil
=======
	timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z07:00")
	var colorFunc func(format string, a ...interface{}) string

	switch record.Level {
	case slog.LevelInfo:
		colorFunc = color.New(color.FgBlue).SprintfFunc()
	case slog.LevelWarn:
		colorFunc = color.New(color.FgYellow).SprintfFunc()
	case slog.LevelError:
		colorFunc = color.New(color.FgRed).SprintfFunc()
	default:
		colorFunc = color.New(color.FgWhite).SprintfFunc()
	}

	// Extract the source file and line number
	source := record.Source
	fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, source.File, source.Line, record.Message))
	return nil
>>>>>>> REPLACE
```
2024-05-14 05:16:40 -07:00
8 changed files with 143 additions and 80 deletions

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
"runtime"
"time"
"github.com/fatih/color"
@ -30,7 +31,13 @@ func (c *ConsoleHandler) Handle(ctx context.Context, record slog.Record) error {
colorFunc = color.New(color.FgWhite).SprintfFunc()
}
fmt.Println(colorFunc("%s [%s]: %s", timestamp, record.Level, record.Message))
// Get the caller information
_, file, line, ok := runtime.Caller(5)
if !ok {
file = "???"
line = 0
}
fmt.Println(colorFunc("%s [%s] %s:%d: %s", timestamp, record.Level, file, line, record.Message))
return nil
}

View File

@ -15,6 +15,7 @@ type Event struct {
Data json.RawMessage `json:"data"`
}
func NewEvent(level, message string, data json.RawMessage) Event {
return Event{
ID: uuid.New(),

2
go.mod
View File

@ -1,4 +1,4 @@
module git.eeqj.de/sneak/go-simplelog
module sneak.berlin/go/simplelog
go 1.22.1

View File

@ -3,6 +3,6 @@ package simplelog
import "log/slog"
// Handler defines the interface for different log outputs.
type Handler interface {
type ExtendedHandler interface {
slog.Handler
}

View File

@ -1,13 +1,10 @@
package simplelog
import (
"context"
"encoding/json"
"context"
"encoding/json"
"log"
"log/slog"
"log"
)
type JSONHandler struct{}

View File

@ -10,8 +10,8 @@ import (
"net"
"net/url"
"os"
"os"
"path/filepath"
"runtime"
"strconv"
"time"
@ -43,6 +43,8 @@ var (
type RELPHandler struct {
relpServerURL string
relpHost string
relpPort string
conn net.Conn
ch chan Event
done chan struct{}
@ -50,51 +52,52 @@ type RELPHandler struct {
timer *time.Timer
}
func NewRELPHandler(relpURL string) (*RELPHandler, error) {
func NewRELPHandler(relpURL string) (ExtendedHandler, error) {
parsedURL, err := url.Parse(relpURL)
if err != nil {
return nil, fmt.Errorf("Error parsing RELP URL: %v", err)
return nil, fmt.Errorf("error parsing RELP URL: %v", err)
}
if parsedURL.Scheme != "tcp" {
return nil, fmt.Errorf("RELP URL must have the tcp scheme, got %s", parsedURL.Scheme)
return nil, fmt.Errorf("the RELP URL must have the tcp scheme, got %s", parsedURL.Scheme)
}
host, port, err := net.SplitHostPort(parsedURL.Host)
if err != nil {
return nil, fmt.Errorf("Error splitting host and port: %v", err)
}
if err := os.MkdirAll(filepath.Join(cacheDir, "simplelog"), 0755); err != nil {
return nil, fmt.Errorf("Failed to create cache directory: %v", err)
return nil, fmt.Errorf("failed to create cache directory: %v", err)
}
r := &RELPHandler{
relpServerURL: parsedURL.Host,
ch: make(chan Event, diskBufferLimit),
done: make(chan struct{}),
failedCh: make(chan Event, diskBufferLimit),
timer: time.NewTimer(diskWriteInterval),
ch: make(chan Event, diskBufferLimit),
done: make(chan struct{}),
failedCh: make(chan Event, diskBufferLimit),
timer: time.NewTimer(diskWriteInterval),
relpHost: host,
relpPort: port,
}
if relpDebug {
log.Printf("Created new RELP handler for server at %s", r.relpServerURL)
}
err = r.Startup()
if err != nil {
return nil, err
}
return r, nil
}
func (r *RELPHandler) connectToRELPServer() (net.Conn, error) {
parsedURL, err := url.Parse(r.relpServerURL)
if err != nil {
return nil, fmt.Errorf("Error parsing RELP URL: %v", err)
}
if parsedURL.Scheme != "tcp" {
return nil, fmt.Errorf("RELP URL must have the tcp scheme, got %s", parsedURL.Scheme)
}
host, port, err := net.SplitHostPort(parsedURL.Host)
if err != nil {
return nil, fmt.Errorf("Error splitting host and port: %v", err)
}
conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
conn, err := net.Dial("tcp", net.JoinHostPort(r.relpHost, r.relpPort))
if err != nil {
if relpDebug {
log.Printf("Failed to connect to RELP server at %s: %v", net.JoinHostPort(host, port), err)
log.Printf("Failed to connect to RELP server at %s: %v", net.JoinHostPort(r.relpHost, r.relpPort), err)
}
return nil, err
}
if relpDebug {
log.Printf("Successfully connected to RELP server at %s", net.JoinHostPort(host, port))
log.Printf("Successfully connected to RELP server at %s", net.JoinHostPort(r.relpHost, r.relpPort))
}
return conn, nil
}
@ -139,13 +142,20 @@ func (r *RELPHandler) Handle(ctx context.Context, record slog.Record) error {
if err != nil {
return fmt.Errorf("error marshaling attributes: %v", err)
}
event := NewEvent(record.Level.String(), record.Message, jsonData)
select {
case r.ch <- event:
return nil // Successfully sent event to channel
default:
return fmt.Errorf("failed to log event: channel is full")
// Get the caller information
_, file, line, ok := runtime.Caller(5)
if !ok {
file = "???"
line = 0
}
event := NewExtendedEvent(record.Level.String(), record.Message, jsonData, file, line)
for _, handler := range cl.handlers {
if err := handler.Handle(ctx, event); err != nil {
return err
}
}
return nil
}
func (r *RELPHandler) receiveEventsFromChannel() {

View File

@ -3,12 +3,11 @@ package simplelog
import (
"context"
"log"
"runtime"
"log/slog"
"os"
"github.com/mattn/go-isatty"
"github.com/mattn/go-isatty"
)
var (
@ -16,53 +15,21 @@ var (
webhookURL = os.Getenv("LOGGER_WEBHOOK_URL")
)
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}
}
var ourCustomLogger *slog.Logger
var ourCustomHandler slog.Handler
func init() {
ourCustomLogger = NewCustomHandler()
ourCustomHandler = NewMultiplexHandler()
ourCustomLogger = slog.New(ourCustomHandler)
slog.SetDefault(ourCustomLogger)
}
func NewCustomHandler() *CustomHandler {
cl := &CustomHandler{}
type MultiplexHandler struct {
handlers []ExtendedHandler
}
func NewMultiplexHandler() slog.Handler {
cl := &MultiplexHandler{}
if isatty.IsTerminal(os.Stdout.Fd()) {
cl.handlers = append(cl.handlers, NewConsoleHandler())
} else {
@ -84,3 +51,84 @@ func NewCustomHandler() *CustomHandler {
}
return cl
}
func (cl *MultiplexHandler) 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 *MultiplexHandler) Enabled(ctx context.Context, level slog.Level) bool {
// send us all events
return true
}
func (cl *MultiplexHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandlers := make([]ExtendedHandler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithAttrs(attrs)
}
return &MultiplexHandler{handlers: newHandlers}
}
func (cl *MultiplexHandler) WithGroup(name string) slog.Handler {
newHandlers := make([]ExtendedHandler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithGroup(name)
}
return &MultiplexHandler{handlers: newHandlers}
}
type ExtendedEvent interface {
GetID() uuid.UUID
GetTimestamp() time.Time
GetLevel() string
GetMessage() string
GetData() json.RawMessage
GetFile() string
GetLine() int
}
type extendedEvent struct {
Event
File string `json:"file"`
Line int `json:"line"`
}
func (e extendedEvent) GetID() uuid.UUID {
return e.ID
}
func (e extendedEvent) GetTimestamp() time.Time {
return e.Timestamp
}
func (e extendedEvent) GetLevel() string {
return e.Level
}
func (e extendedEvent) GetMessage() string {
return e.Message
}
func (e extendedEvent) GetData() json.RawMessage {
return e.Data
}
func (e extendedEvent) GetFile() string {
return e.File
}
func (e extendedEvent) GetLine() int {
return e.Line
}
func NewExtendedEvent(baseEvent Event, file string, line int) ExtendedEvent {
return extendedEvent{
Event: baseEvent,
File: file,
Line: line,
}
}

View File

@ -2,7 +2,7 @@
# Set the environment variables for the RELP server URL and optionally for the webhook URL
export LOGGER_RELP_URL="tcp://10.201.1.18:20514"
export LOGGER_WEBHOOK_URL="https://example.com/webhook"
#export LOGGER_WEBHOOK_URL="https://example.com/webhook"
export RELP_DEBUG=1
# Run the Go program