diff --git a/cmd/launcher/launcher.go b/cmd/launcher/launcher.go index 52d77d330..93d46309d 100644 --- a/cmd/launcher/launcher.go +++ b/cmd/launcher/launcher.go @@ -160,7 +160,7 @@ func runLauncher(ctx context.Context, cancel func(), multiSlogger, systemMultiSl } debugAddrPath := filepath.Join(rootDirectory, "debug_addr") - debug.AttachDebugHandler(debugAddrPath, logger) + debug.AttachDebugHandler(debugAddrPath, slogger) defer os.Remove(debugAddrPath) // open the database for storing launcher data, we do it here @@ -281,7 +281,7 @@ func runLauncher(ctx context.Context, cancel func(), multiSlogger, systemMultiSl // For now, remediation is not performed -- we only log the hardware change. agent.DetectAndRemediateHardwareChange(ctx, k) - powerEventWatcher, err := powereventwatcher.New(ctx, k, log.With(logger, "component", "power_event_watcher")) + powerEventWatcher, err := powereventwatcher.New(ctx, k, slogger) if err != nil { slogger.Log(ctx, slog.LevelDebug, "could not init power event watcher", diff --git a/cmd/launcher/run_compactdb.go b/cmd/launcher/run_compactdb.go index 59bbddb27..41a12532e 100644 --- a/cmd/launcher/run_compactdb.go +++ b/cmd/launcher/run_compactdb.go @@ -1,13 +1,15 @@ package main import ( + "context" "errors" + "log/slog" + "os" "path/filepath" - "github.com/go-kit/kit/log/level" - "github.com/kolide/kit/logutil" "github.com/kolide/launcher/ee/agent" "github.com/kolide/launcher/pkg/launcher" + "github.com/kolide/launcher/pkg/log/multislogger" ) func runCompactDb(args []string) error { @@ -21,7 +23,14 @@ func runCompactDb(args []string) error { } // relevel - logger := logutil.NewServerLogger(opts.Debug) + slogLevel := slog.LevelInfo + if opts.Debug { + slogLevel = slog.LevelDebug + } + + slogger := multislogger.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slogLevel, + })).Logger boltPath := filepath.Join(opts.RootDirectory, "launcher.db") @@ -30,7 +39,10 @@ func runCompactDb(args []string) error { return err } - level.Info(logger).Log("msg", "Done compacting. Safe to remove old db", "path", oldDbPath) + slogger.Log(context.TODO(), slog.LevelInfo, + "done compacting, safe to remove old db", + "path", oldDbPath, + ) return nil } diff --git a/ee/keyidentifier/examples/key-identifier/main.go b/ee/keyidentifier/examples/key-identifier/main.go index 20295c544..955ebe095 100644 --- a/ee/keyidentifier/examples/key-identifier/main.go +++ b/ee/keyidentifier/examples/key-identifier/main.go @@ -4,8 +4,8 @@ import ( "fmt" "os" - "github.com/kolide/kit/logutil" "github.com/kolide/launcher/ee/keyidentifier" + "github.com/kolide/launcher/pkg/log/multislogger" ) func main() { @@ -18,7 +18,7 @@ func main() { } func testIdentifyFile(path string) error { - kIdentifer, _ := keyidentifier.New(keyidentifier.WithLogger(logutil.NewCLILogger(true))) + kIdentifer, _ := keyidentifier.New(keyidentifier.WithSlogger(multislogger.New().Logger)) ki, err := kIdentifer.IdentifyFile(path) if err != nil { diff --git a/ee/keyidentifier/keyidentifier.go b/ee/keyidentifier/keyidentifier.go index e2c1f0144..2d898c22f 100644 --- a/ee/keyidentifier/keyidentifier.go +++ b/ee/keyidentifier/keyidentifier.go @@ -2,16 +2,17 @@ package keyidentifier import ( "bytes" + "context" "crypto/ecdsa" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" + "log/slog" "os" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" + "github.com/kolide/launcher/pkg/log/multislogger" "golang.org/x/crypto/ssh" ) @@ -29,35 +30,35 @@ type KeyInfo struct { } // keyidentifier attempts to identify a key. It uses a set of -// herusitics to try to guiess what kind, what size, and whether or +// heuristics to try to guiess what kind, what size, and whether or // not it's encrypted. type KeyIdentifier struct { - logger log.Logger + slogger *slog.Logger } type Option func(*KeyIdentifier) -func WithLogger(logger log.Logger) Option { - return func(kIdentifer *KeyIdentifier) { - kIdentifer.logger = logger +func WithSlogger(slogger *slog.Logger) Option { + return func(kIdentifier *KeyIdentifier) { + kIdentifier.slogger = slogger.With("component", "key_identifier") } } func New(opts ...Option) (*KeyIdentifier, error) { - kIdentifer := &KeyIdentifier{ - logger: log.NewNopLogger(), + kIdentifier := &KeyIdentifier{ + slogger: multislogger.NewNopLogger(), } for _, opt := range opts { - opt(kIdentifer) + opt(kIdentifier) } - return kIdentifer, nil + return kIdentifier, nil } -func (kIdentifer *KeyIdentifier) IdentifyFile(path string) (*KeyInfo, error) { - level.Debug(kIdentifer.logger).Log( - "msg", "starting a key identification", +func (kIdentifier *KeyIdentifier) IdentifyFile(path string) (*KeyInfo, error) { + kIdentifier.slogger.Log(context.TODO(), slog.LevelDebug, + "starting a key identification", "file", path, ) @@ -66,7 +67,7 @@ func (kIdentifer *KeyIdentifier) IdentifyFile(path string) (*KeyInfo, error) { return nil, fmt.Errorf("reading file %s: %w", path, err) } - ki, err := kIdentifer.Identify(keyBytes) + ki, err := kIdentifier.Identify(keyBytes) if err != nil { return nil, fmt.Errorf("identifying key: %w", err) } @@ -77,9 +78,9 @@ func (kIdentifer *KeyIdentifier) IdentifyFile(path string) (*KeyInfo, error) { // Identify uses a manually curated set of heuristics to determine // what kind of key something is. Generally speaking, we consider `err // == nil` as success, and throw away errors as unparsable keys. -func (kIdentifer *KeyIdentifier) Identify(keyBytes []byte) (*KeyInfo, error) { - level.Debug(kIdentifer.logger).Log( - "msg", "starting a key identification", +func (kIdentifier *KeyIdentifier) Identify(keyBytes []byte) (*KeyInfo, error) { + kIdentifier.slogger.Log(context.TODO(), slog.LevelDebug, + "starting a key identification", "file", "", ) @@ -94,7 +95,7 @@ func (kIdentifer *KeyIdentifier) Identify(keyBytes []byte) (*KeyInfo, error) { } // If nothing else fits. treat it like a pem - if ki, err := kIdentifer.attemptPem(keyBytes); err == nil { + if ki, err := kIdentifier.attemptPem(keyBytes); err == nil { return ki, nil } @@ -105,7 +106,7 @@ func (kIdentifer *KeyIdentifier) Identify(keyBytes []byte) (*KeyInfo, error) { // attemptPem tries to decode the pem, and then work with the key. It's // based on code from x/crypto's ssh.ParseRawPrivateKey, but more // flexible in handling encryption and formats. -func (kIdentifer *KeyIdentifier) attemptPem(keyBytes []byte) (*KeyInfo, error) { +func (kIdentifier *KeyIdentifier) attemptPem(keyBytes []byte) (*KeyInfo, error) { ki := &KeyInfo{ Format: "", Parser: "attemptPem", @@ -118,8 +119,8 @@ func (kIdentifer *KeyIdentifier) attemptPem(keyBytes []byte) (*KeyInfo, error) { ki.Encrypted = boolPtr(pemEncryptedBlock(block)) - level.Debug(kIdentifer.logger).Log( - "msg", "pem decoded", + kIdentifier.slogger.Log(context.TODO(), slog.LevelDebug, + "pem decoded", "block type", block.Type, ) @@ -156,8 +157,8 @@ func (kIdentifer *KeyIdentifier) attemptPem(keyBytes []byte) (*KeyInfo, error) { if key, err := x509.ParseECPrivateKey(block.Bytes); err == nil { ki.Bits = key.PublicKey.Curve.Params().BitSize } else { - level.Debug(kIdentifer.logger).Log( - "msg", "x509.ParseECPrivateKey failed to parse", + kIdentifier.slogger.Log(context.TODO(), slog.LevelDebug, + "x509.ParseECPrivateKey failed to parse", "err", err, ) } @@ -179,8 +180,8 @@ func (kIdentifer *KeyIdentifier) attemptPem(keyBytes []byte) (*KeyInfo, error) { } // Unmatched. return what we have - level.Debug(kIdentifer.logger).Log( - "msg", "pem failed to match block type", + kIdentifier.slogger.Log(context.TODO(), slog.LevelDebug, + "pem failed to match block type", "type", block.Type, ) return ki, nil diff --git a/ee/keyidentifier/keyidentifier_test.go b/ee/keyidentifier/keyidentifier_test.go index 8d4ec7cde..c25426927 100644 --- a/ee/keyidentifier/keyidentifier_test.go +++ b/ee/keyidentifier/keyidentifier_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/kolide/kit/logutil" + "github.com/kolide/launcher/pkg/log/multislogger" "github.com/stretchr/testify/require" ) @@ -21,7 +21,7 @@ type spec struct { func TestIdentifyFiles(t *testing.T) { t.Parallel() - kIdentifier, err := New(WithLogger(logutil.NewCLILogger(true))) + kIdentifier, err := New(WithSlogger(multislogger.NewNopLogger())) require.NoError(t, err) testFiles, err := filepath.Glob("testdata/specs/*.json") diff --git a/ee/powereventwatcher/power_event_watcher_other.go b/ee/powereventwatcher/power_event_watcher_other.go index 229a01a38..707f438d9 100644 --- a/ee/powereventwatcher/power_event_watcher_other.go +++ b/ee/powereventwatcher/power_event_watcher_other.go @@ -5,8 +5,8 @@ package powereventwatcher import ( "context" + "log/slog" - "github.com/go-kit/kit/log" "github.com/kolide/launcher/ee/agent/types" "github.com/kolide/launcher/pkg/traces" ) @@ -16,7 +16,7 @@ type noOpPowerEventWatcher struct { interrupted bool } -func New(ctx context.Context, _ types.Knapsack, _ log.Logger) (*noOpPowerEventWatcher, error) { +func New(ctx context.Context, _ types.Knapsack, _ *slog.Logger) (*noOpPowerEventWatcher, error) { _, span := traces.StartSpan(ctx) defer span.End() diff --git a/ee/powereventwatcher/power_event_watcher_other_test.go b/ee/powereventwatcher/power_event_watcher_other_test.go index 670e4ed64..ca4b62525 100644 --- a/ee/powereventwatcher/power_event_watcher_other_test.go +++ b/ee/powereventwatcher/power_event_watcher_other_test.go @@ -9,15 +9,15 @@ import ( "testing" "time" - "github.com/go-kit/kit/log" typesmocks "github.com/kolide/launcher/ee/agent/types/mocks" + "github.com/kolide/launcher/pkg/log/multislogger" "github.com/stretchr/testify/require" ) func TestInterrupt_Multiple(t *testing.T) { t.Parallel() - p, err := New(context.TODO(), typesmocks.NewKnapsack(t), log.NewNopLogger()) + p, err := New(context.TODO(), typesmocks.NewKnapsack(t), multislogger.NewNopLogger()) require.NoError(t, err) // Start and then interrupt diff --git a/ee/powereventwatcher/power_event_watcher_windows.go b/ee/powereventwatcher/power_event_watcher_windows.go index 8992ec0f8..695989931 100644 --- a/ee/powereventwatcher/power_event_watcher_windows.go +++ b/ee/powereventwatcher/power_event_watcher_windows.go @@ -7,11 +7,10 @@ import ( "context" "encoding/xml" "fmt" + "log/slog" "syscall" "unsafe" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" "github.com/kolide/launcher/ee/agent/types" "github.com/kolide/launcher/pkg/traces" "golang.org/x/text/encoding/unicode" @@ -28,7 +27,7 @@ type ( } powerEventWatcher struct { - logger log.Logger + slogger *slog.Logger knapsack types.Knapsack subscriptionHandle uintptr subscribeProcedure *syscall.LazyProc @@ -48,14 +47,14 @@ const ( ) // New sets up a subscription to relevant power events with a callback to `onPowerEvent`. -func New(ctx context.Context, k types.Knapsack, logger log.Logger) (*powerEventWatcher, error) { +func New(ctx context.Context, k types.Knapsack, slogger *slog.Logger) (*powerEventWatcher, error) { _, span := traces.StartSpan(ctx) defer span.End() evtApi := syscall.NewLazyDLL("wevtapi.dll") p := &powerEventWatcher{ - logger: logger, + slogger: slogger.With("component", "power_event_watcher"), knapsack: k, subscribeProcedure: evtApi.NewProc("EvtSubscribe"), unsubscribeProcedure: evtApi.NewProc("EvtClose"), @@ -117,7 +116,12 @@ func (p *powerEventWatcher) Interrupt(_ error) { // EvtClose: https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtclose ret, _, err := p.unsubscribeProcedure.Call(p.subscriptionHandle) - level.Debug(p.logger).Log("msg", "unsubscribed from power events", "ret", fmt.Sprintf("%+v", ret), "last_err", err) + + p.slogger.Log(context.TODO(), slog.LevelDebug, + "unsubscribed from power events", + "ret", fmt.Sprintf("%+v", ret), + "last_err", err, + ) p.interrupt <- struct{}{} } @@ -126,7 +130,10 @@ func (p *powerEventWatcher) Interrupt(_ error) { func (p *powerEventWatcher) onPowerEvent(action uint32, _ uintptr, eventHandle uintptr) uintptr { var ret uintptr // We never do anything with this and neither does Windows -- it's here to satisfy the interface if action == 0 { - level.Debug(p.logger).Log("msg", "received EvtSubscribeActionError when watching power events", "err_code", uint32(eventHandle)) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "received EvtSubscribeActionError when watching power events", + "err_code", uint32(eventHandle), + ) return ret } @@ -147,7 +154,10 @@ func (p *powerEventWatcher) onPowerEvent(action uint32, _ uintptr, eventHandle u uintptr(unsafe.Pointer(&propertyCount)), // PropertyCount -- modified by call: only matters if we used EvtRenderEventValues ) if err != nil && err.Error() != operationSuccessfulMsg { - level.Debug(p.logger).Log("msg", "error calling EvtRender to get event details", "last_err", err) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "error calling EvtRender to get event details", + "last_err", err, + ) return ret } @@ -164,29 +174,51 @@ func (p *powerEventWatcher) onPowerEvent(action uint32, _ uintptr, eventHandle u decoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder() utf8bytes, err := decoder.Bytes(buf) if err != nil { - level.Debug(p.logger).Log("msg", "error decoding from utf16 to utf8", "err", err) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "error decoding from utf16 to utf8", + "err", err, + ) return ret } var e eventLogEntry if err := xml.Unmarshal(utf8bytes, &e); err != nil { - level.Debug(p.logger).Log("msg", "error unmarshalling event log entry", "err", err) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "error unmarshalling event log entry", + "err", err, + ) return ret } switch e.System.EventID { case eventIdEnteringModernStandby, eventIdEnteringSleep: - level.Debug(p.logger).Log("msg", "system is sleeping", "event_id", e.System.EventID) + p.slogger.Log(context.TODO(), slog.LevelDebug, + "system is sleeping", + "event_id", e.System.EventID, + ) if err := p.knapsack.SetInModernStandby(true); err != nil { - level.Debug(p.logger).Log("msg", "could not disable osquery healthchecks on system sleep", "err", err) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "could not enable osquery healthchecks on system sleep", + "err", err, + ) } case eventIdExitingModernStandby: - level.Debug(p.logger).Log("msg", "system is waking", "event_id", e.System.EventID) + p.slogger.Log(context.TODO(), slog.LevelDebug, + "system is waking", + "event_id", e.System.EventID, + ) if err := p.knapsack.SetInModernStandby(false); err != nil { - level.Debug(p.logger).Log("msg", "could not enable osquery healthchecks on system wake", "err", err) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "could not enable osquery healthchecks on system wake", + "err", err, + ) } default: - level.Debug(p.logger).Log("msg", "received unexpected event ID in log", "event_id", e.System.EventID, "raw_event", string(utf8bytes)) + p.slogger.Log(context.TODO(), slog.LevelWarn, + "received unexpected event ID in log", + "event_id", e.System.EventID, + "raw_event", string(utf8bytes), + ) } return ret diff --git a/ee/tables/tablehelpers/parser.go b/ee/tables/tablehelpers/parser.go index 67d10cab1..9b165ae38 100644 --- a/ee/tables/tablehelpers/parser.go +++ b/ee/tables/tablehelpers/parser.go @@ -3,9 +3,8 @@ package tablehelpers import ( "bufio" "bytes" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" + "context" + "log/slog" ) type Matcher struct { @@ -16,13 +15,13 @@ type Matcher struct { type OutputParser struct { matchers []Matcher - logger log.Logger + slogger *slog.Logger } -func NewParser(logger log.Logger, matchers []Matcher) *OutputParser { +func NewParser(slogger *slog.Logger, matchers []Matcher) *OutputParser { p := &OutputParser{ matchers: matchers, - logger: logger, + slogger: slogger, } return p } @@ -45,8 +44,8 @@ func (p *OutputParser) Parse(input *bytes.Buffer) map[string]string { if m.Match(line) { key, err := m.KeyFunc(line) if err != nil { - level.Debug(p.logger).Log( - "msg", "key match failed", + p.slogger.Log(context.TODO(), slog.LevelDebug, + "key match failed", "line", line, "err", err, ) @@ -55,8 +54,8 @@ func (p *OutputParser) Parse(input *bytes.Buffer) map[string]string { val, err := m.ValFunc(line) if err != nil { - level.Debug(p.logger).Log( - "msg", "value match failed", + p.slogger.Log(context.TODO(), slog.LevelDebug, + "value match failed", "line", line, "err", err, ) @@ -89,8 +88,8 @@ func (p *OutputParser) ParseMultiple(input *bytes.Buffer) []map[string]string { if m.Match(line) { key, err := m.KeyFunc(line) if err != nil { - level.Debug(p.logger).Log( - "msg", "key match failed", + p.slogger.Log(context.TODO(), slog.LevelDebug, + "key match failed", "line", line, "err", err, ) @@ -99,8 +98,8 @@ func (p *OutputParser) ParseMultiple(input *bytes.Buffer) []map[string]string { val, err := m.ValFunc(line) if err != nil { - level.Debug(p.logger).Log( - "msg", "value match failed", + p.slogger.Log(context.TODO(), slog.LevelDebug, + "value match failed", "line", line, "err", err, ) @@ -113,14 +112,20 @@ func (p *OutputParser) ParseMultiple(input *bytes.Buffer) []map[string]string { } if len(row) == 0 { - level.Debug(p.logger).Log("msg", "No matched keys", "line", line) + p.slogger.Log(context.TODO(), slog.LevelDebug, + "no matched keys", + "line", line, + ) continue } results = append(results, row) } if err := scanner.Err(); err != nil { - level.Debug(p.logger).Log("msg", "scanner error", "err", err) + p.slogger.Log(context.TODO(), slog.LevelDebug, + "scanner error", + "err", err, + ) } return results } diff --git a/ee/tables/wmitable/wmitable.go b/ee/tables/wmitable/wmitable.go index 2953eb9da..118f860f2 100644 --- a/ee/tables/wmitable/wmitable.go +++ b/ee/tables/wmitable/wmitable.go @@ -89,7 +89,7 @@ func (t *Table) generate(ctx context.Context, queryContext table.QueryContext) ( ctx, cancel := context.WithTimeout(ctx, 120*time.Second) defer cancel() - wmiResults, err := wmi.Query(ctx, class, properties, wmi.ConnectUseMaxWait(), wmi.ConnectNamespace(ns), wmi.WithWhere(whereClause)) + wmiResults, err := wmi.Query(ctx, t.slogger, class, properties, wmi.ConnectUseMaxWait(), wmi.ConnectNamespace(ns), wmi.WithWhere(whereClause)) if err != nil { t.slogger.Log(ctx, slog.LevelInfo, "wmi query failure", diff --git a/ee/wmi/wmi.go b/ee/wmi/wmi.go index 184d91ffc..b46a5edb8 100644 --- a/ee/wmi/wmi.go +++ b/ee/wmi/wmi.go @@ -35,13 +35,10 @@ package wmi import ( "context" "fmt" + "log/slog" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" "github.com/go-ole/go-ole" "github.com/go-ole/go-ole/oleutil" - "github.com/kolide/launcher/pkg/contexts/ctxlog" - "github.com/scjalliance/comshim" ) @@ -113,9 +110,8 @@ func WithWhere(whereClause string) Option { } } -func Query(ctx context.Context, className string, properties []string, opts ...Option) ([]map[string]interface{}, error) { - logger := log.With(ctxlog.FromContext(ctx), "caller", "wmi.Query") - handler := NewOleHandler(ctx, properties) +func Query(ctx context.Context, slogger *slog.Logger, className string, properties []string, opts ...Option) ([]map[string]interface{}, error) { + handler := NewOleHandler(ctx, slogger, properties) // settings qs := &querySettings{} @@ -160,7 +156,10 @@ func Query(ctx context.Context, className string, properties []string, opts ...O service := serviceRaw.ToIDispatch() defer service.Release() - level.Debug(logger).Log("msg", "Running WMI query", "query", queryString) + slogger.Log(ctx, slog.LevelDebug, + "running WMI query", + "query", queryString, + ) // result is a SWBemObjectSet resultRaw, err := oleutil.CallMethod(service, "ExecQuery", queryString) @@ -180,14 +179,14 @@ func Query(ctx context.Context, className string, properties []string, opts ...O } type oleHandler struct { - logger log.Logger + slogger *slog.Logger results []map[string]interface{} properties []string } -func NewOleHandler(ctx context.Context, properties []string) *oleHandler { +func NewOleHandler(ctx context.Context, slogger *slog.Logger, properties []string) *oleHandler { return &oleHandler{ - logger: log.With(ctxlog.FromContext(ctx), "caller", "oleHandler"), + slogger: slogger.With("component", "ole_handler"), properties: properties, results: []map[string]interface{}{}, } @@ -202,7 +201,11 @@ func (oh *oleHandler) HandleVariant(v *ole.VARIANT) error { for _, p := range oh.properties { val, err := oleutil.GetProperty(item, p) if err != nil { - level.Debug(oh.logger).Log("msg", "Got error looking for property", "property", p, "err", err) + oh.slogger.Log(context.TODO(), slog.LevelDebug, + "got error looking for property", + "property", p, + "err", err, + ) continue } defer val.Clear() diff --git a/ee/wmi/wmi_test.go b/ee/wmi/wmi_test.go index 3a5dd0938..295148474 100644 --- a/ee/wmi/wmi_test.go +++ b/ee/wmi/wmi_test.go @@ -7,6 +7,7 @@ import ( "context" "testing" + "github.com/kolide/launcher/pkg/log/multislogger" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -14,7 +15,6 @@ import ( func TestQuery(t *testing.T) { t.Parallel() - // If you want a logger for debugging, add it in to the ctx ctx := context.TODO() var tests = []struct { @@ -130,7 +130,7 @@ func TestQuery(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { - rows, err := Query(ctx, tt.class, tt.properties, tt.options...) + rows, err := Query(ctx, multislogger.NewNopLogger(), tt.class, tt.properties, tt.options...) if tt.err { require.Error(t, err) return diff --git a/pkg/debug/debug.go b/pkg/debug/debug.go index 224964832..f47432f8a 100644 --- a/pkg/debug/debug.go +++ b/pkg/debug/debug.go @@ -4,8 +4,10 @@ package debug import ( + "context" "fmt" "html/template" + "log/slog" "net" "net/http" nhpprof "net/http/pprof" @@ -14,14 +16,12 @@ import ( "runtime/pprof" "strings" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" "github.com/google/uuid" ) const debugPrefix = "/debug/" -func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) { +func startDebugServer(addrPath string, slogger *slog.Logger) (*http.Server, error) { // Generate new (random) token to use for debug server auth token, err := uuid.NewRandom() if err != nil { @@ -30,7 +30,7 @@ func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) // Start the debug server r := http.NewServeMux() - registerAuthHandler(token.String(), r, logger) + registerAuthHandler(token.String(), r, slogger) serv := http.Server{ Handler: r, } @@ -44,7 +44,9 @@ func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) go func() { if err := serv.Serve(listener); err != nil && err != http.ErrServerClosed { - level.Info(logger).Log("msg", "debug server failed", "err", err) + slogger.Log(context.TODO(), slog.LevelInfo, + "debug server failed", "err", err, + ) } }() @@ -60,8 +62,8 @@ func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) return nil, fmt.Errorf("writing debug address: %w", err) } - level.Info(logger).Log( - "msg", "debug server started", + slogger.Log(context.TODO(), slog.LevelInfo, + "debug server started", "addr", addr, ) @@ -69,7 +71,7 @@ func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) } // The below handler code is adapted from MIT licensed github.com/e-dard/netbug -func handler(token string, logger log.Logger) http.HandlerFunc { +func handler(token string, slogger *slog.Logger) http.HandlerFunc { info := struct { Profiles []*pprof.Profile Token string @@ -84,8 +86,8 @@ func handler(token string, logger log.Logger) http.HandlerFunc { case "": // Index page. if err := indexTmpl.Execute(w, info); err != nil { - level.Info(logger).Log( - "msg", "error rendering debug template", + slogger.Log(r.Context(), slog.LevelInfo, + "error rendering debug template", "err", err, ) return @@ -105,18 +107,18 @@ func handler(token string, logger log.Logger) http.HandlerFunc { } } -func authHandler(token string, logger log.Logger) http.HandlerFunc { +func authHandler(token string, slogger *slog.Logger) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.FormValue("token") == token { - handler(token, logger).ServeHTTP(w, r) + handler(token, slogger).ServeHTTP(w, r) } else { http.Error(w, "Request must include valid token.", http.StatusUnauthorized) } } } -func registerAuthHandler(token string, mux *http.ServeMux, logger log.Logger) { - mux.Handle(debugPrefix, http.StripPrefix(debugPrefix, authHandler(token, logger))) +func registerAuthHandler(token string, mux *http.ServeMux, slogger *slog.Logger) { + mux.Handle(debugPrefix, http.StripPrefix(debugPrefix, authHandler(token, slogger))) } var indexTmpl = template.Must(template.New("index").Parse(` diff --git a/pkg/debug/debug_test.go b/pkg/debug/debug_test.go index 1a1d717db..067979d97 100644 --- a/pkg/debug/debug_test.go +++ b/pkg/debug/debug_test.go @@ -12,7 +12,7 @@ import ( "testing" "time" - "github.com/go-kit/kit/log" + "github.com/kolide/launcher/pkg/log/multislogger" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -28,7 +28,7 @@ func TestStartDebugServer(t *testing.T) { tokenFile, err := os.CreateTemp("", "kolide_debug_test") require.Nil(t, err) - serv, err := startDebugServer(tokenFile.Name(), log.NewNopLogger()) + serv, err := startDebugServer(tokenFile.Name(), multislogger.NewNopLogger()) require.Nil(t, err) url := getDebugURL(t, tokenFile.Name()) @@ -46,7 +46,7 @@ func TestDebugServerUnauthorized(t *testing.T) { tokenFile, err := os.CreateTemp("", "kolide_debug_test") require.Nil(t, err) - serv, err := startDebugServer(tokenFile.Name(), log.NewNopLogger()) + serv, err := startDebugServer(tokenFile.Name(), multislogger.NewNopLogger()) require.Nil(t, err) url := getDebugURL(t, tokenFile.Name()) @@ -65,7 +65,7 @@ func TestAttachDebugHandler(t *testing.T) { tokenFile, err := os.CreateTemp("", "kolide_debug_test") require.Nil(t, err) - AttachDebugHandler(tokenFile.Name(), log.NewNopLogger()) + AttachDebugHandler(tokenFile.Name(), multislogger.NewNopLogger()) // Start server syscall.Kill(syscall.Getpid(), debugSignal) diff --git a/pkg/debug/signal_debug.go b/pkg/debug/signal_debug.go index 31b907a71..d0d9b3088 100644 --- a/pkg/debug/signal_debug.go +++ b/pkg/debug/signal_debug.go @@ -5,29 +5,27 @@ package debug import ( "context" + "log/slog" "os" "os/signal" "syscall" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" ) const debugSignal = syscall.SIGUSR1 // AttachDebugHandler attaches a signal handler that toggles the debug server // state when SIGUSR1 is sent to the process. -func AttachDebugHandler(addrPath string, logger log.Logger) { +func AttachDebugHandler(addrPath string, slogger *slog.Logger) { sig := make(chan os.Signal, 1) signal.Notify(sig, debugSignal) go func() { for { // Start server on first signal <-sig - serv, err := startDebugServer(addrPath, logger) + serv, err := startDebugServer(addrPath, slogger) if err != nil { - level.Info(logger).Log( - "msg", "starting debug server", + slogger.Log(context.TODO(), slog.LevelInfo, + "starting debug server", "err", err, ) continue @@ -36,15 +34,15 @@ func AttachDebugHandler(addrPath string, logger log.Logger) { // Stop server on next signal <-sig if err := serv.Shutdown(context.Background()); err != nil { - level.Info(logger).Log( - "msg", "error shutting down debug server", + slogger.Log(context.TODO(), slog.LevelInfo, + "error shutting down debug server", "err", err, ) continue } - level.Info(logger).Log( - "msg", "shutdown debug server", + slogger.Log(context.TODO(), slog.LevelInfo, + "shutdown debug server", ) } }() diff --git a/pkg/debug/signal_debug_windows.go b/pkg/debug/signal_debug_windows.go index 64a833ab3..54529cd22 100644 --- a/pkg/debug/signal_debug_windows.go +++ b/pkg/debug/signal_debug_windows.go @@ -3,10 +3,8 @@ package debug -import ( - "github.com/go-kit/kit/log" -) +import "log/slog" -func AttachDebugHandler(addrPath string, logger log.Logger) { +func AttachDebugHandler(addrPath string, slogger *slog.Logger) { // TODO: noop for now } diff --git a/pkg/osquery/table/keyinfo.go b/pkg/osquery/table/keyinfo.go index 13655082c..43a72a9bd 100644 --- a/pkg/osquery/table/keyinfo.go +++ b/pkg/osquery/table/keyinfo.go @@ -26,7 +26,7 @@ func KeyInfo(slogger *slog.Logger) *table.Plugin { table.TextColumn("fingerprint_md5"), } - // we don't want the logging in osquery, so don't instantiate WithLogger() + // we don't want the logging in osquery, so don't instantiate WithSlogger() kIdentifer, err := keyidentifier.New() if err != nil { slogger.Log(context.TODO(), slog.LevelInfo, diff --git a/pkg/osquery/table/sshkeys.go b/pkg/osquery/table/sshkeys.go index 0c35e4acf..8d99b115a 100644 --- a/pkg/osquery/table/sshkeys.go +++ b/pkg/osquery/table/sshkeys.go @@ -37,7 +37,7 @@ func SshKeys(slogger *slog.Logger) *table.Plugin { table.TextColumn("fingerprint_md5"), } - // we don't want the logging in osquery, so don't instantiate WithLogger() + // we don't want the logging in osquery, so don't instantiate WithSlogger() kIdentifer, err := keyidentifier.New() if err != nil { slogger.Log(context.TODO(), slog.LevelInfo,