Why is my windows service not logging anything? - windows-services

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net" />
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
<!-- Redacted -->
</system.serviceModel>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs\" />
<datePattern value="'Proxy_'dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<priority value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<category name="Client.log">
<priority value="ALL" />
</category>
</log4net>
<applicationSettings>
<!-- Redacted -->
</applicationSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
I have the above config for my windows service when it's installed, and I'm initializing my logger like so in the Progam.cs file on the service that I'm installing:
static void Main()
{
XmlConfigurator.Configure();
_logger.Debug("ProxyServerService Started.");
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ProxyServerService()
};
ServiceBase.Run(ServicesToRun);
_logger.Debug("ProxyServerService Terminated.");
}
When I use pretty much the same configuration in an application that communicates with this service it creates a log directory and writes logs to that directory. But when I run the service nothing happens.

Turns out that the reason I couldn't see the logs is because I'd configured the logger the log in the active directory, which is Windows\system32 and windows wouldn't let me do that.
I changed the following line:
<file value="logs\" />
To:
<file value="C:\AppName\logs\" />
And it works fine.

Related

Is it possible to add an hour to the timestamp in log4net using the ConversionPattern

We have a situation where the server is in Germany and we're based in the UK. We want the log4net logs to show a timestamp that is GMT, but I can't work out how or if it's possible to add an hour to the time being written to the log file.
This is our current config:
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs\\" />
<datePattern value="dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="50" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-dd-MM HH:mm:ss.fff} %-5level - %message%newline" />
</layout>
</appender>
I found some references online to an "hourOffset", but this doesn't seem to work and never appears in the log4net documentation.
Any advise here would be welcome.
Use utcdate instead of d (or date). See also the documentation.
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%utcdate{yyyy-dd-MM HH:mm:ss.fff} %-5level - %message%newline" />
</layout>

SimpleMembership fails first login attempt

