Why does this web api need a local web api call to log? - asp.net-web-api2

I have two almost identical web api services programmed in C# and installed on the same Windows 2008 Server on IIS 6.1. When I do web api calls to them, they both work just fine. I am using log4net for logging purposes. One of them, however, does not always log. They both have the same exact log4net configuration, which is:
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\LOGS\SomeFolder\" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<preserveLogFileNameExtension value="true" />
<rollingStyle value="Date" />
<datePattern value="'WebApi.One.'yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level [%thread][%date{dd-MM-yy HH:mm:ss,fff}] %logger - %message%newline" />
</layout>
</appender>
</log4net>
The only difference in the configuration is the datePattern which has a slightly different name so that they do not log to the same exact file.
For the web api where logging works as expected a new log file is created each day as soon as a web api call comes in. For the web api where logging does not seem to work the new log file is not created. However, if I make a web api call from a browser on the same server as it is installed on, then logging starts. After the logging has started for that day it continues fine (even with web api calls coming from other machines). But the next day no new file is created.
I am unable to see what the difference is. Surely there must be something I am not thinking of that makes these two web apis behave differently when it comes to logging. Remember, both of the services work fine, it is just the logging that is not working for one of them.
Any suggestions?
Edit 1:
After adding diagnostics as suggested by Peter I can see that the access to the path is denied:
log4net:ERROR Could not create Appender [RollingLogFileAppender] of type [log4net.Appender.RollingFileAppender]. Reported error follows.
System.UnauthorizedAccessException: Access to the path 'C__LOGS_WebApi.One_' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.Mutex.CreateMutexWithGuaranteedCleanup(Boolean initiallyOwned, String name, Boolean& createdNew, SECURITY_ATTRIBUTES secAttrs)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
at log4net.Appender.RollingFileAppender.ActivateOptions()
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [RollingLogFileAppender] not found.
I don't know why though.
Edit 2:
I checked solutions in these StackOverflow answers:
What am I doing wrong with thie log4net implementation?
log4net: Error on loading custom appender
But still no progress.
This looked very similar, but I could see no solution there (although maybe there is one).
Edit 3:
Folder permissions:

According to the exception message, the process does not have enough rights to write to the location of the log file.
In my experience with dealing with IIS, changing the security permissions on the folder where the log file is stored so that the application/process has the rights to modify the log file(s) usually works.
To confirm/troubleshoot start by giving everyone full control on the folder and testing that the file can be modified.
If that works then you can confirm it is a permission issue.
I usually give IIS_IUSRS the following permission on the Log folder where I store my logs and archive.
Read
Write
Modify
To limit possible attack vectors I try to give the process as few permission as needed to perform its function. Adding and removing permissions and then testing that it still functions as desired.

It looks like a security issue, to debug this you should enable debugging for log4net:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
And
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
in your configuration.
This way you are able to see why the creation of the file fails.
log4net faq

Related

asp.net core out-of-process fails to start correctly

I'm attempting to us the RunFromPackage App Setting for an Azure Web Site.
I'm using the following stack
asp.net core (out-of-process)
Targeting .Net Framework 4.7.2
and I can no longer get my web application to run correctly. when I hit the url all I get is
"The page cannot be displayed because an internal server error has occurred."
in the response.
I have launched my application using the Kudu powershell window with the command
".{applicationName}.exe"
and it start up fine. No errors or anything
Viewing the event viewer logs all I see is
APPLICATION_MANAGER::~APPLICATION_MANAGER | this=000001D1CD999A60 [TID 8872] [PID 8028]
When turning on the Failed Request Tracing Logs I see the following relevant information
URL_CACHE_ACCESS_START RequestURL="/favicon.ico" 15:37:30.729
URL_CACHE_ACCESS_END PhysicalPath="", URLInfoFromCache="false", URLInfoAddedToCache="true", ErrorCode="The operation completed successfully.
(0x0)" 15:37:30.729
GENERAL_GET_URL_METADATA PhysicalPath="", AccessPerms="545" 15:37:30.729
HANDLER_CHANGED OldHandlerName="", NewHandlerName="aspNetCore", NewHandlerModules="AspNetCoreModule", NewHandlerScriptProcessor="", NewHandlerType="" 15:37:30.729
MODULE_SET_RESPONSE_ERROR_STATUS
Warning ModuleName="IIS Web Core", Notification="BEGIN_REQUEST", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="Access is denied.
(0x80070005)", ConfigExceptionInfo=""
I have tried to turn on the asp.net core module logging but I get no log files. I have also tried to turn on the stdoutlog but nothing is appearing to log.
Here is a copy of my web.config
<configuration>
<system.webServer>
<security>
<access sslFlags="SslNegotiateCert" />
</security>
<serverRuntime uploadReadAheadSize="30000000" />
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="true" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="OutOfProcess" arguments="%LAUNCHER_ARGS%">
<handlerSettings>
<handlerSetting name="debugFile" value="\\?\%home%\LogFiles\aspnetcore-debug.log" />
<handlerSetting name="debugLevel" value="FILE,TRACE" />
</handlerSettings>
</aspNetCore>
</system.webServer>
</configuration>
I'm not really sure what is going on. All I can gather is something is going wrong with the IIS Module. from the error message it appears that it cannot read or process my web.config ErrorCode="Access is denied."
Strangely enough I had a previous build of the application up and running. I have tried to isolate the changes that may have broke the site but I cant seem to find out what has cause this.
It appears that this was due to the fact I was trying to get only client authentication on one endpoint.
The following setting
<access sslFlags="SslNegotiateCert" />
in the web.config, and Require incoming Certificate in the App Settings caused my issue.
I then tried the feature of "Certificate exclusion paths" but having this and the web.config access node makes the web server very upset and causes the error message
"The page cannot be displayed because an internal server error has occurred."
I had to remove the node from my web.config file, leave the Required SSL, and set my Certificate Exclusion path and everything turned back online.

