Skip to content

Timer for Diagnostic Events log flush is initialized on startup, even when no events are written #11098

Closed
@cjaliaga

Description

@cjaliaga

The timer used to periodically flush logs for DiagnosticEvents is currently initialized as soon as the singleton Repository is created, regardless of whether any events are ever written.

With the change in Service Provider implementation in the OOP host, this behavior changed: singletons are now initialized eagerly at startup by JobHostScopedServiceProviderFactory

var jobHostServices = _rootProvider.CreateChildContainer(_rootServices);

As a result, the Repository singleton—and its flush timer—are both created immediately when the child container is created, whether or not the Repository is ever actually resolved in the DiagnosticEventLogger. This means the timer is running even if no events are ever written

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
// Exit early if logging is not enabled or the state is not a diagnostic event
if (!IsEnabled(logLevel) ||
(_diagnosticEventRepository != null && !_diagnosticEventRepository.IsEnabled()) ||
!(state is IDictionary<string, object> stateInfo && IsDiagnosticEvent(stateInfo)))
{
return;
}
string message = formatter(state, exception);
_diagnosticEventRepository ??= _diagnosticEventRepositoryFactory.Create();
_diagnosticEventRepository.WriteDiagnosticEvent(DateTime.UtcNow, stateInfo[ScriptConstants.ErrorCodeKey].ToString(), logLevel, message, stateInfo[ScriptConstants.HelpLinkKey].ToString(), exception);
}

Expected behavior

The timer should only be initialized the first time an event is actually written, rather than eagerly on startup. This would avoid unnecessary background timers in instances that never write any diagnostic event.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions