Log4Net only logging when browsing from localhost - asp.net-mvc

I've used Log4Net in multiple applications for a while. It has been working fine, but recently I noticed that the applications were suddenly not logging anymore. Turns out this issue is the same for all my applications, and they all suddenly stopped logging some months ago. The strange thing is that the logging works when I access the applications directly on the server (http://localhost/myApp), while nothing is logged when I access the application from another PC. My first thought was that it must be related to file/folder permissions, but allowing "Everyone" (Windows user group) full access to the log folder did not help.
They are all ASP.Net MVC 4 applications running on IIS7 (Windows 2008 R2 Enterprise OS), and the application pool is using "ApplicationPoolIdentity". Log4Net version is 1.2.10.0 and I am using a custom CompositeRollingFileAppender. I thought it may have been something wrong with the custom appender, but the problem remained the same when I tried switching to the standard RollingFileAppender. I've seen the issue on multiple servers.
Has anyone seen something similar? Please share your thoughts, as I cannot see why there should be any difference in accessing the applications locally or remotly.
Here is the log4net section in one of my applications' web.config:
<log4net>
<appender name="RollingFileAppender" type="[mynamespace].CompositeRollingFileAppender">
<file value="Logs/ApplicationLog.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="20" />
<maximumFileSize value="10MB" />
<datePattern value="_yyyy-MM-dd" />
<staticLogFileName value="true" />
<preserveLogFileNameExtension value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%utcdate;%property{ErrorCode};%property{Severity};%property{ErrorName};%property{Module};%m%n" />
</layout>
</appender>
<root>
<priority value="ALL" />
<appender-ref ref="RollingFileAppender" />
<level value="Warn" />
</root>
<logger name="NHibernate">
<level value="OFF" />
</logger>
<logger name="NHibernate.SQL">
<level value="OFF" />
</logger>
</log4net>

Turns out the issue was not directly related to log4net, but to the way ASP.Net MVC3 and newer handles exceptions by default. Some months ago we updated our applications from MVC2 to MVC4, and because of this code which is executed by default from global.asax.cs.Application_Start(), it "bypassed" our exception handling module when CustomErrors where set to RemoteOnly or On:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
This thread put me on the right track. I ended up removing the filters.Add(..) line, and now it seems to be working fine!

Related

Umbraco / Azure Blob Storage - Able to upload images & view in Umbraco, but getting 404 Errors on front-end

