在IIS 7服务器中记下异常原因

时间:2013-11-04 10:21:41

标签: c# wcf iis

我正在使用C#和.NET Framework 4.0开发WCF RESTful服务。

我的所有方法都是这样的:

public List<User> GetAllUsers()
{
    List<User> usersList = null;
    OutgoingWebResponseContext ctx =
        WebOperationContext.Current.OutgoingResponse;

    try
    {
        using (var context = new AdnLineContext())
        {
            context.Configuration.ProxyCreationEnabled = false;
            if ((context.Users != null) &&
                (context.Users.Count() > 0))
            {
                usersList = context.Users.ToList();

                ctx.StatusCode = System.Net.HttpStatusCode.OK;
            }
            else
            {
                // No users found.
                ctx.SetStatusAsNotFound();
                ctx.SuppressEntityBody = true;
            }
        }
    }
    catch (Exception)
    {
        ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
        ctx.SuppressEntityBody = true;
    }

    return usersList;
}

如您所见,有一个catch块来处理未处理的异常并发送HTTP状态代码500作为响应。

我已将此添加到web.config以跟踪这些例外:

<system.diagnostics>
<sources>
  <source name="UserTraceSource" switchValue="Error, Information, Warning, ActivityTracing" >
    <listeners>
      <add name="xml"
         type="System.Diagnostics.XmlWriterTraceListener"
         initializeData="D:\logs\MyTraces.svclog" />
    </listeners>
  </source>
</sources>
<trace autoflush="true" />
</system.diagnostics>

但是当发生异常时我什么都没看到。

我需要添加到每个catch块以将ex.Message写入跟踪日志吗?

这是我的web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="MyProjectWCFService.MyProjectService"
               behaviorConfiguration="MyProjectServiceBehaviour">
        <endpoint address=""
                  contract="MyProjectWCFService.IMyProjectService"
                  behaviorConfiguration="restfulBehavior"
                  binding="webHttpBinding" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restfulBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MyProjectServiceBehaviour">

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <connectionStrings>
    <add name="MyProjectContext"
          providerName="System.Data.SqlClient"
          connectionString="Server=.\SQLEXPRESS;Database=MyProject;Integrated Security=True;MultipleActiveResultSets=True"/>
  </connectionStrings>
  <system.diagnostics>
    <sources>
      <source name="UserTraceSource" switchValue="Error, Information, Warning, ActivityTracing" >
        <listeners>
          <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="D:\log\MyProjectTraces.svclog" />
        </listeners>
      </source>
    </sources>
    <trace autoflush="true" />
  </system.diagnostics>
</configuration>

2 个答案:

答案 0 :(得分:0)

您需要使用Trace类来通知听众需要记录的内容,例如

catch (Exception ex)
{
    ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
    ctx.SuppressEntityBody = true;
    System.Diagnostics.Trace.WriteLine(ex.Message, "GetAllUsers"); // log exception
}

答案 1 :(得分:0)

错误发生在web.config上。我没有定义跟踪。

这就是我解决问题的方法:

<system.diagnostics>
<trace autoflush="true" >
  <listeners>
    <add name="myListener"
       type="System.Diagnostics.TextWriterTraceListener"
       initializeData="D:\log\MyProjectTraces.svclog" />
    <remove name="Default"/>
  </listeners>
</trace>
</system.diagnostics>

我也使用了詹姆斯的回答:

catch (Exception ex)
{
    ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
    ctx.SuppressEntityBody = true;
    System.Diagnostics.Trace.WriteLine(ex.Message, "GetAllUsers"); // log exception
}