Reputation: 59
I'm working on ASP.Net MVC web app, using System.Diagnostics.TraceSource to trace and log to file. Added following to web.config
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace> // what's this for?
<sources>
<source name ="WebAppLog">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="PartialView_WebApp.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
</system.diagnostics>
Added Log.cs to application to log mesages to file.
public class Log
{
static TraceSource source = new TraceSource("WebAppLog");
public static void Message(TraceEventType traceEventType, string message)
{
short id;
switch (traceEventType)
{
case TraceEventType.Information:
id = 3;
break;
case TraceEventType.Verbose:
id = 4;
break;
default:
id = -1;
break;
}
source.TraceEvent(traceEventType, id, message);
source.Flush();
}
}
Home controller.cs
public ActionResult Index()
{
try
{
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action Start");
// Do work
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action End");
return View();
}
catch (Exception ex)
{
throw;
}
}
After executing, i'm able to generate log file but couldn't write anything, always the file size is 0 bytes. What could be the possible mistake.?
Upvotes: 1
Views: 5445
Reputation: 23214
The Switch
on a TraceSource
determines whether any output gets generated.
By default, if it is not configured, there will be no output.
The value for the Switch
matches the log levels that should appear in the output.
It can be set via code:
static TraceSource source = new TraceSource("WebAppLog");
source.Switch.Level = SourceLevels.Verbose;
Or via configuration, which is more flexible. Your configuration will look like:
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace>
<sources>
<source name ="WebAppLog" switchName="mySwitch">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\tmp\trace.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
<switches>
<add name="mySwitch" value="Verbose" />
</switches>
</system.diagnostics>
<trace autoflush="false" indentsize="4"></trace>
With autoflush=true
you don't have to call source.Flush()
explicitly.
The indentsize
gets applied in the log output, notice the leading whitespace starting from line 2 in the output fragment below.
WebAppLog Information: 3: Index Action Start
ProcessId=7416
LogicalOperationStack=
ThreadId=1
Upvotes: 3