按代码添加应用程序侦听器

时间:2013-04-13 11:21:05

标签: c# wcf configuration app-config

我希望将所有内容转换为C#代码。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.diagnostics>
    <sources>
      <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="NewListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing" >
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="NewListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="Trace.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
          name="NewListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack">
        <filter type="" />
      </add>
    </sharedListeners>
  </system.diagnostics>

 </configuration>

这个配置做的是记录文件中发生的所有异常自动,我不需要为此编码。我正在搜索一个简单的方法将我的异常记录到svclog文件,直到客户端发送给我进行调试我想删除app.config并只使用C#代码。

1 个答案:

答案 0 :(得分:0)

我搜索了很多,所以我们不能自动完成,但这是一个很好的方法:

public static class myClass
{

    [XmlRoot("Exception"), System.Xml.Serialization.XmlType("Exception")]
    public class exception
    {
        public exception()
        {
            ExceptionType = "";
            appDomain = "";
            Message = "";
            StackTrace = "";
            ExceptionString = "";
            InnerException = null;
            HelpLink = "";
            TargetSite = "";
            Source = "";
        }

        internal exception(Exception ex)
        {
            ExceptionType = ex.GetType().ToString();
            appDomain = AppDomain.CurrentDomain.FriendlyName;
            Message = ex.Message;
            StackTrace = ex.StackTrace == null ? " - " : ex.StackTrace.ToString();
            HelpLink = ex.HelpLink == null ? " - " : ex.HelpLink.ToString();
            TargetSite = ex.TargetSite == null ? " - " : ex.TargetSite.ToString();
            Source = ex.Source == null ? " - " : ex.Source.ToString();
            ExceptionString = ex.ToString();
            if (ex.InnerException != null)
                InnerException = new exception(ex.InnerException);
        }

        [XmlElement("ExceptionType")]
        public string ExceptionType { get; set; }
        [XmlElement("AppDomain")]
        public string appDomain { get; set; }
        [XmlElement("Message")]
        public string Message { get; set; }
        [XmlElement("StackTrace")]
        public string StackTrace { get; set; }
        [XmlElement("ExceptionString")]
        public string ExceptionString { get; set; }
        [XmlElement("HelpLink")]
        public string HelpLink { get; set; }
        [XmlElement("TargetSite")]
        public string TargetSite { get; set; }
        [XmlElement("Source")]
        public string Source { get; set; }
        [XmlElement("InnerException")]
        public exception InnerException { get; set; }
    }

    private static System.Diagnostics.TraceSource TraceLogger { get; set; }

    static myClass()
    {
        var xml = new System.Diagnostics.XmlWriterTraceListener(System.IO.Directory.GetCurrentDirectory() + "\\ApplicationTrace.svclog");
        xml.TraceOutputOptions = System.Diagnostics.TraceOptions.Callstack | System.Diagnostics.TraceOptions.DateTime | System.Diagnostics.TraceOptions.LogicalOperationStack | System.Diagnostics.TraceOptions.ProcessId | System.Diagnostics.TraceOptions.ThreadId | System.Diagnostics.TraceOptions.Timestamp;

        TraceLogger = new System.Diagnostics.TraceSource("TraceLogger");
        TraceLogger.Switch.Level = System.Diagnostics.SourceLevels.All;
        TraceLogger.Listeners.Add(xml);

        TraceLogger.Flush();
        TraceLogger.Close();

    }

    private static void WriteException(Exception ex)
    {
        using (var writer = new StringWriter())
        {
            exception ee = new exception(ex);
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(ee.GetType());
            x.Serialize(writer, ee);
            var xmlEncodedList = writer.GetStringBuilder().ToString();
            XmlTextReader myXml = new XmlTextReader(new StringReader(xmlEncodedList));

            XPathDocument xDoc = new XPathDocument(myXml);
            XPathNavigator myNav = xDoc.CreateNavigator();
            TraceLogger.TraceData(System.Diagnostics.TraceEventType.Error, 0, myNav);
            TraceLogger.Flush();
        }
    }

    public static void HandleExceptions(Exception ex)
    {
       //do some thing then log
            WriteException(ex);
    }
}

您的应用程序中发生的每个错误都可以调用此方法,或者您可以使用application.DispatcherUnhandledException事件来捕获错误。


我们创建了一个可以使用xmlSerialization进行Serialize的异常类,然后我们有一个记录异常的静态跟踪源。