Writing Custom ASP.NET Trace Messages

ASP.NET tracing enables you to append custom trace information to the end of an ASP.NET page or to the trace log. The trace information written to the trace log is viewable with the trace viewer. For more information, see How to: View ASP.NET Trace Information with the Trace Viewer.

You can write trace information using the TraceContext class's Warn or Write methods. The difference between the two methods is that a message written with the Warn method appears in red text.

For information on enabling tracing for a page, see How to: Enable Tracing for an ASP.NET Page. For information on enabling tracing for an application, see How to: Enable Tracing for an ASP.NET Application.

The following code example demonstrates using the TraceContext class to display trace information at the end of an ASP.NET page. A different exception is thrown for each LinkButton control that caused the postback. The error message used to initialize the ArgumentException or InvalidOperationException is displayed in the trace log.

<%@ Page Language="C#" Trace="true"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
void Page_Load(object sender, EventArgs e)
    try {
      if (IsPostBack)
        switch (Request.Form["__EVENTTARGET"])
          case "WarnLink":
            throw new ArgumentException("Trace warn.");
          case "WriteLink":
            throw new InvalidOperationException("Trace write.");
            throw new ArgumentException("General exception.");
    catch (ArgumentException ae) {    
        Trace.Warn("Exception Handling", "Warning: Page_Load.", ae);
    catch (InvalidOperationException ioe) {    
        Trace.Write("Exception Handling", "Exception: Page_Load.", ioe);


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Trace Example</title>
    <form id="form1" runat="server">
      <asp:LinkButton id="WriteLink" 
                      text="Generate Trace Write" />
      <asp:LinkButton id="WarnLink"
                      text="Generate Trace Warn" />

See Also