我正在开发ASP.Net MVC web应用程序,使用System.Diagnostics.TraceSource跟踪并记录到文件。添加到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>将Log.cs添加到应用程序中,以记录到文件中的模型。
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();
}
}家庭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;
}
}执行后,我可以生成日志文件,但是什么都写不出来,文件大小总是0字节。什么是可能的错误?
发布于 2018-07-17 17:21:18
Switch上的TraceSource决定是否生成任何输出。
默认情况下,如果未对其进行配置,则将没有输出。
Switch的值与输出中应该显示的日志级别相匹配。
它可以通过代码设置:
static TraceSource source = new TraceSource("WebAppLog");
source.Switch.Level = SourceLevels.Verbose; 或者通过更灵活的配置。您的配置如下所示:
<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>使用autoflush=true,您不必显式地调用source.Flush()。
在日志输出中应用indentsize,注意下面输出片段中从第2行开始的前导空格。
WebAppLog Information: 3: Index Action Start
ProcessId=7416
LogicalOperationStack=
ThreadId=1https://stackoverflow.com/questions/51386660
复制相似问题