TraceSource and ASP.NET: Works for Web Applications, not WebSites
I'm adding tracing functionality to an ASP.NET website so I decided to investigate TraceSource by creating a couple of prototypes; a Web Application project and a Website project.
I'm using similar Web.config for each project to log traces to the Windows Event Log:
<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>
I'm simply starting with the following basic trace:开发者_开发百科
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.");
}
With the Web Application project, I can see the trace created in the Event Log. However, with the Website project, I cannot.
Are additional steps (Ex: web.config settings, permissions, etc) required with the Website projects to use TraceSource?
The reason for this is because the Trace methods are only compiled by .Net if the TRACE constant is defined as part of the compile. In a Web Site project, the way to do this is to include compiler configuration in your web.config file, like this:
<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>
Note the "/d:TRACE" compiler option, which enables the TRACE constant when compiling your code (C# in this example).
After some trial and error, apparently the system.codedom\compilers node is required in the web.config, but I'm not entirely sure why.
精彩评论