logging stack trace with logger - c#

I am using Logging Application block with C#.Net 2.0. My code is logging the error information to a flat file. I have set all required configuration in web.config like listeners, formatters and categories, etc as described in msdn and it is working fine.
But the problem is, I cannot put more than 50 characters in le.Message property. In my case, the stack trace is more than 500 charactors long which I want to log into the flat file when error occurs.
Is there any limit on number of charactors we can put inside Message Property of LogEntry object? or is there any other way to log the stack trace into logger flat file?
Here is the simple code.
LogEntry le = new LogEntry();
le.Categories.Add("ErrorsToEventLog");
le.Categories.Add("ErrorsToLogFile");
le.Title = "Error message";
le.TimeStamp = System.DateTime.Now;
le.Severity = System.Diagnostics.TraceEventType.Error;
le.Message = "<text of error's stack trace>";
Logger.write(le);
configuration settings
<configSections>
<section name="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" />
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" />
</configSections>
Here is the formatter I used,
<formatters>
<add template="Timestamp: {timestamp} Message: {message}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=null" name="Text Formatter" />
</formatters>
And here is the listener,
<add fileName="Logs/ErrorLog_{Date}.log"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.
CustomTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" traceOutputOptions="None"
type="EnterpriseLibrary.Logging.Extensions.RollingFlatFileTraceListener,
EnterpriseLibrary.Logging.Extensions, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null" name="Custom TraceListener" initializeData="" />
Categories
<categorySources>
<add switchValue="All" name="ErrorsToEventLog">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
<add switchValue="All" name="ErrorsToLogFile">
<listeners>
<add name="Custom TraceListener" />
</listeners>
</add>
</categorySources>

To my knowledge, there is no such limit for log message. How do you set the stack trace to the message?

Assuming your analysis is correct (it isn't convenient for me to double-check right now), have you considered creating a subclass for LogEntry that doesn't have the limits that you're running up against?

Related

How do I update my web.config for sending error through email in C#?

I am using Visual Studio 2013, the web server is running .NET 4, and I am getting a error on a web form on the live server, that works fine running on localhost.
It is currently emailing errors when I debug my web application through localhost and I would like it to send me errors when it is live (and if possible, on my localhost as well). It used to send me errors from the production server but when I started debugging, it changed some settings and now it doesn't anymore.
I am assuming that the problem is a setting somewhere, can anyone give some general ideas on where to look for the problem? Here is some code from my web.config for exception handling, is there some other code that could help clarify the problem?
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add toAddress="cynthiat#myurl.com" fromAddress="sysadmin#myurl.com" subjectLineStarter="" subjectLineEnder="" smtpServer="###.###.###.###" smtpPort="##" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Email TraceListener" />
<add source="Enterprise Library Logging" formatter="Text Formatter" log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds5" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Formatted EventLog TraceListener" />
</listeners>
<formatters>
<add template="Extended Properties: {dictionary({key} - {value}
)}
Message: {message}
Timestamp: {timestamp}
Severity: {severity}
Machine: {machine}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="Email TraceListener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="Global Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=f890890fsfds" name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
We can't help too much with your specific question without seeing more of your config file(s) and/or error handling code that sends e-mail notifications. However, another solution to your problem may be an error hanndling/logging/notification framework, such as:
ELMAH
ELMAH: Error Logging Modules and Handlers for ASP.NET (and MVC too!)
NuGet package - https://www.nuget.org/packages/elmah/
Source - https://code.google.com/p/elmah/
Cloud logging - https://elmah.io
Enterprise Library
Microsoft Enterprise Library
Logging application block
Exception Handling application block

EntLib 6 Logging Block on SQL issue with TraceListenerData

