为了禁用 FirebirdSQL 日志记录,我需要将以下代码 ( See here ) 添加到 app.config:
<system.diagnostics>
<sources>
<source name="FirebirdSql.Data.FirebirdClient" switchValue="Off">
<listeners>
<clear />
</listeners>
</source>
</sources>
</system.diagnostics>
这成功了,即没有记录任何内容。 现在我已经在 C# 代码中执行此操作,但尽管我的代码,但所有内容都已记录:
TraceSource ts = new TraceSource("FirebirdSql.Data.FirebirdClient");
ts.Switch = new SourceSwitch("sourceSwitch", "Off");
var listeners = ts.Listeners;
listeners.Clear();
ts.Switch.Level = SourceLevels.Off;
我将其添加到执行 SQL 语句的程序集中。
我错过了什么?
最佳答案
这将禁用所有跟踪源,无论它们是如何注册的(在代码中或在配置中。)
当您创建一个 TraceSource(在代码或配置中)时,它会被添加到一个静态列表中。没有公共(public) API 可以访问该列表。但是那个“私有(private)”关键字是一个标志,让较小的开发人员服从,而不是我们。所以我们只是把它踢下来并引用我们理所当然的变量。然后我们可以添加/删除监听器,关闭跟踪标志——禁用跟踪的方法不止一种。
此示例将在单个方法中工作,但即使您没有像此示例那样对 TraceSource 的引用,该技术也将/应该工作。
TraceSource source = new TraceSource("foo");
SourceSwitch onOff = new SourceSwitch("onOff", "Verbose");
onOff.Level = SourceLevels.Verbose;
ConsoleTraceListener console = new ConsoleTraceListener();
source.Switch = onOff;
bool alreadyDone = false;
foreach (var listener in source.Listeners)
{
if (typeof(ConsoleTraceListener) == listener.GetType())
{
alreadyDone = true;
}
}
if (!alreadyDone)
{
source.Listeners.Add(console);
}
source.TraceInformation("Hellow World! The trace is on!");
List<WeakReference> traceSources =
(List<WeakReference>)typeof(TraceSource)
.GetField("tracesources", BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(source);
foreach (WeakReference weakReference in traceSources)
{
TraceSource target = (TraceSource)weakReference.Target;
source.TraceInformation(
"Somebody, in code or config, registered this trace source " + target.Name);
target.Listeners.Clear();
}
source.TraceInformation(
"Can you still see this? (No you can't, I cleared all the listeners)");
关于c# - 在 c# 代码中删除监听器/禁用跟踪源的日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16979668/