Search code examples
c#asp.netloggingexceptiontrace

Trace C# Log Details


Is it possible to write a code to trace a log wrote in c#?. For example:

string filePath = @"C:\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
    writer.WriteLine("Message :" + ex.Message );
}

Now i want to write a code trace exception message (ex.Message) without open Error.txt.(Note: Code should work for trace any website developed in asp.net+c#).


Solution

  • Of course, there's a powerful built-in mechanism for tracing in .NET platform. Refer to that and MSDN documentation. It's implemented through static classes, so you can use it anywhere in your code. First step is to configure trace listeners via code or .config file:

    Trace.Listeners.Add(new TextWriterTraceListener("trace.log");
    

    Then, to log a message just call:

    Trace.WriteLine(ex.ToString());
    

    If you just need to check periodically if a certain website is online, you can write something simple like this:

    Timer t = new Timer(60000);
    t.Elapsed += (sender, e) =>
    {
        try
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://google.com");
            using (HttpWebResponse httpRes = (HttpWebResponse) httpReq.GetResponse())
            {
                if (httpRes.StatusCode != HttpStatusCode.OK)
                {
                    File.AppendAllText(@"C:\Error.txt",
                        string.Format("Server error: {0} {1}",
                         httpRes.StatusCode, httpRes.StatusDescription));
                }
            }
        }
        catch (Exception exc)
        {
            File.AppendAllText(@"C:\Error.txt", "Error: "+exc.ToString());
        }
    };
    t.Start();
    

    Or use universal monitoring solution like Zabbix.