I recently began integrating UmbracoFileSystemProviders.Azure from https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure and am able to do the following on my local machine & a dev environment...
I can log into Umbraco (v7.3.1/a1.0.5780.28249), upload an image &
have it appear in the appropriate container on our Azure blob
storage
I can view images at their corresponding azure address (i.e. "https://azureaccount.blob.core.windows.net/media-stage/9999/file-name.png")
I can view images within Umbraco's backend (i.e. "http://localhost:99999/umbraco/backoffice/UmbracoApi/Images/GetBigThumbnail?originalImagePath=%2Fmedia%2F9999%2Ffile-name.png")
However, I get a 404 error when I try to view images on the front-end (i.e. "http://www.sitedomain.com/media/9999/file-name.png"). I think this is because the site is still trying to find the front-end image within the site rather than in Azure (based on the fact that creating/removing a matching directory & image at the appropriate relative location causes the image to load or yield a 404). This issue is consistent across multiple browsers & image uploads (whether I upload through Umbraco or through Microsoft Azure Storage Explorer). Does anyone have any ideas how I might be able to resolve it?
The following are all of the files/code snippets I'm using that I think might be relevant to the issue (with client-specific data swapped out in favor of generic data for security)...
Relevant section of Config/FileSystemProviders.config:
<Provider alias="media" type="Our.Umbraco.FileSystemProviders.Azure.AzureBlobFileSystem, Our.Umbraco.FileSystemProviders.Azure">
<Parameters>
<add key="alias" value="media"/>
</Parameters>
</Provider>
Relevant sections of Web.config:
<appSettings>
<!--other data here-->
<add key="AzureBlobFileSystem.ConnectionString:media" value="DefaultEndpointsProtocol=https;AccountName=azureaccount;AccountKey=aBcDeFgHiJkLmNoPqRsTuVwXyZ==;EndpointSuffix=core.windows.net" />
<add key="AzureBlobFileSystem.ContainerName:media" value="media-stage" />
<add key="AzureBlobFileSystem.RootUrl:media" value="https://azureaccount.blob.core.windows.net/" />
<add key="AzureBlobFileSystem.MaxDays:media" value="365" />
<add key="AzureBlobFileSystem.UseDefaultRoute:media" value="true" />
<add key="AzureBlobFileSystem.UsePrivateContainer:media" value="false" />
<!--other data here-->
</appSettings>
<location path="Media">
<system.webServer>
<handlers>
<remove name="StaticFileHandler" />
<add name="StaticFileHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.StaticFileHandler" />
</handlers>
</system.webServer>
</location>
A few additional notes for the troubleshooting process...
I've seen a few similar issues posted on GitHub (& closed out), but I believe my situation to be unique because...
I am not seeing configuration errors when I view the project or
umbraco backend (as with
https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure/issues/103)
My Umbraco is version 7.3.1 (rather than 7.5+, like https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure/issues/57)
Commenting out the image processor in the web config does not solve the issue (as with
https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure/issues/27)
I've also tried forgoing the web.config approach & using the following within Config/FileSystemProviders.config (again, client-specific data has been replaced with generalized stuff), but still had the same problem...
<Provider alias="media" type="Our.Umbraco.FileSystemProviders.Azure.AzureBlobFileSystem, Our.Umbraco.FileSystemProviders.Azure">
<Parameters>
<add key="containerName" value="media-stage" />
<add key="rootUrl" value="https://azureaccount.blob.core.windows.net/" />
<add key="connectionString" value="DefaultEndpointsProtocol=https;AccountName=azureaccount;AccountKey=aBcDeFgHiJkLmNoPqRsTuVwXyZ==;EndpointSuffix=core.windows.net"/>
<add key="maxDays" value="365" />
<add key="useDefaultRoute" value="true" />
<add key="usePrivateContainer" value="false" />
</Parameters>
Thanks in advance for any assistance!
I found that I needed to disable the Virtual Path Provider otherwise the URLs generated were always relative (of the form /media/nnnnn/filename.jpg). Hence I added this to web.config AppSettings
<add key="AzureBlobFileSystem.DisableVirtualPathProvider" value="true" />
see https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure.
This was with Umbraco version 7.7.7.

Exclude IP adress from spring security cas filter

I have a site that uses CAS as a SSO solution and require all that access the site to be authenticated. To fulfill the regulations that our company has we need to create fully rendered snapshot copies of the site. I was thinking of using something like Httrack to accomplish this, but I need to get around the login. My plan was to exclude the IP address of the server running httrack, but I cannot seem to figure out how to configure this.
<sec:http name="contentSecurityFilterChain" use-expressions="true" access-decision-manager-ref="contentAccessDecisionManager" entry-point-ref="casAuthenticationEntryPoint">
<sec:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter" />
<sec:logout logout-success-url="/logout.jsp" logout-url="/j_security_logout" invalidate-session="true" delete-cookies="sessionKey,userId,lastClient" />
<sec:access-denied-handler ref="accessDeniedHandler" />
<sec:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />
<sec:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
<sec:csrf disabled="true" />
<sec:headers>
<!-- Enable hsts if possible. See http://tools.ietf.org/html/rfc6797 -->
<sec:hsts disabled="true" />
<sec:cache-control disabled="true" />
<sec:frame-options disabled="true" />
</sec:headers>
<sec:intercept-url pattern="/monitoring/**" access="hasRole('ROLE_MONITORING')" requires-channel="${security.channel.dispatcher}" />
channel="${security.channel.dispatcher}" />
<sec:intercept-url pattern="/api/login" access="hasRole('ROLE_AUTHENTICATED')" />
<sec:intercept-url pattern="/**" access="hasRole('ROLE_AUTHENTICATED') or hasIpAddress('192.168.123.123')" requires-channel="${security.channel.dispatcher}" />
</sec:http>
I tried the above as a first attempt (where 192.168.123.123 represents my excluded server), but the request still gets redirected to the SSO site before returning to the filter chain.
The closest I got in my various naive fiddlings was by adding a filter to the entry point that did not trigger the commence method; While it did not redirect the request, it only returned an empty page. I assume that is because by not calling the commence method the request was seen as not matching the filter group.
Is there a way to exclude an IP address from the security filters OR is there a better way of doing this?
Suggestions most welcomed!

