Hello,
I'm new to this mailing list. Sorry if this is not the appropriate way to
report a bug fix. Dereferencing HttpContext.Request will throw an exception
if you call it in an Asp.net application's Application_Start().
Thus, if you have log4net logging *and* you use a pattern layout format
like %aspnet-request{REMOTE_ADDR} *and* you call Log4net inside
Application_Start(), Log4net will throw an exception trying to log the
message. The stack will look like this:
log4net:ERROR [RollingFileAppender] ErrorCode: GenericFailure. Failed in
DoAppend
System.Web.HttpException (0x80004005): Request is not available in this
context
at System.Web.HttpContext.get_Request()
at
log4net.Layout.Pattern.AspNetRequestPatternConverter.Convert(TextWriter
writer, LoggingEvent loggingEvent, HttpContext httpContext)
at
log4net.Layout.Pattern.AspNetPatternLayoutConverter.Convert(TextWriter
writer, LoggingEvent loggingEvent)
at log4net.Layout.Pattern.PatternLayoutConverter.Convert(TextWriter
writer, Object state)
at log4net.Util.PatternConverter.Format(TextWriter writer, Object state)
at log4net.Layout.PatternLayout.Format(TextWriter writer, LoggingEvent
loggingEvent)
at log4net.Layout.Layout2RawLayoutAdapter.Format(LoggingEvent
loggingEvent)
Here is my proposed fix:
internal sealed class AspNetRequestPatternConverter :
AspNetPatternLayoutConverter
{
/// <summary>
/// Write the ASP.Net Cache item to the output
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will
receive the formatted result.</param>
/// <param name="loggingEvent">The <see cref="LoggingEvent" />
on which the pattern converter should be executed.</param>
/// <param name="httpContext">The <see cref="HttpContext" />
under which the ASP.Net request is running.</param>
/// <remarks>
/// <para>
/// Writes out the value of a named property. The property name
/// should be set in the <see
cref="log4net.Util.PatternConverter.Option"/>
/// property.
/// </para>
/// </remarks>
protected override void Convert(TextWriter writer,
LoggingEvent loggingEvent, HttpContext httpContext)
{
bool requestExists = true;
HttpRequest request = null;
try
{
request = httpContext.Request;
if (request == null)
requestExists = false;
}
catch (System.Web.HttpException)
{
requestExists = false;
}
if (requestExists)
{
if (Option != null)
{
WriteObject(writer, loggingEvent.Repository,
request.Params[Option]);
}
else
{
WriteObject(writer, loggingEvent.Repository,
request.Params);
}
}
else
{
writer.Write(SystemInfo.NotAvailableText);
}
}
}