Trace to a file : Trace « Development « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Tracing" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Logging trace output to <asp:Literal runat="server" Text="<%$ appSettings:traceFile %>" /></h2>
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.IO;
using System.Web;
using System.Configuration;

public partial class Tracing : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Trace.TraceFinished += Trace_Finished;
        Trace.Write("Using Page Trace", "Subscribed to TraceFinished event");
    }

    void Trace_Finished(Object sender, TraceContextEventArgs e)
    {
        string traceFile = ConfigurationManager.AppSettings["traceFile"];
        using (StreamWriter w = File.AppendText(traceFile))
        {
            int i = 0;
            foreach (TraceContextRecord r in e.TraceRecords)
                w.WriteLine("{0}) {1}:{2}", ++i, r.Category, r.Message);
        }
    }
}

File: Web.config

<?xml version="1.0"?>

<configuration>
  <appSettings>
    <add key="traceFile" value="c:\temp\trace_log.txt"/>
  </appSettings>
  <system.web>
    <compilation debug="true"/>
    <trace enabled="true" pageOutput="false" localOnly="true" />
  </system.web>
</configuration>








9.44.Trace
9.44.1.Trace.IsEnabled
9.44.2.Enable trace in Web.config
9.44.3.Enabling Page Level Tracing
9.44.4.Set Page.Trace.IsEnabled to true (C#)
9.44.5.Write warning message with Trace.Warn
9.44.6.Use Trace.Write to write message (C#)
9.44.7.Trace to a file