How to disable Tracing within a MVC Asp.Net application using Trace.WriteLine and Glimpse?

I use MVC3/ASP.NET 4.5, and use Trace.WriteLine("") type statements in my application which show up in my Glimpse Panel.
However how can I disable Tracing, say when I go into Production. I thought it was:
<system.web>
<trace enabled="false" />
But this does not work. The tracing comments still faithfully appear in Glimpse.
Unfortunately that trigger is focused on system web's tracing and not Glimpse. We could change things to adhere to that config point, but it doesn't currently.
Hence the following is what you want in you web.config:
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<inspectors>
<ignoredTypes>
<add type="Glimpse.Core.Inspector.TraceInspector, Glimpse.Core" />
</ignoredTypes>
</inspectors>
</glimpse>
And if you want the tab do disappear as well, you will want this:
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<tabs>
<ignoredTypes>
<add type="Glimpse.Core.Tab.Trace, Glimpse.Core" />
</ignoredTypes>
</tabs>
<inspectors>
<ignoredTypes>
<add type="Glimpse.Core.Inspector.TraceInspector, Glimpse.Core" />
</ignoredTypes>
</inspectors>
</glimpse>

Log4net logging not working - asp.net mvc

My log4net configuration is this,
<?xml version="1.0" encoding="utf-8" ?>
<log4netConfiguration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4net.config" />
</appSettings>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="C:\my_logs/my_web_logs/my_log_%date{ddMMyyyy}.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="30MB" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n"/>
<!--<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />-->
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</log4netConfiguration>
I have a Logger helper class as,
public static class Logger
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static log4net.ILog Log
{
get { return log; }
}
}
In my assembly info, I have this entry,
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
log4net.config is the config file added to the web project.
In the code I log using the logger class,
Logger.Log.Info("User visits Sign In Page.");
Logging has been working when I set up the above setting. But suddenly logging has stopped working.
But when I created a new asp.net mvc website with above settings, logging works for that.
I tried with IIS Express and Local IIS. In both cases logging works for the test application I have created.
I cannot figure out why it's not logging? How can I diagnose this? What are the possible issues?
Solved by myself, reason was "for some reason" log4net configuration was not loaded from assembly info. Still I do not know why that happens.
I tried so many fixes proposed by different posts. Finally fixed the issue.
Solution mentioned in this post helped me to solve the issue.
I have added following configuration,
<!--These settings load the log4net configuration.-->
<add key="log4net.Config" value="log4net.config"/>
<add key="log4net.Config.Watch" value="True"/>
It starts logging!
Then I removed following line from assembly info,
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
The reason is that Log4Net tries to load the config from the assembly that first uses LogManager.GetLogger(). If it's one of your class libraries it will simply ignore the attribute in all other assemblies.
The easiest way to fix it is to invoke LogManager in your start file (like Program.cs or Global.asax):
var logger = LogManager.GetLogger(typeof(Program));
logger.Info("Application started.");
//rest of app init.
Doing that will get you the expected behavior with the assembly attribute.
I found log4net won't load the webconfig configuration unless you call log4net.Config.XmlConfigurator.Configure(); on start up.
protected void Application_Start()
{
// your other codes
log4net.Config.XmlConfigurator.Configure(); // must have this line
Logger = log4net.LogManager.GetLogger(typeof(MvcApplication));
}
I had a similar issue: I would not get any logging output, when I ran my assembly from IIS or IISExpress.
However, none of the answers above worked for me.
In my case the solution was to specify the path to the config file as an absolute path. It turned out that IISExpress does not set the current directory to the bin folder and log4net would not find the config file, so I had to use this workaround:
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
// remove file:// part from uri
UriBuilder ub = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(ub.Path);
var fi = new FileInfo(Path.Combine(Path.GetDirectoryName(path), "Logging.config.xml"));
if (fi.Exists)
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(fi);
var logger = log4net.LogManager.GetLogger(typeof(WebApiApplication));
logger.Info("Application started.");
}
else
{
throw new FileNotFoundException("log4net config file not found", fi.FullName);
}