I want to log my application with Enterprise Library 6 in a SQL DB.
I launched the SQL scripts to create SQL things, and I decided to put Logger in Class Library.
Here is the code i've done in order to make the POC:
Portable Class content:
public static void LogToDatabase()
{
try
{
//Bootstrapping logging
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
Logger.SetLogWriter(logWriterFactory.Create());
if (Logger.IsLoggingEnabled())
{
LogEntry log = GetLogEntry();
log.Categories.Add("General"); // name of Categorie in EntLib Config editor
log.Priority = 5;
log.Severity = System.Diagnostics.TraceEventType.Information;
log.Message = "Hello dude, from Logger";
Logger.Write(log);
}
}
catch (Exception ex)
{
}
}
private static LogEntry GetLogEntry()
{
LogEntry log = new LogEntry();
log.TimeStamp = DateTime.Now;
log.Title = "TANOLIS";
log.Priority = 5; // default priority
log.Severity = System.Diagnostics.TraceEventType.Verbose; // default severity
log.MachineName = "MachineName";//HttpContext.Current.Server.MachineName;
log.ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
return log;
}
And this is the Config string I've done in the Unit test (where I launch the LogToDatabase()) :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
databaseInstanceName="DB_Belval" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory" formatter="DB Command Formatter" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="DB Command Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<dataConfiguration defaultDatabase="MY-DB" />
<connectionStrings>
<add name="DB_Belval" connectionString="Data Source=server;Initial Catalog=catalog;Persist Security Info=True;User=username;Password=pwd"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
The error comes in this line:
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
and is
Invalid TraceListenerData type in configuration 'listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"'.
Thanks to help me :-)
I finally found the solution, I included using Microsoft.Practices.EnterpriseLibrary.Logging.Database; to the caller (the UnitTest)
Question is resolved but it still not working... so warning, don't take the whole code :-)

Enterprise Library 6 - dynamically change log file name

Is it possible to dynamically set log folder and file name in C# which overrides the config value(file name) in the Listeners section of logging configuration?
Tried to follow the below link but it is applicable only for EL 5
Log messages going to previously created log file
This is how i Initialize EL Logging:
IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
Logger.SetLogWriter(logWriterFactory.Create(), false);
ExceptionPolicyFactory factory = new ExceptionPolicyFactory(configurationSource);
ExceptionPolicy.SetExceptionManager(factory.CreateManager());
These are my web.config entries inside the listeners tag:
<add name="RollingFlatFileTraceLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\logs\Trace.log" footer=""
formatter="CustomRollingFlatFileLogFormatter"
header="" rollFileExistsBehavior="Overwrite" rollInterval="Day"
rollSizeKB="2048" maxArchivedFiles="52" />
<add name="RollingFlatFileErrorLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\logs\Error.log" footer="----------------------------------------"
formatter=" CustomRollingFlatFileLogFormatter "
header="----------------------------------------" rollFileExistsBehavior="Overwrite"
rollInterval="Day" rollSizeKB="2048" maxArchivedFiles="52" />
I use Logger.Write and ExceptionPolicy.HandleException to write to the corresponding trace and error logs.
The best (and easiest!) approach would be to use programmatic configuration to set the filename.
However, you can use a similar approach to modify settings at runtime. Setup the configuration in an external file and use a file configuration source in app/web.config. An external file is necessary to avoid a configuration is read-only exception.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<enterpriseLibrary.ConfigurationSource selectedSource="File-based Configuration Source">
<sources>
<add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
filePath="entlib.config" />
</sources>
</enterpriseLibrary.ConfigurationSource>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>
And configure the external file (entlib.config in this case):
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<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=6.0.0.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>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
source="Enterprise Library Logging" formatter="Text Formatter"
log="" machineName="." traceOutputOptions="None" />
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="trace.log" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="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 & Warnings">
<listeners>
<add name="Event Log Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>
Use the SerializableConfigurationSource from the blog posting:
public class SerializableConfigurationSource : IConfigurationSource
{
Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
public SerializableConfigurationSource()
{
}
public ConfigurationSection GetSection(string sectionName)
{
ConfigurationSection configSection;
if (sections.TryGetValue(sectionName, out configSection))
{
SerializableConfigurationSection section = configSection as SerializableConfigurationSection;
if (section != null)
{
using (StringWriter xml = new StringWriter())
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml))
{
section.WriteXml(xmlwriter);
xmlwriter.Flush();
MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() });
return configSection;
}
}
}
return null;
}
public void Add(string sectionName, ConfigurationSection configurationSection)
{
sections[sectionName] = configurationSection;
}
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public void Remove(string sectionName)
{
sections.Remove(sectionName);
}
public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;
public void Dispose()
{
}
}
Bootstrap the blocks at startup:
IConfigurationSource configSource = ConfigurationSourceFactory.Create();
var loggingSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;
var data = loggingSettings.TraceListeners.First(t => t.Name == "Flat File Trace Listener") as FlatFileTraceListenerData;
// Change the file name
data.FileName = "trace_1.txt";
var loggingXmlConfigSource = new SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings);
var logFactory = new LogWriterFactory(loggingXmlConfigSource);
Logger.SetLogWriter(logFactory.Create());
IConfigurationSource config = ConfigurationSourceFactory.Create();
ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config);
ExceptionManager exManager = factory.CreateManager();
ExceptionPolicy.SetExceptionManager(exManager);
// This will log to the file trace_1.txt
ExceptionPolicy.HandleException(new Exception(), "Policy");
As you have mentioned in the post, Setup the configuration in an external file. External file means, can you confirm in which path we have to place the Entlib.config file.

Microsoft.Practices.ServiceLocation.ActivationException was unhandled by user code

I am working on migrating the current ASP.NET application from 2.0 to 4.0 and also trying to migrate the enterprise library to 5.0 from 4.0
I have made all the necessary changes in the configuration file. All the application is working on project mates machine but it is not working on my machine.
Stack Trace of the error I am getting ---
Microsoft.Practices.ServiceLocation.ActivationException was unhandled by user code
HResult=-2146233088
Message=Activation error occured while trying to get instance of type LogWriter, key ""
Source=Microsoft.Practices.ServiceLocation
StackTrace:
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer()
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(LogEntry log)
at App.LogEntryHelper.WriteLogEntry(LogEntry entry, String category) in c:\App.Client.WebUI\AppCode\LogEntryHelper.cs:line 252
at App.LogEntryHelper.WriteFacadePerformanceLog(DateTime start, DateTime end) in c:\App.Client.WebUI\AppCode\LogEntryHelper.cs:line 209
at App.Facade.FutureEventFacade.GetFutureEventsParticipant(Int64 participantID) in c:\App.Client.WebUI\Facade\FutureEventFacade.cs:line 92
at App.Facade.ParticipantFacade.GetParticipant(Int64 participantID) in c:\App.Client.WebUI\Facade\ParticipantFacade.cs:line 81
at App.ParticipantPage.Page_Load(Object sender, EventArgs e) in c:\App.Client.WebUI\ParticipantPage.aspx.cs:line 67
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Adapters.ControlAdapter.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type LogWriter cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter,(none)
Source=Microsoft.Practices.Unity
TypeRequested=LogWriter
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityServiceLocator.DoGetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type LogWriter cannot be constructed. You must configure the container to supply this value.
Source=Microsoft.Practices.Unity
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
Here are the details of configuration file
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="App.Properties.SecuritySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="App.Properties.ReportingSettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="App.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</sectionGroup>
<sectionGroup name="system.web">
<section name="uploadManagement" type="App.WebControls.UploadModule, App.WebControls"/>
</sectionGroup>
<!-- AJAX -->
<!-- End AJAX -->
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="App.Debug.log" header="----------------------------------------" footer="----------------------------------------" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Debug Flat File TraceListener"/>
<add fileName="App.Client.WebUI.Facade.Performance.log" header="----------------------------------------" footer="----------------------------------------" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Facade Performance Flat File TraceListener"/>
<add fileName="App.Exception.log" rollSizeKB="10000" timeStampPattern="ddd" rollFileExistsBehavior="Overwrite" rollInterval="Day" formatter="Text Formatter" header="----------------------------------------" footer="----------------------------------------" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="Callstack" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Rolling Flat File TraceListener"/>
<add source="AdminTool Web UI" formatter="Text Formatter" log="AdminTool" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="Callstack" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="WebUI EventLog TraceListener"/>
<add fileName="App.SSO.log" header="----------------------------------------" footer="----------------------------------------" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="SSO Flat File TraceListener"/>
</listeners>
<formatters>
<add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter"/>
</formatters>
<logFilters>
<add minimumPriority="0" maximumPriority="3" type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Priority Debug Filter"/>
</logFilters>
<categorySources>
<add switchValue="All" name="Web UI Debug">
<listeners>
<add name="Debug Flat File TraceListener"/>
</listeners>
</add>
<add switchValue="All" name="Web UI Exception">
<listeners>
<add name="Rolling Flat File TraceListener"/>
<add name="WebUI EventLog TraceListener"/>
</listeners>
</add>
<add switchValue="All" name="Web UI Facade Performance">
<listeners>
<add name="Facade Performance Flat File TraceListener"/>
</listeners>
</add>
<add switchValue="All" name="Web UI SSO">
<listeners>
<add name="SSO Flat File TraceListener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events"/>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="Debug Flat File TraceListener"/>
<add name="WebUI EventLog TraceListener"/>
<add name="SSO Flat File TraceListener"/>
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings"/>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="WebUI Policy">
<exceptionTypes>
<add type="System.DirectoryServices.DirectoryServicesCOMException, System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" postHandlingAction="None" name="DirectoryServicesCOMException"/>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="None" name="Exception">
<exceptionHandlers>
<add logCategory="Web UI Exception" eventId="2000" severity="Error" title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Logging Handler"/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
I am able to resolve the issue. I found that I have installed version of ESB 2.0 which was causing the issue. Whenever application is trying to log something IIS used to look into the ESB configuration file instead of web.config file. As soon as I uninstalled the ESB application everything started working.
For me I was opening another configuration file which had the enterpriseLibrary but it was missing from the local app configuration file. I added the following into the local configuration and I got past the error.
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral" requirePermission="true" />
</configSections>

Unity: The type LogWriter cannot be constructed

For the following "project" I am getting a very annoying and inexplicable error when resolving Unity for DI.
InvalidOperationException - The type LogWriter cannot be constructed.
You must configure the container to supply this value.
?ex.Message; "Resolution of the dependency failed, type =
\"WindowsFormsApplication1.Performance\", name =
\"(none)\".\r\nException occurred while: while resolving.\r\nException
is: InvalidOperationException - The type LogWriter cannot be
constructed. You must configure the container to supply this
value.\r\n-----------------------------------------------\r\nAt the
time of the exception, the container was:\r\n\r\n Resolving
WindowsFormsApplication1.Performance,(none)\r\n Resolving parameter
\"lw\" of constructor
WindowsFormsApplication1.Performance(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter
lw,
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManager
em)\r\n Resolving
Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter,(none)\r\n"
?ex.StackTrace; " at
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object
existing, String name, IEnumerable1 resolverOverrides) in
e:\\Builds\\Unity\\UnityTemp\\Compile\\Unity\\Unity\\Src\\UnityContainer.cs:line
515\r\n at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type
t, String name, IEnumerable1 resolverOverrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line
485\r\n at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t,
String name, ResolverOverride[] resolverOverrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line
173\r\n at
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer
container, ResolverOverride[] overrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainerExtensions.cs:line
504\r\n at WindowsFormsApplication1.Form1.OnLoad(EventArgs e) in
D:\Devzone\Tasking\WindowsFormsApplication1\Form1.cs:line 33"
In a form:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
IUnityContainer container = new UnityContainer();
Performance p = container.Resolve<Performance>();
}
catch (Exception ex)
{
}
}
Dependency class:
public class Performance
{
public Performance(LogWriter lw, ExceptionManager em)
{
}
}
Configuration File:
<?xml version="1.0" encoding="utf-8" ?>
<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="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.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.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Event Log Listener" />
</listeners>
</add>
<add switchValue="All" name="Category2" />
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Event Log Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<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" />
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
You need to add the Enterprise Library extension to your container. Without it, the container doesn't read the config file and therefore doesn't know how to create Entlib objects, like the LogWriter.
Activation error occured while trying to get instance of type LogWriter, key ""
check your config file it must have correct default 'loggingConfiguration' section
In order for Unity to construct your Performance class, it needs to know how to construct the implementation of ILogWriter.
I cannot see anywhere in your code where you tell Unity what class to create for the ILogWriter interface, so I suspect you may need to add this.
Try this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogWriter, LogWriter>();
container.RegisterType<ExceptionManager>();
container.RegisterType<Performance>(new InjectionConstructor(typeof(ILogWriter), typeof(ExceptionManager));
Performance p = container.Resolve<Performance>();
}
catch (Exception ex)
{
}
}
LogWriter does not have an empty constructor or a constructor with all concrete types parameters: LogWriter Constructor.
So Unity fails in building it and as it says, it will need your help by configuring the container to provide an implementation.
As a confirmation, ExceptionManager will probably be resolved ok, since it has only one constructor, parameterless as well :)

Categories

Resources