Strange behaviour in Production environnement

S

Smith

Hello experts,

I have the following peice of code in my Global.asax

void Application_Error(object sender, EventArgs e)

{

//get reference to the source of the exception chain

Log log = new Log();

Exception ex = Server.GetLastError();

log.AddLogEntry(Request, ex);

log.SaveData();

Response.Redirect("~/Error.aspx");






}



This code works well on my test server Win2k3 , IIS 6. It write to my
erro.log text file and displays Error.aspx as expected.



In Production( Win2k3 , IIS 6) , it open the file error.log(Can be seen on
last modified date) but the expection is not written to the file. Neither is
Error.aspx displayed. Can someone tell were i should be looking?





Many thanks in advance .

S
 
M

Med

Hi,

Does asp.net process has write /modify permission on the folder/file that
you are attemting to write? I would also use:
Server.ClearError(); before redirecting.


Regards


Med
 
S

Smith

Med said:
Hi,

Does asp.net process has write /modify permission on the folder/file that
you are attemting to write? I would also use:
Server.ClearError(); before redirecting.

The user asp.net process is running under har full permission in the folder
where the code lives.Also note that the modified date of the error file
actually change according to the time error occured. It this was permission
problem, would it be allowed to actually open the file?
How does ServerClear() helps here?

Thanks
S
 
M

Med

Hi,
The user asp.net process is running under har full permission in the
folder where the code lives.
Does the log folder/file resides in this folder?

Actually Server.ClearError(); was irrelavant to your problem here, it was
just a suggestion as it prevents the error from continuing to the
Application_Error event handler.

Could you send the code for AddLogEntry(Request, ex)?

This is how I do it:

<%@ Import Namespace = "System.IO" %>
<%@ Import Namespace = "System.Diagnostics" %>

void Application_Error(object sender, EventArgs e)
{
//Only redirect to error page if in Release mode.
#if DEBUG
{
//Show error details
}
#else
{
try
{
LogError(Server.GetLastError().GetBaseException());
Server.ClearError();
}
catch
{
//Do something.....
}

//Redirect to error.aspx page
Response.Redirect("error.aspx");
}
#endif
}

private void LogError(Exception objError)
{

try
{
string sLogFilePathAndName = String.Format(@"{0}{1} {2}.log",
Server.MapPath("~/Logs/"), DateTime.Now.ToLongDateString(),
DateTime.Now.DayOfWeek);
using (StreamWriter sw = File.AppendText(sLogFilePathAndName))
{
sw.WriteLine(Environment.NewLine);
sw.WriteLine(String.Format("Error Caught in Application on
{0} {1} @ {2}", DateTime.Now.DayOfWeek, DateTime.Now.ToLongDateString(),
DateTime.Now.ToLongTimeString()));
sw.WriteLine(String.Format("IP Address: {0}",
Request.ServerVariables["REMOTE_ADDR"].ToString()));
sw.WriteLine(String.Format("Platform: {0}",
Request.Browser.Platform));
sw.WriteLine(String.Format("Browser: {0}",
Request.Browser.Type));
sw.WriteLine(String.Format("Error in: {0}",
Request.Url.ToString()));
sw.WriteLine(String.Format("Error Message: {0}",
objError.Message.ToString()));
sw.WriteLine("Stack Trace:");
sw.WriteLine(objError.StackTrace.ToString());
sw.WriteLine(Environment.NewLine);
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.Close();
}
}
catch
{
//Do something.....
}
}


You may also want to look at:
http://support.microsoft.com/default.aspx?scid=kb;en-us;306355


Hope it helps

Med
 
S

Smith

I use the same log class as in the project :
http://www.asp.net/downloads/starter-kits/my-web-pages/

//===============================================================================================

//

// (c) Copyright Microsoft Corporation.

// This source is subject to the Microsoft Permissive License.

// See
http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.

// All other rights reserved.

//

//===============================================================================================

using System;

using System.Web;

using System.Collections.Generic;

using System.Collections.Specialized;

namespace MyWebPagesStarterKit

