views:

344

answers:

2

Ok so I am trying to have error log file for the website running on ASP.net and C#.

I tried storing to drive with regular path. Expecting it because it is in c# code (code behind page) it will pick up the server and store it there. (In the end it is a code that gets executed on server)

Unfortunatelly for me thats not true. It gets saved on local machine from which client opens the site.

How can you force it to be saved on server machine?

I want all of the error logs on one place. Any suggestions on reading or how to do this.

   string path = "C:\\WebSite";
   string error = "error";          
   try
    {
      // check if dir exists if it does i add file name to the path
      // i removed code to keep it simple
      path += "\\logs.txt";

      FileStream log_fs = 
              new FileStream(path, FileMode.Append, FileAccess.Write);
      StreamWriter log_sw = 
              new StreamWriter(log_fs);
      string log = String.Empty;

      // formate log string using error message

      log_sw.Write(log);
      log_sw.Close();
      log_fs.Close();
   }
   catch (Exception ex)
   {
        // here I e-mail the error in case logging failed
   }

This code will generate file on local machine, instead of server

A: 

You can log to any location on the web server (that the ASPNET user account has permission to write to) with code such as this:

string log = String.Empty;

// format log string using error message

try
{
    using (StreamWriter logFile = new StreamWriter(@"C:\WebSite\logs.txt", true))
    {
        logFile.WriteLine(log);
    }
}
catch
{
    // here I e-mail the error in case logging failed
}

This will write the file to the web server hosting the website. Now, if you're running the website locally during development and you're using either the built-in VS webserver or IIS, then of course the file will be created on your machine when testing the website locally.

Bullines
A: 

To answer the suggestion portion of your question, have you considered using ELMAH, it will log errors to different storages:

Microsoft SQL Server Oracle (OracleErrorLog) SQLite (version 3) database file Microsoft Access (AccessErrorLog) VistaDB (VistaDBErrorLog) Loose XML files RAM (in-memory)

or send via email, twitter

elmah is very easy to setup and very effective

Jon