Not able to see the logging errors in the event viewer while using enterprise library

Aug 11, 2014 at 9:06 AM
Edited Aug 11, 2014 at 9:07 AM
Hi,

I am using the following configuration file for logging of the errors in the event viewer.

<?xml version="1.0"?>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, PublicKeyToken=31bf3856ad364e35"
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, PublicKeyToken=31bf3856ad364e35"
    source="Enterprise Library Logging" formatter="Text Formatter"
    log="LuckyLogListner" machineName="." traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, 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">
  <listeners>
    <add name="Event Log Listener" />
  </listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
  <listeners>
    <add name="Event Log Listener" />
  </listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors &amp; Warnings">
  <listeners>
    <add name="Event Log Listener" />
  </listeners>
</errors>
</specialSources>
</loggingConfiguration>

I am calling this above config file from app.config

<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging,PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration configSource="Logging.config" />
Aug 11, 2014 at 9:12 AM
I am using the following class for the same.

using System;
using System.Runtime.Remoting.Messaging;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Example
{
/// <summary>
/// Class to invoke the Log & Trace engine of enterprise library framework
/// </summary>
public static class LogTraceEngine
{
    #region Private Variables

    private static LogWriter _defaultLogWriter;
    private static TraceManager _traceManager;
    private static object sync = new object();
    private delegate void WriteLogAsync(string logMessage);
    private delegate void WriteLogWithCategoryAsync(string logMessage, string category);
    private delegate void WriteLogArgumentsWithCategoryAsync(string logMessage, string  category, params string[] arguments);
    #endregion

    #region Public Methods

    /// <summary>
    /// Method to initialize services for logging in application
    /// </summary>
    public static void InitializeLoggingService()
    {
        try
        {
            //get the immediate application log writer and trace manager instance from Enterprise Library Container
            _defaultLogWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
            _traceManager = EnterpriseLibraryContainer.Current.GetInstance<TraceManager>();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Method to log message details in asynchronous process
    /// </summary>
    /// <param name="message">message to log</param>
    public static void LogAsync(string message)
    {
        WriteLogAsync logDefinition = new WriteLogAsync(WriteLog);
        AsyncCallback logDefinitionCompletedCallback = new AsyncCallback(LogDefinitionCompletedCallBack);
        lock (sync)
        {
            logDefinition.BeginInvoke(message, logDefinitionCompletedCallback, null);
        }
    }

    /// <summary>
    /// Method to log messages with log category mentioned
    /// </summary>
    /// <param name="message">message to log</param>
    /// <param name="category">log category</param>
    public static void LogAsync(string message, string category)
    {
        WriteLogWithCategoryAsync logDefinition = new WriteLogWithCategoryAsync(WriteLogWithCategory);
        AsyncCallback logDefinitionWithCategoryCompletedCallBack = new AsyncCallback(LogDefinitionWithCategoryCompletedCallBack);
        lock (sync)
        {
            logDefinition.BeginInvoke(message, category, logDefinitionWithCategoryCompletedCallBack, null);
        }
    }

    /// <summary>
    /// Method to log messages with log category mentioned
    /// </summary>
    /// <param name="message">message to log</param>
    /// <param name="category">log category</param>
    /// <param name="arguments">arguments</param>
    public static void LogAsync(string message, string category, params string[] arguments)
    {
        WriteLogArgumentsWithCategoryAsync logDefinition = new WriteLogArgumentsWithCategoryAsync(WriteLogParametersWithCategory);
        AsyncCallback logDefinitionWithParameterCategoryCompletedCallBack = new AsyncCallback(LogDefinitionWithParameterCategoryCompletedCallBack);
        lock (sync)
        {
            logDefinition.BeginInvoke(message, category, arguments, logDefinitionWithParameterCategoryCompletedCallBack, null);
        }
    }


    /// <summary>
    /// Method to write log in flat file of application directory location specified
    /// </summary>
    /// <param name="logMessage">log message</param>
    /// <param name="categoryName">category name</param>
    public static void WriteLog(string logMessage)
    {
        if (_defaultLogWriter != null)
            _defaultLogWriter.Write(logMessage, "General");
    }

    /// <summary>
    /// Method to write log information on the basis of category and message provided
    /// </summary>
    /// <param name="logMessage">log message</param>
    /// <param name="category">log category</param>
    public static void WriteLogWithCategory(string logMessage, string category)
    {
        if (_defaultLogWriter != null)
            _defaultLogWriter.Write(logMessage, category.ToString());
    }

    /// <summary>
    /// Method to write log information on the basis of category and message provided
    /// </summary>
    /// <param name="logMessage">log message</param>
    /// <param name="category">log category</param>
    public static void WriteLogParametersWithCategory(string logMessage, string category, params object[] arguments)
    {
        if (_defaultLogWriter != null)
        {
            if (arguments != null && arguments.Length > 0)
            {
                logMessage += "\r\nWith Field(s)/Value(s): ";

                foreach (var item in arguments)
                {
                    if (item != null)
                    {
                        if (arguments.Length > 1)
                        {
                            logMessage += string.Format("{0}~ ", item.ToString());
                        }
                        else
                        {
                            logMessage += string.Format("{0}", item.ToString());
                        }
                    }
                }
            }

            if (logMessage.Contains("~"))
            {
                logMessage = logMessage.Substring(0, logMessage.LastIndexOf('~'));
            }

            _defaultLogWriter.Write(logMessage,"General");
            _defaultLogWriter.Write(logMessage, category.ToString());
        }
    }

    /// <summary>   
    /// Method to write trace log in flat file of application directory location specified
    /// </summary>
    /// <param name="traceMessage">trace message</param>
    public static void WriteTrace(string traceMessage)
    {
        if (_defaultLogWriter != null)
            _defaultLogWriter.Write(traceMessage, "General");
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Method to handle the log completed call back method
    /// </summary>
    /// <param name="result">result obtained</param>
    private static void LogDefinitionCompletedCallBack(IAsyncResult result)
    {
        WriteLogAsync importStock = (WriteLogAsync)((AsyncResult)result).AsyncDelegate;
    }

    /// <summary>
    /// Method to handle the log with category completed call back method
    /// </summary>
    /// <param name="result">result obtained</param>
    private static void LogDefinitionWithCategoryCompletedCallBack(IAsyncResult result)
    {
        WriteLogWithCategoryAsync importStock = (WriteLogWithCategoryAsync)((AsyncResult)result).AsyncDelegate;
    }

    /// <summary>
    /// Method to handle the log with category completed call back method
    /// </summary>
    /// <param name="result">result obtained</param>
    private static void LogDefinitionWithParameterCategoryCompletedCallBack(IAsyncResult result)
    {
        WriteLogArgumentsWithCategoryAsync importStock = (WriteLogArgumentsWithCategoryAsync)((AsyncResult)result).AsyncDelegate;
    }

    #endregion
}
}

and in the .xaml.cs file i am initializing the class

Example.LogTraceEngine.InitializeLoggingService();

and in the click method of the button i am calling the method

Example.LogTraceEngine.WriteLog("Hello");
Aug 11, 2014 at 1:27 PM
Answer posted here: http://entlib.codeplex.com/workitem/33827 but the forum is the better place for these questions so continue on this thread:

You need Administrator permission to create the EventLog. If you add a flat file trace listener you wills see the error:
----------------------------------------
Logging Errors & Warnings Error: 6352 : Timestamp: 8/11/2014 4:38:24 AM
Message: Tracing to LogSource 'General' failed. Processing for other sources will continue. See summary information below for more information. Should this problem persist, stop the service and check the configuration file(s) for possible error(s) in the configuration of the categories and sinks.


Summary for Enterprise Library Distributor Service:
======================================
--> 
Message: 
Timestamp: 8/11/2014 4:38:24 AM
Message: Hello
Category: General
Priority: -1
EventId: 1
Severity: Information
Title:
Machine: 
App Domain: WpfApplication1.exe
ProcessId: 3420
Process Name: WpfApplication1.exe
Thread Name: 
Win32 ThreadId:8260
Extended Properties: 
--> MachineName: 
--> TimeStamp: 8/11/2014 4:38:24 AM
--> FullName: Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
--> AppDomainName: WpfApplication1.exe
--> WindowsIdentity: 

Exception Information Details:
======================================
Exception Type: System.Security.SecurityException
Action: 0
PermissionType: NULL
FirstPermissionThatFailed: NULL
PermissionState: NULL
Demanded: NULL
GrantedSet: NULL
RefusedSet: NULL
DenySetInstance: NULL
PermitOnlySetInstance: NULL
FailedAssemblyInfo: NULL
Method: NULL
Zone: MyComputer
Url: NULL
Message: The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.
Data: System.Collections.ListDictionaryInternal
TargetSite: Microsoft.Win32.RegistryKey FindSourceRegistration(System.String, System.String, Boolean, Boolean)
HelpLink: NULL
Source: System
HResult: -2146233078

StackTrace Information Details: 
======================================
   at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
   at System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate)
   at System.Diagnostics.EventLogInternal.VerifyAndCreateSource(String sourceName, String currentMachineName)
   at System.Diagnostics.EventLogInternal.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
   at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
   at System.Diagnostics.EventLogTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType severity, Int32 id, Object data)
   at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedTraceListenerWrapperBase.TraceData(TraceEventCache eventCache, String source, TraceEventType severity, Int32 id, Object data) in c:\EntLib\Entlib\Source\Blocks.Desktop\Logging\Src\Logging\TraceListeners\FormattedTraceListenerWrapperBase.cs:line 88
   at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.TraceListenerWrapper.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data) in c:\EntLib\Entlib\Source\Blocks.Desktop\Logging\Src\Logging\TraceListeners\TraceListenerWrapper.cs:line 92
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogSource.TraceData(TraceEventType eventType, Int32 id, LogEntry logEntry, TraceListenerFilter traceListenerFilter, TraceEventCache traceEventCache) in c:\EntLib\Entlib\Source\Blocks.Desktop\Logging\Src\Logging\LogSource.cs:line 178
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl.ProcessLog(LogEntry log, TraceEventCache traceEventCache) in c:\EntLib\Entlib\Source\Blocks.Desktop\Logging\Src\Logging\LogWriterImpl.cs:line 553
Category: 
Priority: -1
EventId: 6352
Severity: Error
Title:
Machine: 
App Domain: WpfApplication1.exe
ProcessId: 3420
Process Name: WpfApplication1.exe
Thread Name: 
Win32 ThreadId:8260
Extended Properties: 
----------------------------------------
You can pre-create the EventLog by running an application/script as Administrator that writes an entry to the EventLog (and creates the required registry entries).

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to