log4net with ASP.NET 3.5 problems - asp.net

I'm having some trouble getting log4net to work from ASP.NET 3.5. This is the first time I've tried to use log4net, I feel like I'm missing a piece of the puzzle.
My project references the log4net assembly, and as far as I can tell, it is being deployed successfully on my server.
My web.config contains the following:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler
, log4net"
requirePermission="false"/>
</configSections>
<log4net>
<appender name="InfoAppender" type="log4net.Appender.FileAppender">
<file value="..\..\logs\\InfoLog.html" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern
value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<logger name="_Default">
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</logger>
</log4net>
I'm using the following code to test the logger:
using log4net;
using log4net.Config;
public partial class _Default : System.Web.UI.Page
{
private static readonly ILog log = LogManager.GetLogger("_Default");
protected void Page_Load(object sender, EventArgs e)
{
log.Info("Hello logging world!");
}
}
In my Global.asax, I'm doing the following:
void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
At this point, I can't think of what else I might be doing wrong. The directory I'm trying to store the log in is writable, and even if I try different directories I get the same result: no file, no logs.
Any suggestions? :-)
Edit: I've tried several different formats for the path & name of the log file, some of which include "..\..\InfoLog.html", "InfoLog.html", "logs\InfoLog.html", etc, just in case someone is wondering if that's the problem.
Edit: I've added the root logger node back into the log4net section, I ommitted that on accident when copying from the samples. The root logger node looks like this:
<root>
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</root>
Even with it, however, I'm still having no luck.

The root logger is mandatory I think. I suspect configuration is failing because the root doesn't exist.
Another potential problem is that Configure isn't being pointed to the Web.config.
Try Configure(Server.MapPath("~/web.config")) instead.

It sounds very much like a file permissions issue to me. If you specify a file name without any path, log4net will write to the root directory of the web application. Try that. Barring any success there, I'd recommend you enable internal log4net debugging by putting the following in your web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
Then, deploy the app compiled in debug mode and run the visual studio remote debugger to see any errors that are thrown.

Iv just spent 3 hours trying to fix this problem is the end it was the web.config formatting.
I had this, and it didn't work:
<section name="SubSonicService" type="SubSonic.SubSonicSection, SubSonic" requirePermission="false"/>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler
, log4net"
requirePermission="false"/>
changing it to this fixed it:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" requirePermission="false"/>
Annoying!!

Just for info: the file path must be formatted as follows:
<file value="..\\..\\logs\\InfoLog.html" />

A simple configuration tutorial from CodeProject

I don't have the Global.asx to run in .net 3.5
this is my code... I configure the log4net in a separate file log4net.config
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
//My Web Services class name
private static readonly log4net.ILog log = log4net.LogManager.GetLogger("Service1");

i had the same (frustrating) problem. i moved the root to the top of the log4net config section and it all worked. Also, i too had root and a logger element, this resulted in two lines each time i made a call to the logger. i removed the logger element and simply keep the root and its working great.

How about creating the logger with the page's type, like this:
private static readonly ILog log = LogManager.GetLogger(typeof(_Default));

This is what i have in Global.ASX. Got it all working in asp.net 3.5
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
log4net.Config.XmlConfigurator.Configure();
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
log4net.LogManager.Shutdown();
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

Related

Add custom response header to web.config

I have a website that is susceptible to a clickjacking vulnerability. Doing some research, it looks like one of the simple approaches is to simply add the X-Frame-Options: SAMEORIGIN to the response header. This is a very old web application (ca. last update was 2004), and is running IIS 6 with ASP.NET 2.0.
In newer versions, I could simply add the following section to the web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
</system.webServer>
And that would be the end of it. However, I can't seem to be able to verify that this is possible using IIS 6.
Is this possible with IIS 6 and ASP.NET 2.0 to be done in only the web.config file? If so, how? If not, what code changes would I have to make in order to achieve the same result? Would simply adding
Context.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
to the Global.asax#Application_EndRequest be sufficient?
I don't believe that you'll be able to accomplish this solely by updating the web.config since you are targeting II6 (as support for the <customHeaders> section was added in IIS7+).
What you would likely need to do would be to create a custom HttpModule similar to the approach mentioned in this blog post that would handle actually adding the Header which might look something like this :
public class SameOriginHeaderModule : IHttpModule
{
private HttpApplication _application;
public void Init(HttpApplication context)
{
_application = context;
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
void context_EndRequest(object sender, EventArgs e)
{
// If your request exists, add the header
if (_application.Context != null)
{
var response = _application.Response;
response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
}
}
public void Dispose()
{
}
}
You would then need to register this module within your web.config file as seen below :
<configuration>
<system.web>
<httpModules>
<add name="SameOriginHeaderModule" type="SameOriginHeaderModule" />
</httpModules>
</system.web>
</configuration>

View not found error when enabling error pages in ASP.NET MVC project

In my ASP.NET MVC project I have the /errors/error.html page as a general error page and a second /errors/error404.aspx that handles the 404 errors.
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/errors/error.html">
<error statusCode="404" redirect="/errors/error404.aspx" />
</customErrors>
Also, I have in my Global.asax file a general handler that logs all uncaught exceptions for logging purposes.
public void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Common.Core.LogError(ex); // Saving exception details in the database
}
The above setup works well except for when I have a general error (e.g. a 500 error) the Application_Error logs this error below:
The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/app/Error.aspx
~/Views/app/Error.ascx
~/Views/Shared/Error.aspx
~/Views/Shared/Error.ascx
~/Views/app/Error.cshtml
~/Views/app/Error.vbhtml
~/Views/Shared/Error.cshtml
~/Views/Shared/Error.vbhtml
The Exception from the actual error is not logged at all.
How can I avoid this error?
P.S. For anyone who might ask, I tried to put my error pages as views inside a controller but also I couldn't make it work with the redirectMode="ResponseRewrite" option.
You are trying to handle errors in a non-ASP.NET MVC way, in an ASP.NET MVC project. To resolve your issue, you could comment the line filters.Add(new HandleErrorAttribute()); in the FilterConfig.cs file. See the snippet below.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
}
}

