TraceSource和ASP.NET:适用于Web应用程序,而不适用于WebSites

Bul*_*nes 3 c# asp.net trace .net-4.0 tracesource

我正在向ASP.NET网站添加跟踪功能,所以我决定通过创建几个原型来研究TraceSource ; Web应用程序项目和网站项目.

我正在为每个项目使用类似的Web.config来记录到Windows事件日志的跟踪:

<configuration>
    <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0"/>
    </system.web>    
    <system.diagnostics>
        <trace autoflush="true" />
        <sources>
            <source name="HelloWorld">
                <listeners>
                    <add name="eventlogListener" />
                </listeners>
            </source>
        </sources>    
        <sharedListeners>
            <add name="eventlogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="My Source" />
        </sharedListeners>
    </system.diagnostics>
</configuration>
Run Code Online (Sandbox Code Playgroud)

我只是从以下基本跟踪开始:

private static TraceSource _ts = new TraceSource("HelloWorld", SourceLevels.All);

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    _ts.TraceEvent(TraceEventType.Information, 10, "Greetings from OnLoad.");
}
Run Code Online (Sandbox Code Playgroud)

使用Web应用程序项目,我可以看到在事件日志中创建的跟踪.但是,有了网站项目,我不能.

网站项目需要使用TraceSource的其他步骤(例如:web.config设置,权限等)吗?

Jos*_*shL 7

原因是因为如果将TRACE常量定义为编译的一部分,则Trace方法仅由.Net编译.在Web站点项目中,执行此操作的方法是在web.config文件中包含编译器配置,如下所示:

  <system.codedom>
    <compilers>
      <compiler
         language="c#;cs;csharp"
         extension=".cs"
         type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.50727.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
         compilerOptions="/d:TRACE"
         warningLevel="1" />
    </compilers>
  </system.codedom>
Run Code Online (Sandbox Code Playgroud)

请注意"/ d:TRACE"编译器选项,它在编译代码时启用TRACE常量(本例中为C#).