Run WIF without LoadUserProfile = True is throwing null error

I am using WIF SSO for authentication in my website. Everything works perfect in development environment. But on deployment I got issue
Message: The data protection operation was unsuccessful. This may have
been caused by not having the user profile loaded for the current
thread's user context, which may be the case when the thread is
impersonating. ExceptionStackTrace: at
System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
Byte[] optionalEntropy, DataProtectionScope scope) at
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Encode(Byte[]
value)
Searching abt this issue leads me to this stackoverflow question
Is it possible to run WIF without LoadUserProfile = True
I added the code mentioned but now I am getting
Value cannot be null
I am getting e.ServiceConfiguration.ServiceCertificate ServiceCertificate null. My question is what kind of certificate is this and where can I define this in my config. Do I need to place the same certificate on ACS.
here is my config section
<microsoft.identityModel>
<service>
<audienceUris>
<add value="http://localhost:9494/" />
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="https://devworks-sb.accesscontrol.appfabriclabs.com/v2/wsfederation" realm="http://localhost:9494" requireHttps="false" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
<applicationService>
<claimTypeRequired>
<!--Following are the claims offered by STS 'https://devworks-sb.accesscontrol.appfabriclabs.com/'. Add or uncomment claims that you require by your application and then update the federation metadata of this application.-->
<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" optional="true" />
<claimType type="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" optional="true" />
<!--<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" optional="true" />-->
<!--<claimType type="http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider" optional="true" />-->
</claimTypeRequired>
</applicationService>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="BE9D0A516BEC2BC820C23D5C2EA79F068C094382" name="https://devworks-sb.accesscontrol.appfabriclabs.com/" />
</trustedIssuers>
</issuerNameRegistry>
</service> </microsoft.identityModel>
thanx
First thing you mentioned that the problem occurred after deployment, is that right? In your web.config have you changed the audienceUris to http://whatever_service_name.cloudapp.net?
<audienceUris>
<add value="http://localhost:9494/" /> <== This is wrong
</audienceUris>
Next your question about certificate is NULL at e.ServiceConfiguration.ServiceCertificate, please verify the following:
A. Endpoint is added in your application Service Definition:
B. Certificate thumbprint is set in Service Configuration
C. Certificate is set in web.config which is correct above
D. Finally added the following in your web.config so certificate can be search by thumbprint:
<serviceCertificate>
<certificateReference x509FindType="FindByThumbprint" findValue="CERT_THUMB" />
</serviceCertificate>
Study these two resources which will be very helpful:
http://www.jimandkatrin.com/CodeBlog/post/Troubleshooting-Azure-issues.aspx
http://blogs.msmvps.com/marcelmeijer/blog/2012/05/04/windows-azure-wif-access-control-acs/
The root cause is likely to be you’re using DPAPI (the default configuration of WIF). Please try to do a few modifications for the application to work in Windows Azure. I would like to suggest you to check http://msdn.microsoft.com/en-us/IdentityTrainingCourse_WIFonWAZLab2010 for a tutorial.
Best Regards,
Ming Xu.

Resources