2024-11-17 20:51:12 +00:00
|
|
|
//go:build windows
|
|
|
|
|
2023-04-22 10:17:51 +00:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-09-10 22:34:10 +00:00
|
|
|
"log/slog"
|
2023-04-22 10:17:51 +00:00
|
|
|
"os"
|
|
|
|
|
2024-10-03 18:23:56 +00:00
|
|
|
"github.com/prometheus-community/windows_exporter/internal/log/eventlog"
|
2024-09-10 22:34:10 +00:00
|
|
|
"github.com/prometheus/common/promslog"
|
|
|
|
"golang.org/x/sys/windows"
|
2023-04-22 10:17:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// AllowedFile is a settable identifier for the output file that the logger can have.
|
|
|
|
type AllowedFile struct {
|
|
|
|
s string
|
|
|
|
w io.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *AllowedFile) String() string {
|
|
|
|
return f.s
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set updates the value of the allowed format.
|
|
|
|
func (f *AllowedFile) Set(s string) error {
|
2023-07-21 18:18:15 +00:00
|
|
|
f.s = s
|
2024-09-10 22:34:10 +00:00
|
|
|
|
2023-04-22 10:17:51 +00:00
|
|
|
switch s {
|
|
|
|
case "stdout":
|
|
|
|
f.w = os.Stdout
|
|
|
|
case "stderr":
|
|
|
|
f.w = os.Stderr
|
|
|
|
case "eventlog":
|
2024-09-10 22:34:10 +00:00
|
|
|
handle, err := windows.RegisterEventSource(nil, windows.StringToUTF16Ptr("windows_exporter"))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to open event log: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
f.w = eventlog.NewEventLogWriter(handle)
|
2023-04-22 10:17:51 +00:00
|
|
|
default:
|
2024-08-10 20:05:33 +00:00
|
|
|
file, err := os.OpenFile(s, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o200)
|
2023-04-22 10:17:51 +00:00
|
|
|
if err != nil {
|
2024-09-10 22:34:10 +00:00
|
|
|
return fmt.Errorf("failed to open log file: %w", err)
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|
2024-09-10 22:34:10 +00:00
|
|
|
|
2023-04-22 10:17:51 +00:00
|
|
|
f.w = file
|
|
|
|
}
|
2024-09-10 22:34:10 +00:00
|
|
|
|
2023-04-22 10:17:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-10 20:05:33 +00:00
|
|
|
// Config is a struct containing configurable settings for the logger.
|
2023-04-22 10:17:51 +00:00
|
|
|
type Config struct {
|
2024-09-10 22:34:10 +00:00
|
|
|
*promslog.Config
|
2023-04-22 10:17:51 +00:00
|
|
|
|
|
|
|
File *AllowedFile
|
|
|
|
}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
func New(config *Config) (*slog.Logger, error) {
|
2023-04-22 10:17:51 +00:00
|
|
|
if config.File == nil {
|
|
|
|
return nil, errors.New("log file undefined")
|
|
|
|
}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
config.Config.Writer = config.File.w
|
2024-11-14 22:12:28 +00:00
|
|
|
config.Config.Style = promslog.SlogStyle
|
2023-04-22 10:17:51 +00:00
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
return promslog.New(config.Config), nil
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|