1

我正在使用 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>
4

2 回答 2

0

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

catch (Exception ex)
{
    ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
    ctx.SuppressEntityBody = true;
    System.Diagnostics.Trace.WriteLine(ex.Message, "GetAllUsers"); // log exception
}
于 2013-11-04T10:31:20.687 回答
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
}
于 2013-11-04T12:09:49.040 回答