How to ignore Liferay user removed from LDAP errors?

I have a Liferay 6.1 instance that is connected to LDAP. New users get imported nicely, but when I remove a user from the LDAP directory, Liferay starts throwing exceptions when it tries to sync users from LDAP.
These seem to be safe to ignore, but they produce several megabytes of log and it makes log parsing highly annoying. Also I think it might affect performance. If a deleted user logs in, they see nothing.
16:13:54,422 ERROR [liferay/scheduler_dispatch-790][PortalLDAPImporterImpl:995] LDAP user not found with fullUserDN cn=foobar,ou=people,o=foo,dc=bar,dc=baz
javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name 'cn=foobar,ou=people,o=foo,dc=bar,dc=baz'
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3057)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2978)
... etc
How could I convince Liferay that this is really OK? Or is there something else I should do?
Until missing users in LDAP are supported by Liferay you can turn off the logging for this particular message. Just create the file ROOT.war/WEB-INF/classes/META-INF/portal-log4j-ext.xml with the following content:
<?xml version="1.0">
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Copy all appenders from
ROOT.war/WEB-INF/lib/portal-impl.jar/META-INF/portal-log4j.xml
and add the following filter: -->
<appender ...>
...
<filter class="org.apache.log4j.filter.StringMatchFilter">
<param name="StringToMatch" value="LDAP user not found with fullUserDN" />
<param name="AcceptOnMatch" value="false" />
</filter>
</appender>
<!-- Keep the root definition from portal-log4j.xml
to trigger the parsing of the appenders: -->
<root>
<priority value="INFO" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>
You can find more about logging in the Liferay Wiki.

Why does log4net stop logging after a while on .NET WCF but not a usual website?

I've search many sites and tried several different opinions. But I still could not solve it. Here are the things I did right now:
In Global.asax at Application_Startup I give the file path and startup the Log4Net.
Right after I start log4net, I write a log that says "Application has
stared'"
Currently, there is only 1 worker in IIS for the WCF application The
IIS user has access to WRITE, MODIFY and READ privileges
The problem:
When I invoke a method of service directly (without doing the 2.
step below), No Logs is written
On a browser, I write te WCF url and hit ENTER, Log4Net creates the
folder and the files (files are EMPTY at this point).
If I make requests and invoke the methods (doing the 1st step), now
Log4Net writes the logs.
The actual problem:
After the 3rd step, (lets say we waited without any invokes of the
WCF methods around 10 minutes or more), the invoking DOES NOT CREATE
Log4Net Text logs ANYMORE.
Sometimes, if I repeat the 2nd step, it begins writing the logs
again. But there is no coherent results.
Here is the Config.xml:
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="ProcessInfo_FileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="L:\LOGs\ProcessInfo\ProcessInfo_[%processid].txt" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="200" />
<maximumFileSize value="30MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] - %message%newline" />
</layout>
</appender>
<logger name="ProcessInfo">
<levelMin value="ERROR" />
<levelMax value="INFO" />
<appender-ref ref="ProcessInfo_FileAppender" />
</logger>
<root></root>
</log4net>
I have other WCF projects which have no problem even with multiple Workers. (I used the exact same IIS and Log4Net xml configuration with them). Also, as I mentioned on the title, I have a WebSite who has exact same logging codes (they both using a common 3rd party dll which I wrote) and has NO PROBLEM of writing Log4Net text logging at all.
Please help.
Thanks.
The problem is not in your logging configuration, you should try to enable log4net internal debugging. This will tell you why the logging stops. I guess there is some code that reconfigures your logging to load configuration from your web.config which is not there.
<configuration>
...
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Log4net FAQ

