mirror of
https://github.com/prometheus-community/windows_exporter.git
synced 2026-10-17 10:09:05 +02:00
fix: log startup errors to the event log when running as a service (#2506)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Jan-Otto Kröpke <mail@jkroepke.de>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
485fcb8d24
commit
ba682be668
@@ -7,6 +7,7 @@ on:
|
||||
- synchronize
|
||||
- labeled
|
||||
- unlabeled
|
||||
- edited
|
||||
|
||||
permissions: {}
|
||||
|
||||
|
||||
@@ -18,8 +18,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"unsafe"
|
||||
@@ -161,6 +163,22 @@ func logToEventToLog(eType uint16, msg string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// logStartupError logs an error that occurs before the configured logger exists.
|
||||
// A service has no console to receive the default stderr output,
|
||||
// so the error is written to the event log as well.
|
||||
func logStartupError(ctx context.Context, msg string, err error) {
|
||||
if IsService {
|
||||
if logErr := logToEventToLog(windows.EVENTLOG_ERROR_TYPE, fmt.Sprintf("%s: %v", msg, err)); logErr != nil {
|
||||
logToFile(fmt.Sprintf("%s: %v", msg, err))
|
||||
}
|
||||
}
|
||||
|
||||
//nolint:sloglint // We do not have a logger yet.
|
||||
slog.LogAttrs(ctx, slog.LevelError, msg,
|
||||
slog.Any("err", err),
|
||||
)
|
||||
}
|
||||
|
||||
func logToFile(msg string) {
|
||||
if file, err := os.CreateTemp("", "windows_exporter.service.error.log"); err == nil {
|
||||
_, _ = file.WriteString(msg)
|
||||
|
||||
@@ -128,10 +128,7 @@ func run(ctx context.Context, args []string) int {
|
||||
collectors := collector.NewWithFlags(app)
|
||||
|
||||
if err := config.Parse(app, args); err != nil {
|
||||
//nolint:sloglint // we do not have an logger yet
|
||||
slog.LogAttrs(ctx, slog.LevelError, "Failed to load configuration",
|
||||
slog.Any("err", err),
|
||||
)
|
||||
logStartupError(ctx, "Failed to load configuration", err)
|
||||
|
||||
return 1
|
||||
}
|
||||
@@ -140,9 +137,7 @@ func run(ctx context.Context, args []string) int {
|
||||
|
||||
logger, err := log.New(logConfig)
|
||||
if err != nil {
|
||||
logger.LogAttrs(ctx, slog.LevelError, "failed to create logger",
|
||||
slog.Any("err", err),
|
||||
)
|
||||
logStartupError(ctx, "failed to create logger", err)
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user