Fastest way to rewrite only one subpath

I have a website developed in Classic ASP.NET and running on IIS 7.5. It works okay. But now I have the task to add affiliate program to my website. I want my reflink to looks like www.mywebsite.com/r/userid. Well, I googled around and found I can:
Use UrlRewrite third-party HttpModules. As I understand, they are based on runAllManagedModulesForAllRequests="true" web.config setting. Theoretically, I can:
Set runAllManagedModulesForAllRequests="true" and do RewritePath in Application_BeginRequest manually. But my Application_BeginRequest already contains a bit of code. It is too heavy to send all pages, images etc. to Application_BeginRequest because of one rarely called URL.
So, the question is how can I rewrite only subpath that starts with www.mywebsite.com/r/, and do not call Application_BeginRequest for every image, css etc.? Best if no third-party things.
Well, finished up with HttpModule.
web.config:
<system.webServer>
<modules>
<add name="ReflinkModule" preCondition="" type="www.ReflinkModule" />
</modules>
</system.webServer>
ReflinkModule.cs:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
if (HttpContext.Current == null)
return;
if (HttpContext.Current.Request == null)
return;
if (HttpContext.Current.Request.RawUrl == null)
return;
string start = "/r/";
if (!HttpContext.Current.Request.RawUrl.StartsWith(start))
return;
string key = HttpContext.Current.Request.RawUrl.Substring(start.Length);
HttpContext.Current.RewritePath("~/Xxxxx.aspx?r=" + key);
}

HttpModule EndRequest handler called twice

I am attempting to implement authentication for a REST service implemented in WCF and hosted on Azure. I am using HttpModule to handle the AuthenticationRequest, PostAuthenticationRequest and EndRequest events. If the Authorization header is missing or if the token contained therein is invalid, during EndRequest I am setting the StatusCode on the Response to 401. However, I have determined that EndRequest is called twice, and on the second call the response has already had headers set, causing the code which sets the StatusCode to throw an exception.
I added locks to Init() to ensure that the handler wasn't being registered twice; still ran twice. Init() also ran twice, indicating that two instances of the HttpModule were being created. However, using Set Object ID in the VS debugger seems to indicate that the requests are actually different requests. I've verified in Fiddler that there is only one request being issued to my service from the browser.
If I switch to using global.asax routing instead of depending on the WCF service host configuration, the handler is only called once and everything works fine.
If I add configuration to the system.web configuration section as well as the system.webServer configuration section in Web.config, the handler is only called once and everything works fine.
So I have mitigations, but I really dislike behavior I don't understand. Why does the handler get called twice?
Here is a minimal repro of the problem:
Web.config:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<!--<httpModules>
<add name="AuthModule" type="TestWCFRole.AuthModule, TestWCFRole"/>
</httpModules>-->
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<services>
<service name="TestWCFRole.Service1">
<endpoint binding="webHttpBinding" name="RestEndpoint" contract="TestWCFRole.IService1" bindingConfiguration="HttpSecurityBinding" behaviorConfiguration="WebBehavior"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost/" />
</baseAddresses>
</host>
</service>
</services>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
<bindings>
<webHttpBinding>
<binding name="HttpSecurityBinding" >
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="AuthModule" type="TestWCFRole.AuthModule, TestWCFRole"/>
</modules>
<directoryBrowse enabled="true"/>
</system.webServer>
Http module:
using System;
using System.Web;
namespace TestWCFRole
{
public class AuthModule : IHttpModule
{
/// <summary>
/// You will need to configure this module in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
/// </summary>
#region IHttpModule Members
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
// Below is an example of how you can handle LogRequest event and provide
// custom logging implementation for it
context.EndRequest += new EventHandler(OnEndRequest);
}
#endregion
public void OnEndRequest(Object source, EventArgs e)
{
HttpContext.Current.Response.StatusCode = 401;
}
}
}
When an ASP.net application starts up, to maximize performance the ASP.NET Worker process will instantiate as many HttpApplication objects as it needs. Each HttpApplication object, will also instantiate one copy of each IHttpModule that is registered and call the Init method! That's really an internal design of the ASP.NET process running under IIS (or cassini which is VS built in webserver). Might be because your ASPX page has links to other resources which your browser will try to download, an external resource, and iframe, a css file, or maybe ASP.NET Worker Process behavior.
Luckily it's not the case for Global.asax:
Here's from MSDN:
The Application_Start and Application_End methods are special methods
that do not represent HttpApplication events. ASP.NET calls them once
for the lifetime of the application domain, not for each
HttpApplication instance.
However HTTPModule's init method is called once for every instance of the HttpApplication class after all modules have been created
The first time an ASP.NET page or process is requested in an
application, a new instance of HttpApplication is created. However, to
maximize performance, HttpApplication instances might be reused for
multiple requests.
And illustrated by the following diagram:
If you want code that's guaranteed to run just once, you can either use Application_Start of the Global.asax or set a flag and lock it in the underlying module which is don't think is a good practice for the sake of Authentication!
Sorry no clue to why it could be called twice, however EndRequest can end up being called for multiple reasons. request finished, request was aborted, some error happened. So i wouldn't put my trust in assuming that if you get there, you actually have a 401, it could be for other reasons.
I'd just keep my logic in the AuthenticateRequest pipeline:
public class AuthenticationModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.AuthenticateRequest += Authenticate;
}
public static void Authenticate(object sender, EventArgs e)
{
// authentication logic here
//.............
if (authenticated) {
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(myUser, myRoles);
}
// failure logic here
//.............
}
}

