Activation error occured while trying to get instance of type LogWriter in ASP.Net website

Topics: Exception Handling Application Block, Logging Application Block
Feb 2, 2012 at 5:42 AM

Hi Guy,

        I have this error in a website in IIS, when logging message using logging block of Entlib 5.0. (I have deployed all Enlib dlls(not only 7 assemblies) into website\bin folder.)

        What's strange is that there is no such error when I ran the asp.net project in VS2010(in debug/release), and success to log message into the flat file.

        So the exception is only raised when I deployed the ASP.NET into IIS and visited the website.

        Could someone give me any suggestion or ideas, Many thanks

        My environment:  Windows 7, VS2010, .Net 4, Entlib5.0, IIS7.5

       ------------ My Web.Config for logging/exception is----------

-<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 <configSections>
  <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
  <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
 </configSections>
 <loggingConfiguration name="" tracingEnabled="true" defaultCategory="MyLogger">
  <listeners>
   <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fileName="log\Log.log" footer="" formatter="File Text Formatter" header=""/>
  </listeners>
  <formatters>
   <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" template="{message}" name="File Text Formatter"/>
  </formatters>
  <categorySources>
   <add switchValue="All" name="MyLogger">
    <listeners>
     <add name="Rolling Flat File Trace Listener"/>
    </listeners>
   </add>
  </categorySources>
  <specialSources>
   <allEvents switchValue="All" name="All Events"/>
   <notProcessed switchValue="All" name="Unprocessed Category"/>
   <errors switchValue="All" name="Logging Errors &amp; Warnings">
    <listeners>
     <add name="Rolling Flat File Trace Listener"/>
    </listeners>
   </errors>
  </specialSources>
 </loggingConfiguration>
 <exceptionHandling>
  <exceptionPolicies>
   <add name="MyExceptionPolicy">
    <exceptionTypes>
     <add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="NotifyRethrow">
      <exceptionHandlers>
       <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" logCategory="MyLogger" eventId="100" severity="Error" title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" priority="0"/>
      </exceptionHandlers>
     </add>
    </exceptionTypes>
   </add>
  </exceptionPolicies>
 </exceptionHandling>
 <connectionStrings>
  <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <system.web>......

     -----------The code when raise the exception ----------

      Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(message, "MyLogger", -1, 100, traceType);

     ---------- The exception is:---------

Activation error occured while trying to get instance of type LogWriter, key ""
   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 53
   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]() in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 90
   at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer() in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\Logger.cs:line 408

 

 

 

 

 

 

Editor
Feb 3, 2012 at 4:05 AM

The configuration looks good.  The error you are seeing indicates that the loggingConfiguration was not loaded.  

The mostly likely cause is that the web.config was not deployed or was deployed in the wrong location.  Can you verify that the web.config you posted above is actually deployed on the IIS server?

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 6, 2012 at 6:13 AM

Hi Levy,

       Thanks for the information.

        I find the reason: it's because the IIS user has no access to write/modify file to the physical path of the web application in IIS.

        Once I gave write access to "Users" on that path, everything is working fine.  One concern is that the excpetion/error message is not indicating the actual reason.  :-<

        One more question, Is that the only workaroud for Enterprise logging block working in IIS? 

        Thanks.

     

 

 

 

 

 

Editor
Feb 6, 2012 at 6:44 AM

Usually, it's better to place a log file outside of the web site directory so that write access is not required to the site.  If you do need to grant write access it should be to only a specific folder/file.

It's always a good idea to configure the errors specialSources to point to a location where permissions will be already set.  Sometimes this is hard to know. An alternative to a flat file might be to use Event Log Trace Listener using the Application event log and Application event source since those are almost always defined but it's not ideal since it's not clear from looking at the event log who is logging the messages.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 7, 2012 at 3:05 AM

Thank your Levy again for your kind reply.

The logging requirement for our case is both logging into flat file and event log trace.(I just remove the listener from the configuration I attached)

Actually I have met a problem:  if the logging is used in webapplication(on IIS), if the event source is not registered, logging block will not register message into windows event. as workaround, I need to register event source manually.

Another problem, as there are too much configuration items in configuration file for exception policy and logging category, I have make it work to remove configuration file, by loading XML string(same in configuratin file) into Configuration Source and EnterpriseLibraryContainer.Current = locator. But the problem is that I have to save those XML string into a temp file, and then new a FileConfigurationSource to load the XML string from temp file.  Is there any solution, directly loading XML string, no need to save it into file?

Thank you in advance for your professional support. Thanks

 

 

Editor
Feb 7, 2012 at 4:41 AM
Edited Feb 8, 2012 at 1:27 PM

Registering of event sources is a common problem when using the Event Log from within ASP.NET and is not an Enterprise Library specific problem.  See PRB: "Requested Registry Access Is Not Allowed" Error Message When ASP.NET Application Tries to Write New EventSource in the EventLog.

If you want to do configuration but not from a configuration file I would first recommend the Fluent Configuration API.  If that doesn't meet your needs then you can start to look at other approaches.

If you really want to use a string as configuration that is not from a configuration file you can do that:

    class Program

    {

        static void Main(string[] args)

        {

            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(ReadConfigSource());

 

            var logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

            logWriter.Write("test", "General");

        }

 

        public static IConfigurationSource ReadConfigSource()

        {

            string loggingConfig = @"<?xml version=""1.0"" encoding=""utf-8"" ?>

                   <loggingConfiguration name="""" tracingEnabled=""true"" defaultCategory=""General"">

        <listeners>

            <add name=""Event Log Listener"" type=""Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                listenerDataType=""Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                source=""Enterprise Library Logging"" formatter=""Text Formatter""

                log="""" machineName=""."" traceOutputOptions=""None"" />

        </listeners>

        <formatters>

            <add type=""Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                template=""Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}""

                name=""Text Formatter"" />

        </formatters>

        <categorySources>

            <add switchValue=""All"" name=""General"">

                <listeners>

                    <add name=""Event Log Listener"" />

                </listeners>

            </add>

        </categorySources>

        <specialSources>

            <allEvents switchValue=""All"" name=""All Events"" />

            <notProcessed switchValue=""All"" name=""Unprocessed Category"" />

            <errors switchValue=""All"" name=""Logging Errors &amp; Warnings"">

                <listeners>

                    <add name=""Event Log Listener"" />

                </listeners>

            </errors>

        </specialSources>

    </loggingConfiguration>

";

 

            LoggingSettings loggingSection = null;

 

            using (var stringReader = new StringReader(loggingConfig))

            {

                var xmlReader = XmlReader.Create(stringReader,

                    new XmlReaderSettings(){ IgnoreWhitespace = true });

 

                loggingSection = new LoggingSettings();

                loggingSection.ReadXml(xmlReader);

 

                xmlReader.Close();

            }

 

            var configSource = new DictionaryConfigurationSource();

            configSource.Add(LoggingSettings.SectionName, loggingSection);

 

            return configSource;

        }

    }

 

 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 8, 2012 at 8:20 AM

Hi Levy,

        Thank you for the code.

        Sorry, I have one more question: as my configuration file contains two sections: logingConfiguration and exceptionHandling.

        How to deal with exceptionHandling, shall read another XML string of exceptionHandling section and add it to DictionaryConfigurationSource?

        or Can directly read these two sections?

Editor
Feb 8, 2012 at 1:33 PM

If you want to bundle the configuration together then it probably makes sense to use a FileConfigurationSource and read the configuration in.  This is the easiest and cleanest way to load the configuration.  If you want to use strings without a file (if, for example, the configuration is returned from an external service or location) then you would have to do it one by one and add it to the DictionaryConfigurationSource:

        static void Main(string[] args)

        {

            var config = ReadConfigSource();

            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(config);

 

            var logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

            logWriter.Write("test", "General");

 

            var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

        }

 

        public static IConfigurationSource ReadConfigSource()

        {

            string loggingConfig = @"<?xml version=""1.0"" encoding=""utf-8"" ?>

    <loggingConfiguration name="""" tracingEnabled=""true"" defaultCategory=""General"">

        <listeners>

            <add name=""Event Log Listener"" type=""Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                listenerDataType=""Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                source=""Enterprise Library Logging"" formatter=""Text Formatter""

                log="""" machineName=""."" traceOutputOptions=""None"" />

        </listeners>

        <formatters>

            <add type=""Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                template=""Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}""

                name=""Text Formatter"" />

        </formatters>

        <categorySources>

            <add switchValue=""All"" name=""General"">

                <listeners>

                    <add name=""Event Log Listener"" />

                </listeners>

            </add>

        </categorySources>

        <specialSources>

            <allEvents switchValue=""All"" name=""All Events"" />

            <notProcessed switchValue=""All"" name=""Unprocessed Category"" />

            <errors switchValue=""All"" name=""Logging Errors &amp; Warnings"">

                <listeners>

                    <add name=""Event Log Listener"" />

                </listeners>

            </errors>

        </specialSources>

    </loggingConfiguration>

";

 

            string exceptionConfig = @"<?xml version=""1.0"" encoding=""utf-8"" ?>  

    <exceptionHandling>

        <exceptionPolicies>

            <add name=""Policy"">

                <exceptionTypes>

                    <add name=""All Exceptions"" type=""System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""

                        postHandlingAction=""NotifyRethrow"">

                        <exceptionHandlers>

                            <add name=""Logging Exception Handler"" type=""Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35""

                                logCategory=""General"" eventId=""100"" severity=""Error"" title=""Enterprise Library Exception Handling""

                                formatterType=""Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling""

                                priority=""0"" />

                        </exceptionHandlers>

                    </add>

                </exceptionTypes>

            </add>

        </exceptionPolicies>

    </exceptionHandling>

";

            DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();

            var loggingSettings = new LoggingSettings();

            Configure(LoggingSettings.SectionName, loggingConfig, loggingSettings, configSource);

 

            var exceptionSettings = new ExceptionHandlingSettings();

            Configure(ExceptionHandlingSettings.SectionName, exceptionConfig, exceptionSettings, configSource);

 

            return configSource;

        }

 

        private static void Configure(string sectionName,

            string config,

            SerializableConfigurationSection section,

            DictionaryConfigurationSource source)

        {

            using (var stringReader = new StringReader(config))

            {

                var xmlReader = XmlReader.Create(stringReader,

                    new XmlReaderSettings() { IgnoreWhitespace = true });

 

                section.ReadXml(xmlReader);

 

                xmlReader.Close();

            }

 

            source.Add(sectionName, section);

        }

 

    }

 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 13, 2012 at 2:13 AM

Hi Levy,

             Thanks for your code. Now it works.

Feb 15, 2012 at 1:58 AM

Hi Levy,

           Sorry to interrupt you again.

           I have some more questions:

          1. How to log message to a same file from different applications(web application, desk application), if set log file to the same.

              Currently I found that different files are generated.  does entLib support logging into same file? if it does, then how to make it?

           2. Is it possible to archive files to different folder, instead of remove previous files, so below case, only save latest 100 files, remove all other file 100 days ago. Is it possible to move other files into a arhive folder.

              rollFileExistsBehavior='Increment' rollInterval='Day' maxArchivedFiles='100'

           3. if maxArchivedFiles is not defined, what would happen if running out of disk space?

 

           Thank your very much!

 

Editor
Feb 15, 2012 at 2:58 AM

1) Trace Listener files are locked so you can't log into the same file from within different applications (or AppDomains or even other Trace Listeners).  The database trace listener or distributor service are able to handle logging from multiple applications.

2) Enterprise Library doesn't support the archive behavior you mention. It could be done with a scheduled task that would archive files older than n days every day.

3) If maxArchivedFiles is not defined it will default to 0.  In terms of behavior if you have rollFileExistsBehavior set to "Increment" then you could be creating a lot of log files and potentially filling up the disk.

 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Jun 6, 2012 at 10:22 AM