{

/// <summary>

/// Utility for writing error messages to a Logfile

/// </summary>

[Serializable]

public class Log : Persistable<Log.LogData>

{

/// <summary>

/// Load Log File from App_Data

/// </summary>

public Log()

{

try

{

LoadData();

}

catch { }

}

/// <summary>

/// List of all Log-Entries in the Logfile

/// </summary>

public List<LogData.LogEntry> Entries

{

get { return _data.LogEntries; }

}

/// <summary>

/// Adding a new Log-Entry to the LogData

/// </summary>

/// <param name="Created"></param>

/// <param name="PageTitle"></param>

public void AddLogEntry(HttpRequest httpRequest, Exception ex)

{

LogData.LogEntry entry = new LogData.LogEntry();

//PageTitle

entry.PageTitle = httpRequest.Url.AbsolutePath;

//Date

entry.Created = DateTime.Now.ToLongDateString() + " " +
DateTime.Now.ToLongTimeString();

//Error

entry.Error = ex.ToString();

//HTTP-Values

foreach (string key in httpRequest.ServerVariables)

{

string value = httpRequest.ServerVariables[key];

if (value != string.Empty)

{

if (key == "ALL_HTTP" || key == "ALL_RAW")

value = value.Replace(System.Environment.NewLine, ", ");

entry.ServerVariables.Add(key + ": " + value);


}

}



/===============================================================================================

//

// (c) Copyright Microsoft Corporation.

// This source is subject to the Microsoft Permissive License.

// See
http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.

// All other rights reserved.

//

//===============================================================================================

using System;

using System.Web;

using System.IO;

using System.Xml.Serialization;

using System.Web.Caching;

namespace MyWebPagesStarterKit

{

/// <summary>

/// Generic class for a perssitable object. Encapsulates the logic to
load/save data from/to the filesystem. To speed up the acces, caching is
used.

/// </summary>

/// <typeparam name="T">class or struct with all the data-fields that must
be persisted</typeparam>

public abstract class Persistable<T>

{

private String _path;

protected T _data;

/// <summary>

/// Creates a instance of Persistable. Also creates a instance of T

/// </summary>

public Persistable()

{

_data = (T)Activator.CreateInstance(typeof(T));

}

/// <summary>

/// Loads the data from the filesystem. For deserialization a XmlSeralizer
is used.

/// </summary>

protected void LoadData()

{

_path = HttpContext.Current.Server.MapPath(GetDataFilename());

lock (_path)

{

//first check, if the object is maybe already in the cache

object o = HttpContext.Current.Cache[_path];

if (o != null)

{

_data = (T)o;

}

else

{

//if nothing was found in the cache, the data must be loaded from the disk

//load and deserialize the data from the filesystem

using (FileStream reader = File.Open(_path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite))

{

XmlSerializer serializer = new XmlSerializer(typeof(T));

_data = (T)serializer.Deserialize(reader);

}

HttpContext.Current.Cache.Insert(_path, _data);

}

}

}

/// <summary>

/// Persists the data back to the filesystem

/// </summary>

public void SaveData()

{

_path = HttpContext.Current.Server.MapPath(GetDataFilename());

lock (_path)

{

//insert the data into the cache

HttpContext.Current.Cache.Insert(_path, _data, null, DateTime.MaxValue,
TimeSpan.FromHours(1), CacheItemPriority.Normal, null);

//if the given path does not exist yet, create it

if (!Directory.Exists(Path.GetDirectoryName(_path)))

Directory.CreateDirectory(Path.GetDirectoryName(_path));

//serialize and store the data to the filesystem

using (FileStream writer = File.Create(_path))

{

XmlSerializer serializer = new XmlSerializer(typeof(T));

serializer.Serialize(writer, _data);

}

}

}

//Deletes the data from the cache and filesystem

public virtual bool Delete()

{

bool success = true;

if (File.Exists(_path))

{

lock (_path)

{

try

{

File.Delete(_path);

HttpContext.Current.Cache.Remove(_path);

}

catch { success = false; }

}

}

return success;

}

protected abstract string GetDataFilename();

}

}

Cheers

S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top