How can I include SessionID in log files using log4net in ASP.NET?

I'm new to log4net, so hopefully this is a really easy question for someone?!
I've got log4net working with the RollingLogFileAppender for my web application. I'm using logging to try and find where some performance issues are coming from. In order to do this, it'd be useful to include the ASP.NET SessionID in the log output so that I can make sure I'm looking at log entries for a specific user.
Is there any way I can do this through the conversionPattern setting for the appender? Is there a %property{??} setting I can use?
UPDATE: This question still hasn't been answered - does anybody have any ideas?
Alexander K. is nearly correct. The only problem with it is that the PostAcquireRequestState event also occurs for static requests. A call to Session in this situation will cause a HttpException.
Therefore the correct solution becomes:
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState)
{
log4net.ThreadContext.Properties["SessionId"] = Session.SessionID;
}
}
UPDATE (2014-06-12): Starting from log4net 1.2.11 you can use %aspnet-request{ASP.NET_SessionId} in conversion pattern for this purpose.
References:
https://issues.apache.org/jira/browse/LOG4NET-87
http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html
You should create Application_PostAcquireRequestState handler in Global.asax.cs (it is called in every request):
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
log4net.ThreadContext.Properties["SessionID"] = Session.SessionID;
}
And add [%property{SessionID}] to conversionPattern.
I was looking answer for this too and found out that %aspnet-request{ASP.NET_SessionId} works fine for me.
Someone corrects me if I am wrong, but one ASP.NET thread can handle multiple sessions, so you can not use Session_Start as it is called once when the session starts. What it means is that as soon as a different user accesss the web site, your log4net.ThreadContext might be overwritten by the new user information.
You can either put the below code in Application_AcquireRequestState, or create a HttpModule and do that in AcquireRequestState method. AcquireRequestState is called when ASP.NET runtime is ready to acquire the Session state of the current HTTP request. If you interested in getting username, you can do that in AuthenticateRequest which is raised when ASP.NET runtime is ready to authenticate the identity of the user (and before the AcquireRequestState).
private void AcquireRequestState(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
log4net.ThreadContext.Properties["SessionId"] = context.Session.SessionID;
}
After that you can set up your log4net.config (or in web.config) like this.
<appender name="rollingFile"
type="log4net.Appender.RollingFileAppender,log4net" >
<param name="AppendToFile" value="false" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyy.MM.dd" />
<param name="StaticLogFileName" value="true" />
<param name="File" value="log.txt" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern"
value="%property{SessionId} %d [%t] %-5p %c - %m%n" />
</layout>
</appender>
Hope this helps!
You can try:
<conversionPattern
value="%date %-5level %logger ${COMPUTERNAME} [%property{SessionID}] - %message%newline" />
...in your Web.config, and in Global.asax.cs:
protected void Session_Start(object sender, EventArgs e)
{
log4net.ThreadContext.Properties["SessionID"] = Session.SessionID;
log4net.Config.XmlConfigurator.Configure();
}

Resources