Skip to content

Commit

Permalink
Enable service logging options when running as windows service
Browse files Browse the repository at this point in the history
When running as a windows service, the collector's logger zapcore.Core is replaced
by a customized zapcore.Core that writes the logs to the EventViewer ignoring what is
configured in the yaml.
Instead of replacing it, the PR creates a Tee that preserves the original Core and its
configuration, and adds the customized Core for EventViewer. This way logs are
duplicated and flushed by both Cores.
  • Loading branch information
xborder committed Jan 25, 2023
1 parent 1af31a0 commit a88ca9f
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions otelcol/collector_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func newWithWindowsEventLogCore(set CollectorSettings, flags *flag.FlagSet, elog
}
}
set.LoggingOptions = append(
[]zap.Option{zap.WrapCore(withWindowsCore(elog))},
[]zap.Option{zap.WrapCore(withEventViewer(elog))},
set.LoggingOptions...,
)
return NewCollector(set)
Expand All @@ -164,13 +164,13 @@ func newWithWindowsEventLogCore(set CollectorSettings, flags *flag.FlagSet, elog
var _ zapcore.Core = (*windowsEventLogCore)(nil)

type windowsEventLogCore struct {
core zapcore.Core
elog *eventlog.Log
encoder zapcore.Encoder
levelEnabled func(zapcore.Level) bool
elog *eventlog.Log
encoder zapcore.Encoder
}

func (w windowsEventLogCore) Enabled(level zapcore.Level) bool {
return w.core.Enabled(level)
return w.levelEnabled(level)
}

func (w windowsEventLogCore) With(fields []zapcore.Field) zapcore.Core {
Expand All @@ -179,9 +179,9 @@ func (w windowsEventLogCore) With(fields []zapcore.Field) zapcore.Core {
field.AddTo(enc)
}
return windowsEventLogCore{
core: w.core,
elog: w.elog,
encoder: enc,
levelEnabled: w.levelEnabled,
elog: w.elog,
encoder: enc,
}
}

Expand Down Expand Up @@ -217,13 +217,14 @@ func (w windowsEventLogCore) Write(ent zapcore.Entry, fields []zapcore.Field) er
}

func (w windowsEventLogCore) Sync() error {
return w.core.Sync()
//flushing is not supported by windows/svc/eventlog
return nil
}

func withWindowsCore(elog *eventlog.Log) func(zapcore.Core) zapcore.Core {
func withEventViewer(elog *eventlog.Log) func(zapcore.Core) zapcore.Core {
return func(core zapcore.Core) zapcore.Core {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.LineEnding = "\r\n"
return windowsEventLogCore{core, elog, zapcore.NewConsoleEncoder(encoderConfig)}
return zapcore.NewTee(core, windowsEventLogCore{core.Enabled, elog, zapcore.NewConsoleEncoder(encoderConfig)})
}
}

0 comments on commit a88ca9f

Please sign in to comment.