TraceSource and TraceListener quietly fail to do anything

无人久伴 提交于 2019-12-01 14:32:18

I'm so glad you asked! This problem happened to me recently. I suspected something in the chain of TraceSwitches, TraceSources and TraceListeners had gone awry. But with no trace and no error messages, I needed more information. The authors of the BCL helpfully put all the diagnostic information in a private list whose values disappear when ever the garbage collector feels like it. Still, the info was good enough and accessible via reflection. It turned out that I had several TraceSource's but the one in question didn't have a Switch set to something other than Off. (Another bad sign would be no listeners or only the "Default" listener)

This is the Page_Load event for a page with a label called DumpText. I'm sure this code could be adapted for Console or WinForms.

protected void Page_Load(object sender, EventArgs e)
{
    TraceSource ts = new TraceSource("foo");
    List<WeakReference> list = (List<WeakReference>)GetInstanceField(typeof(TraceSource), ts, "tracesources");
    Dictionary<string, TraceSource> sources = new Dictionary<string, TraceSource>();
    foreach (var weakReference in list)
    {
        if (!weakReference.IsAlive) continue;
        TraceSource source = (weakReference.Target as TraceSource);
        if (source == null || source.Name == "foo") continue;
        if (sources.ContainsKey(source.Name)) continue;
        sources.Add(source.Name, source);
    }
    StringBuilder sb = new StringBuilder();

    foreach (KeyValuePair<string,TraceSource> kvp in sources.OrderBy((x) => x.Key))
    {
        TraceSource source = kvp.Value;
        if (source == null)
        {
            continue;
        }
        sb.Append("<h3>");
        sb.Append(source.Name);
        sb.Append(" - ");
        sb.Append(source.Switch.Level);
        sb.Append("</h3>");

        if (source.Switch.Level == SourceLevels.Off)
        {
            continue;
        }
        foreach (TraceListener l in source.Listeners)
        {
            sb.Append(l.Name);
            sb.Append(" - ");
            sb.Append(l.GetType().ToString());
            sb.Append("<br/>");

            foreach (string att in l.Attributes.Values)
            {
                sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sb.Append(att);
                sb.Append(",");
            }
        }
        sb.Append("<br/>");
    }
    this.DumpText.Text = sb.ToString();
}

internal static object GetInstanceField(Type type, object instance, string fieldName)
    {
        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
            | BindingFlags.Static;
        FieldInfo field = type.GetField(fieldName, bindFlags);
        return field.GetValue(instance);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!