Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions component/slogc/slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
type config struct {
logLevel string
logFormat string
addSource bool
}

type slogComponent struct {
Expand All @@ -31,7 +32,7 @@ func NewSlogComponent() *slogComponent {
}
}

func (s slogComponent) SetLogLevel(l string) {
func (s *slogComponent) SetLogLevel(l string) {
switch strings.ToUpper(l) {
case slog.LevelInfo.String():
s.opts.Level = slog.LevelInfo
Expand All @@ -45,7 +46,7 @@ func (s slogComponent) SetLogLevel(l string) {
}

func (s *slogComponent) SetLogFormat(f string) {
if strings.EqualFold(s.logFormat, "text") {
if strings.EqualFold(f, "text") {
s.handler = slog.NewTextHandler(os.Stdout, s.opts)
} else {
s.handler = slog.NewJSONHandler(os.Stdout, s.opts)
Expand All @@ -57,11 +58,15 @@ func (s *slogComponent) ID() string {
}

func (s *slogComponent) InitFlags() {
flag.StringVar(&s.logLevel, s.id+"-log-level", "debug", "Log level: debug | info | warm | error . Default: debug")
flag.StringVar(&s.logLevel, s.id+"-log-level", "debug", "Log level: debug | info | warn | error . Default: debug")
flag.StringVar(&s.logFormat, s.id+"-log-format", "text", "Log format: json | text . Default: text")
flag.BoolVar(&s.addSource, s.id+"-log-source", false, "Log source: true | false . Default: false")
}

func (s *slogComponent) Activate(_ sctx.ServiceContext) error {
// set log source
s.opts.AddSource = s.addSource

// set log level
s.SetLogLevel(s.logLevel)

Expand Down
44 changes: 44 additions & 0 deletions component/slogc/slog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package slogc

import (
"log/slog"
"testing"
)

func TestSetLogFormat_UsesArgument(t *testing.T) {
comp := NewSlogComponent()
// Manually set internal config to "text" to simulate flag default
comp.logFormat = "text"

// Try to set to json via method argument
comp.SetLogFormat("json")

// Check if handler is JSONHandler
_, ok := comp.handler.(*slog.JSONHandler)
if !ok {
t.Errorf("Expected JSONHandler, got %T. SetLogFormat should use the argument.", comp.handler)
}
}

func TestSetLogLevel_Receiver(t *testing.T) {
comp := NewSlogComponent()
comp.opts.Level = slog.LevelInfo

// Calling on *comp. The receiver is now pointer, so it should work regardless.
comp.SetLogLevel("error")

if comp.opts.Level != slog.LevelError {
t.Errorf("Expected LevelError, got %v.", comp.opts.Level)
}
}

func TestAddSource(t *testing.T) {
comp := NewSlogComponent()
comp.addSource = true

comp.Activate(nil)

if !comp.opts.AddSource {
t.Errorf("Expected AddSource to be true")
}
}