ImageResizing Not Working In Hosting

I have an asp.net mvc project. I installed imageresizing nuget packages. It's working in local.
When I published to my hosting then it's not working.
I set IIS situation integrated and classic but still didn't work.
I couldn't solve, can you help please? Thanks.
The following definitions are exist in web.config
<resizer>
<plugins>
<add name="MvcRoutingShim" />
<add name="DiskCache" />
<add name="SimpleFilters" />
<add name="PrettyGifs" />
</plugins>
</resizer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
</modules>
The self-diagnostics page at /resizer.debug explains the configuration issues present on your hosting environment
Image resizer diagnostic sheet 24.11.2014 22:15:04
2 Issues detected:
(Critical): Grant the website SecurityPermission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal
Without this permission, it may be possible for users to bypass UrlAuthorization rules you have defined for your website, and access images that would otherwise be protected. If you do not use UrlAuthorization rules, this should not be a concern. You may also re-implement your security rules by handling the Config.Current.Pipeline.AuthorizeImage event.
DiskCache(ConfigurationError): Not working: Your NTFS Security permissions are preventing the application from writing to the disk cache
Please give user read and write access to directory "D:\inetpub\adafirin.com\www\imagecache" to correct the problem. You can access NTFS security settings by right-clicking the aformentioned folder and choosing Properties, then Security.

wcf trying to set up tracing to debug, not writing to log file

here's my web.config, running a WCF service in an application on IIS7, but nothing is being written to the specified file. permission on the file has been granted for everyone.
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing, error, warning, critical" propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\log\tracestext.log" />
</listeners>
</source>
</sources>
</system.diagnostics>
I can add a service reference just fine.
I then try to call the service from a windows app and, after a few minutes, get an error on the machine running the windows app "Client is unable to finish the security negotiation within the configured timeout (00:00:00). The current negotiation leg is 1 (00:00:00)."
but absolutely nothing is written to the trace log file specified in config.
Is there something else I need to do to enable tracing? thanks for your help
EDIT: "sources" section now matches the section recommended here: http://msdn.microsoft.com/en-us/library/aa702726.aspx
I've added the "diagnostics . messagelogging" section to "system.servicemodel"
and the event viewer shows: "Message Logging has been turned on. Sensitive information may be logged in the clear, even if it was encrypted on the wire: for example, message bodies.
Process Name: w3wp
Process ID: 1784
"
but the log file is still empty
Yes - you've only just defined some .NET tracing source and listeners - but you haven't instructed WCF yet to actually do the tracing!
You also need:
<system.serviceModel>
<diagnostics>
<messageLogging
logMessagesAtTransportLevel="true" logMessagesAtServiceLevel="false"
logMalformedMessages="true" logEntireMessage="true"
maxSizeOfMessageToLog="65535000" maxMessagesToLog="500" />
</diagnostics>
</system.serviceModel>
These two sections of config combined should do it!
In order to get your messages written back to the log file right away, you might want to add a setting to your <system.diagnostics> section:
<system.diagnostics>
... everything you already have....
<trace autoflush="true" />
</system.diagnostics>
To write to the log file, make sure that identity running your web application has write access to the log directory.
You can find the identity in the IIS 7 management console. Select the application pool that your web application is using. Click on Advanced Settings... In the properties window, look for the identity field. It may say Network Service. This is the account that needs write permission to your log output folder.
If you already have a log file in this directory, try deleting it and letting the framework create it.
Hope this helps.
Make sure you have configured both the system.diagnostics and the
System.serviceModel/diagnostics sections configured.
Make sure you have them configured in the correct App.config/Web.config file. The thing to note is that multiple
config files may exist in a project, and the one used depends on the
Build Configuration.
Personally I had the very same symptom until I noticed that I put the sections under app.config (in my case, client side tracing), instead of app.DebugLocal.config. The later was used as my build configuration was set to DebugLocal.
Probably the issue is due to permission to write in the log directory specified in your config file.
If you are'nt sure wich is the user in the context, give write permission to all machine users.
Right click in log directory
Click in the "Security" tab
Click edit
On "Group Names or Users" section, select "Users MachineName\Users"
On "Permissions" section grant permission to write
It worked fine for me.