My issue is that the new simplemembership provider fails a good username/password combination on the first attempt. The first failed attempt produces the .ASPXAUTH which now contains the user name, the second attempt will work with the same data.
I know this is bound up with the .ASPXAUTH cookie b/c if I delete that after the first (failed) attempt, then I get the same results. The net result is unless it has a user name in the auth cookie that matches the passed in form user name, the person needs to log in a second time. This has nothing to do w/connecting to the database, or initializing the connection b/c I can reproduce this behavior every time.
THoughts?
[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
[HandleError(View = "AntiForgeryExceptionView", ExceptionType = typeof (HttpAntiForgeryException))]
public ActionResult Login(LoginModel model, string returnUrl)
{
ViewBag.Message = "Login";
if (ModelState.IsValid && WebSecurity.UserExists(model.UserName))
{
WebSecurity.Login(model.UserName, model.Password, model.RememberMe);
if (WebSecurity.CurrentUserId > 0)
{
if (!IsRegistered(WebSecurity.CurrentUserId))
{
ModelState.AddModelError("", "You cannot log in before registering.");
return View(model);
}
if (HttpContext.Session != null)
{
Helpers.MemberService.Set(new MemberSession
{
UserId = WebSecurity.CurrentUserId,
SessionId = HttpContext.Session.SessionID
});
}
var cookie = new HttpCookie("MemberId")
{
Expires = DateTime.Now.AddDays(-1) // or any other time in the past
};
HttpContext.Response.Cookies.Set(cookie);
HttpContext.Response.Cookies.Add(new HttpCookie("UserId", WebSecurity.CurrentUserId.ToString(CultureInfo.InvariantCulture)));
if (string.IsNullOrEmpty(returnUrl))
{
// we can assume the user has just logged on...
returnUrl = "../Summary.htm";
}
return RedirectToAction(returnUrl);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
<section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<appSettings configSource="Helpers\Config\appsettings.config" />
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<trust level="Full" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="StructureMap" publicKeyToken="e60ad81abae3c223" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.4.0" newVersion="2.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.net>
<defaultProxy enabled="true" />
<settings>
<!-- This setting causes .NET to check certificate revocation lists (CRL)
before trusting HTTPS certificates. But this setting tends to not
be allowed in shared hosting environments. -->
<!--<servicePointManager checkCertificateRevocationList="true"/>-->
</settings>
</system.net>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
<openid>
<relyingParty>
<security requireSsl="false">
<!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. -->
<!--<trustedProviders rejectAssertionsFromUntrustedProviders="true">
<add endpoint="https://www.google.com/accounts/o8/ud" />
</trustedProviders>-->
</security>
<behaviors>
<!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
with OPs that use Attribute Exchange (in various formats). -->
<add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
</behaviors>
</relyingParty>
</openid>
</dotNetOpenAuth>
<uri>
<!-- See an error due to this section? When targeting .NET 3.5, please add the following line to your <configSections> at the top of this file:
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
-->
<!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
which is necessary for OpenID urls with unicode characters in the domain/host name.
It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
<log4net>
<appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
<!--<file value="${TEMP}\\Logs\\AppName_${COMPUTERNAME} " />-->
<file value="Logs\\WebLog.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<datePattern value=".yyyyMMdd.'log'" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="GeneralLog" />
<appender-ref ref="DebugAppender" />
</root>
</log4net>
</configuration>
I think you are missing the following line to authenticate the cookie for the current request:
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
EDIT:
You're using the new WebSecurity security model, not forms authentication. Ignore my first answer.
Could you check what the contents of WebSecurity.CurrentUserId are after you login? I think the properties of WebSecutiy are not set immediately after the call to the Login. If you send a second request after the call to Login you should see that the CurrentUserId is set.
If you want to check for a succesfull login before continuing you could do the following:
bool isLoggedIn = WebSecurity.Login(model.UserName, model.Password, model.RememberMe);
if (isLoggedIn) {
....
}

ASP.NET MVC Web Application connecting to WCF web service errors with large data

EDIT
I am using MVC 3 trying to call a method in a WCF service that the MVC service has consumed and get the following error when I call the method.
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:emailData. The InnerException message was 'There was an error deserializing the object of type EmailPO. The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 89, position 1075.'. Please see InnerException for more details.
This is not just related to ASP.NET as I thought. I have a WPF Application that also uses this service that locally works with Cassini. When I use an identical WPF application and consume the service after publishing this same WCF service, I also get the above error running teh same method.
ASP.NET MVC Client Web.config that does not work:
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="UserInterface.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<!--<location path="~/Content/images" allowOverride="false">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>-->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Configuration" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="1073741824" maxBufferPoolSize="1073741824"
maxReceivedMessageSize="1073741824" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="65536" maxArrayLength="102400" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://server1/WebServices/MasterEngine/MasterEngineService.svc?wsdl" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Configuration" contract="MasterEngineFarEnd.IMasterEngineService" name="BasicHttpBinding_IMasterEngineService" />
--- Later on after company specific stuff --
<system.web>
<httpRuntime requestValidationMode="2.0" maxRequestLength="5120" executionTimeout="1200" />
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Windows"></authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<!--<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
<error statusCode="500" path="/Error/Error" responseMode="ExecuteURL" />
</httpErrors>-->
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true"></modules>
<handlers>
<remove name="UrlRoutingHandler"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Routing" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
WCF Service (MasterEngine) Web.config
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Configuration" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="1073741824" maxBufferPoolSize="1073741824" maxReceivedMessageSize="1073741824"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="1073741824" maxArrayLength="102400"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<!-- OLD CONFIG
<binding name="BasicHttpBinding_Configuration" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
-->
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://server2/WebServices/InternalService/InternalService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Configuration"
contract="InternalFarEnd.IInternalService" name="BasicHttpBinding_IInternalHubService" />
</client>
</system.serviceModel>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<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="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
WPF application that does not work
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<diagnostics>
<endToEndTracing propagateActivity="true" activityTracing="true"
messageFlowTracing="true" />
</diagnostics>
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<!-- 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>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Configuration" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" maxBufferPoolSize="1073741824"
maxReceivedMessageSize="1073741824" useDefaultWebProxy="true">
<readerQuotas maxDepth="1073741824" maxStringContentLength="1073741824"
maxArrayLength="1073741824" maxBytesPerRead="1073741824" maxNameTableCharCount="1073741824" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://server01-dev/WebServices/MasterEngine/MasterEngineService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Configuration"
contract="MasterEngineFarEnd.IMasterEngineService" name="BasicHttpBinding_IMasterEngineService" />
</client>
</system.serviceModel>
</configuration>
WPF application that does work
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<diagnostics>
<endToEndTracing propagateActivity="true" activityTracing="true"
messageFlowTracing="true" />
</diagnostics>
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<!-- 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>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Configuration" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" maxBufferPoolSize="1073741824"
maxReceivedMessageSize="1073741824" useDefaultWebProxy="true">
<readerQuotas maxDepth="1073741824" maxStringContentLength="1073741824"
maxArrayLength="1073741824" maxBytesPerRead="1073741824" maxNameTableCharCount="1073741824" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://server01-dev/WebServices/MasterEngine/MasterEngineService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Configuration"
contract="MasterEngineFarEnd.IMasterEngineService" name="BasicHttpBinding_IMasterEngineService" />
</client>
</system.serviceModel>
</configuration>
I have gone through adding the max-everything as other threads have said along with what the error actually states, but I see no where at this point where 8192 even applies or what it could be referring to. If someone could point me in the right direction I would really appreciate it. if needed, my class that it is referring to looks like this.. with the DataMembers / DataContracts set up
Email PO Class
[DataContract]
public class EmailPO
{
[DataMember]
public string FromEmail { get; set; }
[DataMember]
public List<String> ToEmail { get; set; }
[DataMember]
public List<String> CcEmail { get; set; }
[DataMember]
public string FullHTML { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public List<EmailClassLibrary.AttachmentItem> Attachments { get; set; }
[DataMember]
public string TableHeader { get; set; }
}
EDIT - UPDATE
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
<endpoint address="http://server1/WebServices/MasterEngine/MasterEngineService.svc?wsdl"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_Configuration"
contract="MasterEngineFarEnd.IMasterEngineService"
name="BasicHttpBinding_IMasterEngineService"/>
Also Tried it with giving it a name and updating the endpoint to use the same name for behaviorConfiguration
Its an Issue where the serialization graph of our objects exceeded the default max limits.
So in Service config add this line.
<system.serviceModel>
...
<behaviors>
<endpointBehaviors>
<behavior name="Behaviors.EndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
...
</system.serviceModel>
It is works for me in WCF service config.
EDIT: you can refer this link CLICK here

log4net.Config.XmlConfigurator.Configure() takes too long

I use Log4Net for logging. When the application starts, I call
log4net.Config.XmlConfigurator.Configure();
But this line takes 15 seconds to finish. Am I doing something wrong? Or is it normal?
I am developing with ASP.NET MVC, an use Unity for dependency injection.
At the application start, I call a Bootstrapper Initialise function
protected void Application_Start()
{
IUnityContainer container = Bootstrapper.Initialise();
...
...
}
In the Bootstrapper Initialize function, I register the type ILog.
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
...
...
container.RegisterType<ILog>("", new ContainerControlledLifetimeManager(),
new InjectionFactory(factory =>
LogManager.GetLogger(typeof(HomeController).Assembly, connectionString)));
...
...
}
At the beginning of GetLogger function I call the configure function
public static ILog GetLogger(Assembly assembly, string connectionString)
{
log4net.Config.XmlConfigurator.Configure(); //<----- it takes 15 seconds to finish
...
...
}
EDIT
---------------------------------------------------------------------------------
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="0" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[database server];initial catalog=[database name];integrated security=false;persist security info=True;User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[UserId],[Operation],[EntityType],[EntityId],[IP],[Host],[SessionId],[LogGroup]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception, #UserId, #Operation, #EntityType, #EntityId, #IP, #Host, #SessionId, #LogGroup)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
<parameter>
<parameterName value="#UserId"/>
<dbType value="Int32" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="UserId" />
</layout>
</parameter>
<parameter>
<parameterName value="#IP"/>
<dbType value="String" />
<size value="25" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="IP" />
</layout>
</parameter>
<parameter>
<parameterName value="#Host"/>
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="Host" />
</layout>
</parameter>
<parameter>
<parameterName value="#LogGroup"/>
<dbType value="Int32" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="LogGroup" />
</layout>
</parameter>
<parameter>
<parameterName value="#Operation"/>
<dbType value="Int32" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="Operation" />
</layout>
</parameter>
<parameter>
<parameterName value="#EntityType"/>
<dbType value="Int32" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="EntityType" />
</layout>
</parameter>
<parameter>
<parameterName value="#EntityId"/>
<dbType value="Int32" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="EntityId" />
</layout>
</parameter>
<parameter>
<parameterName value="#SessionId"/>
<dbType value="String" />
<size value="88" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="SessionId" />
</layout>
</parameter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
15 Seconds sounds like a (connection) timeout, I believe the default timeout is 15 seconds.
I had a similar problem once and it turned out to be The CLR tried to verify the authenticode signature at load time to create publisher evidence for an assembly.
I am not sure about the details but there is a configuration element named "generatePublisherEvidence" in the assembly section where it can be turned off. You should check if you want to do this though. And what the implications for this are.
If you are using .Net 4 (or greater) this should have no impact on load time.
For web applications this setting cannot be set in the applications web.config. It should be set in the aspnet.config in the .Net framework directory.
When you try to call the following statement
log4net.Config.XmlConfigurator.Configure();
The system will try to validate the given database connection string. Here the problem is, your given connection string might be not connecting and it is trying to connect until it's given a time out.
Please verify is your given connection string is valid or not.
http://techxposer.com/2017/08/08/log4net-config-xmlconfigurator-configure-taking-too-much-time/

Why log4net doesn't log nhibernate information

My Visual Studio Solution contains:
[DLL] Sol.DataAccess (NHibernate sessionManager)
[DLL] Sol.Core (Models and Repository)
[MVC] Sol.WebMvc (Controler, View)
All my application contains are (nhibernate.dll [v3.0] and log4net.dll[v1.2.10])
I have 3 configs:
web.config:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" requirePermission="false" />
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>
</configuration>
nhibernate.config:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="...">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">...</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="generate_statistics">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="use_outer_join">true</property>
<property name="max_fetch_depth">2</property>
<property name="command_timeout">60</property>
<property name="adonet.batch_size">25</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="current_session_context_class">web</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.provider_class">NHibernate.Caches.SysCache2.SysCacheProvider, NHibernate.Caches.SysCache2</property>
<mapping assembly="..."/>
</session-factory>
</hibernate-configuration>
and log4net.config:
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<!--for release-->
<!--<bufferSize value="10" />-->
<!--for debug-->
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=xxxxx; Initial Catalog=xxxx; User Id=xxxx; Password=xxxxx; App=xxxx" />
<commandText value="INSERT INTO Logs ([Application],[Host],[User],[Date],[Thread],[Level],[Operation],[Logger],[Message],[Exception]) VALUES (#app, #hostName, #userName, #log_date, #thread, #log_level, #operation, #logger, #message, #exception)" />
<parameter>
<parameterName value="#app" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="xxxx" />
</layout>
</parameter>
<parameter>
<parameterName value="#hostName" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{hostName}" />
</layout>
</parameter>
<parameter>
<parameterName value="#userName" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{userName}" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#operation" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{Operation}" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="Logs/Logs.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<appender name="Console" type="log4net.Appender.AspNetTraceAppender">
<!--A1 uses PatternLayout-->
<layout type="log4net.Layout.PatternLayout">
<!--Print the date in ISO 8601 format-->
<conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="Console"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
Global.cs:
protected void Application_Start()
{
...
// Configuration
#region log4net
// log4net.config
System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/log4net.config"));
if (fi != null && fi.Exists)
{
// Code that runs on application startup
log4net.Config.XmlConfigurator.Configure(fi);
}
// web.config
//log4net.Config.XmlConfigurator.Configure();
// set properti hostName
log4net.GlobalContext.Properties["hostName"] = Dns.GetHostName();
#endregion
#region NHibernate
//HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
var factory = NHibernateSessionManager.ConfigureFromFile(Server.MapPath("~/hibernate.config"));
#endregion
}
in my test controller i have:
public class TestController : BaseController
{
[NHibernateSession]
public ActionResult Index()
{
Logger.Error("fake error", new Exception());
}
}
In my log file - Logs/Logs.txt:
2011-03-11 18:19:23,097 [8] ERROR System.Web.Mvc.Controller [(null)] - fake error
System.Exception: Exception of type 'System.Exception' was thrown.
QUESTION:
Why log4net doesn't log NHibernate information (info, debug ....)
Aren't the versions of these dlls compatible?
I have create an empty ASP.Net MVC3 project. and loss much time trying to fix this issue.
And I find VS2010 bug. Visual Studio 2010 don't copy dll's in bin when you refer it in project.
I put log4net.dll manual in my bin folder and work fine. (Interesting thing is that Logger.Error("fake error") work fine without log4net.dll in bin folder ...)
First off: you speak of "log4net.config", but you don't include that anywhere. The way you configure it in web.config, you should actually include a section called <log4net> inside your web.config, not as a separate file.
If you don't want it in your web.config, you can remove the log4net related sections altogether and add the following line to yur global.asax.cs:
log4net.Config.XmlConfigurator.ConfigureAndWatch(
New FileInfo(Server.MapPath("~/yourreleativepath/log4net.config")))
Also, possibly you miss the priority setting, not entirely sure this helps, but give it a try:
<root>
<priority value="DEBUG"/>
<appender-ref ref="Console"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="AdoNetAppender"/>
</root>
Also, to finetune (because you'll get a lot messages), use something like this:
<logger name="NHibernate.SQL">
<level value="DEBUG"/>
</logger>
<logger name="NHibernate">
<level value="WARN"/>
</logger>
On nhibernate.info you'll find a full example.

Resources