hi,

I am working with Microsoft.Practices.EnterpriseLibrary.Logging,

In my solution i have 8 projects including one webservice, i have only one webconfig file in entire solution which resided under the webservice.

Based on certain condition webservice is calling any one of the project with in the solution. for this scenario i want the separate log file for each project lets say

when ProjectA is getting called then it should write in projectA.LOG and when projectB is getting called then it should write in projectB.log file and so on.

pls suggest how to implement it.

~

Rupesh

Editor
Jun 7, 2012 at 5:23 AM

I created a new thread for this: http://entlib.codeplex.com/discussions/358666

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 15, 2013 at 8:25 PM
Edited Feb 15, 2013 at 8:28 PM
Hi People, We are facing the same issue in one of our Production servers. We have a web farm of 4 servers and one of the server has started throwing below exception.
All the 4 servers have same version of code, but 3 of them are working fine and one has started crashing since yesterday. We have done the initial research on checking the code/config/dll differences and we could not see any difference in the server where the issue is occurring. This is almost certain that it is an IIS/Serve level setting/permission issue, but I am still clueless. Can some one help us here?

Exception:

"Exception message: Activation error occured while trying to get instance of type LogWriter, key ""
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 57
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstanceTService in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 90
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer() in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\Logger.cs:line 413
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(LogEntry log) in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\Logger.cs:line 303
"
continued error....
"Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)".
Exception occurred while: Calling constructor Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener(System.String fileName, System.String header, System.String footer, Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.ILogFormatter formatter, System.Int32 rollSizeKB, System.String timeStampPattern, Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollFileExistsBehavior rollFileExistsBehavior, Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollInterval rollInterval, System.Int32 maxArchivedFiles).
Exception is: IOException - The account used is a computer account. Use your global user account or local user account to access this server.
"

All our boxes are win 2008 servers and the application has been smoothly running since 2 years. above issue is encountered for the first time.
Editor
Feb 15, 2013 at 9:01 PM
Edited Feb 16, 2013 at 5:14 AM
The exception that is being throw is:
IOException - The account used is a computer account. Use your global user account or local user account to access this server
Sounds like permissions. A quick search suggests it's in relation to determining the last write time which makes sense with the RollingFlatFileTraceListener since it uses that to determine when to roll. Try monitoring with Process Monitor to see if it can pinpoint the issue.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Feb 19, 2013 at 6:38 PM
Thanks. We got the root cause of this issue. Basically, enterprise Library logging always tries to make sure that it has access to all the "paths/share folders" at run time (e.g. if you provide a server path for error logging, even if your code does not follow the error condition, but ent lib will still try to access that location and will throw exception if it is not able to access the location).
In our case, we had one of our logs being written to a different domain server. Recently there was a change in the permission level and that is why the application was throwing above exception.
Editor
Feb 19, 2013 at 7:02 PM
Edited Feb 19, 2013 at 7:03 PM
Good to hear that it's working now.

If you look on the samples page there is a sample solution for Rolling XML Trace Listener Sample & (Rolling) Flat File Trace Listeners. In that project there are file based trace listeners with functionality that is based on the Rolling Flat File Trace Listener and Flat File Trace Listener so they should share the same behavior as those trace listeners. The only difference is that these new implementations resolve an issue where an error occurs during initialization preventing any logging from working by throwing an exception back to the caller when attempting to resolve a LogWriter from the container (which is what you were seeing).

Basically, the initialization exception is caught, saved, and swallowed so that the application continues to function. Only when a Write is attempted is the initialization exception thrown and silently handled by the Enterprise Library infrastructure (i.e. the error will be sent to the errors special source for processing detailing the initialization error along with the current LogEntry). This way the application continues to function even though the logging is not working properly.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Feb 19, 2013 at 7:11 PM
Thanks a lot. Let me try different options that the "(Rolling) Flat File Trace Listeners" provide.
I wonder that such exceptions must be suppressed by default so that application should continue to function.
Also, the exception message should have been more informative though.