您好,是否可以在不重新启动 WCF 服务的情况下更改跟踪侦听器应记录的 TraceEventType 级别?我让用户配置跟踪应记录的内容,将其发送到服务,然后将其写入配置文件。该解决方案需要在更改生效之前重新启动服务...
最佳丹尼尔
这比我想象的要容易。我跟踪 TraceSources 并在用户希望更改时设置它们的开关级别。
private static void SetLogLevel(TraceSource traceSource, LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Verbose:
traceSource.Switch.Level = SourceLevels.Verbose;
break;
case LogLevel.Information:
traceSource.Switch.Level = SourceLevels.Information;
break;
case LogLevel.Warning:
traceSource.Switch.Level = SourceLevels.Warning;
break;
case LogLevel.Error:
traceSource.Switch.Level = SourceLevels.Error;
break;
case LogLevel.Critical:
traceSource.Switch.Level = SourceLevels.Critical;
break;
default:
throw new ArgumentOutOfRangeException("logLevel");
}
}
Run Code Online (Sandbox Code Playgroud)
我还在配置文件中写入,以便下次启动服务时跟踪源将获得相同的开关级别。
public TraceSourceConfiguration SetLogConfiguration(TraceSourceConfiguration traceSourceConfiguration)
{
lock (_lock)
{
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection configurationSection = appConfig.GetSection(ConfigurationSectionName);
PropertyInformation traceSourceSection =
configurationSection.ElementInformation.Properties[TraceSourcesSectionName];
if (traceSourceSection != null)
{
ConfigurationElementCollection traceSources =
(ConfigurationElementCollection)traceSourceSection.Value;
foreach (ConfigurationElement traceSource in traceSources)
{
string name = (string)traceSource.ElementInformation.Properties[LogLevelNameElementName].Value;
if (traceSourceConfiguration.Name == name)
{
traceSource.ElementInformation.Properties[LogLevelValueElementName].Value =
traceSourceConfiguration.SwitchValue;
appConfig.Save();
ConfigurationManager.RefreshSection(ConfigurationSectionName);
TraceSourceHandler.SetTraceSourceSwitchLevel(traceSourceConfiguration.Name, traceSourceConfiguration.SwitchValue);
return traceSourceConfiguration;
}
}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)