Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - Trace logs location, where to view them

Where do you see Trace.Write(""); logs while developing an MVC or WCF app? What is the correct place to look at?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When using the System.Diagnostics.Trace class, the Write method writes its trace output "to the trace listeners in the Listeners collection." The Trace.Listeners property by default only contains an instance of the DefaultTraceListener, which outputs messages to the debugger output window. To view those trace messages, you have to enable debugging, of course.

So if you debug your WCF service or ASP.NET app in Visual Studio, you will see the trace output in the VS Output pane. For example, this code:

System.Diagnostics.Trace.WriteLine("GetData method was called.");

...causes this output to appear:

debug output

If you don't want to run a debugger to see the trace output, you can remove the DefaultTraceListener and replace it with another, e.g., a TextWriterTraceListener that will output your trace to a file. This can be done by creating a web.config file with the following content (or just add the system.diagnostics section to your pre-existing web.config):

<configuration>
    <system.diagnostics>
      <trace autoflush="true" indentsize="4">
        <listeners>
          <remove name="Default" />
          <add name="myListener" type="System.Diagnostics.TextWriterTraceListener"
               initializeData="c:myListener.log" />
        </listeners>
      </trace>
    </system.diagnostics>
</configuration>

After that (assuming you are running in a mode that has access to write to the output location), your traces will be output to the specified file.

If you want to write your traces to the Event Log instead of to a file, you can do that too with an EventLogTraceListener:

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener"
          type="System.Diagnostics.EventLogTraceListener"
          initializeData="TraceListenerLog" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

Just take care to ensure that your app is running under an account context with access to write to the Event Log.

There is a lot more you can do with tracing (such as have it output to the ASP.NET page itself. You'll find a walkthrough with more examples here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...