File logging not working

Topics: Logging Application Block
Nov 18, 2010 at 10:15 AM

I have created one application using enterprise library 4.1 and i enabled file log, event log and email log.

now event log and email log working fine but file log is not working.

this is my web.config settings

 

<configSections> <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>    <!--<section name="securityConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings, Microsoft.Practices.EnterpriseLibrary.Security, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />--> </configSections> <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add toAddress="don@empressdigital.com" fromAddress="anil@empressdigital.com" subjectLineStarter="eMAMGateway Error -" subjectLineEnder="" smtpServer="mail.empresstech.com" smtpPort="25" formatter="EmailTextFormatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Email TraceListener"/> <add source="eMAMGateway" formatter="EventTextFormatter" log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="EventLog TraceListener"/> <add fileName="eMAMGateway.log" header="*********" footer="*********" formatter="FileTextFormatter" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="5120" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Rolling Flat File Trace Listener"/> </listeners>    <formatters> <add template="*This is an auto-generated e-mail. Please don't reply to it!*&#xA;&#xA;Dear Customer,&#xA;&#xA; An error has occured in your eMAMGateway application. Following are the details of the issue. &#xA;&#xA;Message: {message}&#xA;&#xA;&#xA;Regards,&#xA;eMAMGateway notification system" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="EmailTextFormatter"/> <add template="Title:{title}&#xA;Message: {message}&#xA;Machine: {machine}&#xA;Process Id: {processId}&#xA;Process Name: {processName}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="EventTextFormatter"/> <add template="{message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="FileTextFormatter"/> </formatters> <categorySources> <add switchValue="All" name="Email"> <listeners> <add name="Email TraceListener"/> </listeners> </add> <add switchValue="All" name="EventLog"> <listeners> <add name="EventLog TraceListener"/> </listeners> </add> <add switchValue="All" name="FileLog"> <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"/> </specialSources> </loggingConfiguration>

Nov 18, 2010 at 10:19 AM

Configure the formatted event log trace listener under the Logging Errors and Warnings section.  When an error occurs while logging, a message will be logged using that trace listener indicating the exception that has occurred.

 

Sarah Urmeneta
Global Technologies & Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 18, 2010 at 11:10 AM

can you explain little more briefly how to configure the formatted event log trace listener under the Logging Errors and Warnings section

Nov 18, 2010 at 11:21 PM

Open your configuration file in the Enterprise Library Configuration Tool.  In the Logging Application Block section, there's a Special Sources node where the Logging Errors and Warnings node is. Right click on it and select New -> Trace Listener Reference.  Click on the added Trace Listener Reference and set the ReferencedTraceListener property to the name of your formatted event log trace listener.

 

Sarah Urmeneta
Global Technologies & Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 19, 2010 at 7:10 AM

I have configured the formatted event log trace listener under the Logging Errors and Warnings section. but i am not able to see any error log. and also the same web.config is working with dev server (XP machine) . Issue only with production server (windows server 2008) file logging. eventviewer and email logging also working fine in production server. 

 

Nov 19, 2010 at 7:22 AM

Interesting, did you use the same event log trace listener which you are sure is generating a log message?   Have you checked if you have the permission to create a file to the directory you configured it to be placed? 

 

Sarah Urmeneta
Global Technologies & Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 19, 2010 at 9:06 AM

 

yes the same event log trace listener.

I  had given full permission in web.config using identity tag and also if i am giving any path which containing sub folders to logg the error something like "test\test1\error.log" all the subfolders will create (i mean test and test1) but i can't see any error.log file inside the test1 folder.

Nov 21, 2010 at 12:39 AM
Edited Nov 21, 2010 at 12:40 AM

Could you post your code which attempts to log to the file?

 

Sarah Urmeneta
Global Technologies & Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 22, 2010 at 3:59 PM

 

    #region "Public enumarations"    public enum LOGLEVEL { CRITICAL = 1, ERROR = 2, INFO = 3, DEBUG = 4 };
    public enum ERRORPARAM { METHOD_NAMES = 1, LINE_NUMBER = 2, MESSAGE = 3, STACK_TRACE = 4, FILE_PATH = 5 };    #endregion
    #region "Private variable declarations"    private static LogEntry objLogEntry = null;    #endregion
    #region "Function declarations"    /// <summary>    /// Function to for each exception to a user defined collection.    /// </summary>    /// <param name="ex"></param>    /// <returns></returns>    public static Exception FormatException(Exception ex)    {        try        {            StackTrace objTrace = new StackTrace(ex, true);            int intIndex = objTrace.FrameCount - 1;            string strTemp = "";
            // Checks for Method name and appends the new method name to collection            if (ex.Data.Contains(ERRORPARAM.METHOD_NAMES))            {                strTemp = ex.Data[ERRORPARAM.METHOD_NAMES].ToString();
                ex.Data.Remove(ERRORPARAM.METHOD_NAMES);                ex.Data.Add(ERRORPARAM.METHOD_NAMES, strTemp + ":" + objTrace.GetFrame(intIndex).GetMethod().Name + "()");            }
            // Checks for the existence of values in collection and fill values            if (ex.Data.Count == 0)            {                ex.Data.Clear();                ex.Data.Add(ERRORPARAM.METHOD_NAMES, objTrace.GetFrame(intIndex).GetMethod().Name + "()");                ex.Data.Add(ERRORPARAM.LINE_NUMBER, objTrace.GetFrame(intIndex).GetFileLineNumber());                ex.Data.Add(ERRORPARAM.MESSAGE, ex.Message);                ex.Data.Add(ERRORPARAM.STACK_TRACE, ex.StackTrace);                ex.Data.Add(ERRORPARAM.FILE_PATH, objTrace.GetFrame(intIndex).GetMethod().ReflectedType.FullName.Replace(".", ":"));            }        }        catch (Exception)        {            Trace.Write(ex.Message);        }        return ex;    }
    /// <summary>    /// Function to log friendly messages.    /// </summary>    /// <param name="strMessage"></param>    /// <param name="logType: CRITICAL,ERROR,INFO,DEBUG"></param>    /// Critical - eamil,eventviewer,logfile,trace; ERROR - event viewer, trace logfile; INFO-logfile,trace; DEBUG - logfile    public static bool WriteLog(string strMessage, LOGLEVEL logLevel)    {        try        {            bool exists = System.Diagnostics.EventLog.SourceExists("eventname");            if (!exists)                System.Diagnostics.EventLog.CreateEventSource("eventname", "Application");
            objLogEntry = new LogEntry();
            /**********************************************************************************************************************/
            objLogEntry.Title = " eventname Error";            objLogEntry.Severity = GetSeverity(logLevel);            objLogEntry.Message = DateTime.Now.ToString("dd/MMM/yyyy HH:MM:ss") + ": " + GetLogType(logLevel) + ": " + strMessage;            objLogEntry.Categories = GetCategory(logLevel);
            /**********************************************************************************************************************/
            Logger.Write(objLogEntry);
            return true;        }        catch (Exception ex)        {            Trace.Write(ex.Message);        }        finally        {            objLogEntry = null;        }
        return false;    }
    /// <summary>    /// Function to log errors.    /// </summary>    /// <param name="ex"></param>    /// <param name="logType"></param>    public static bool WriteLog(Exception ex, LOGLEVEL logLevel)    {        string strFilePath = "";        string strMethods = "";        string strMessage = "";        string strStackTrace = "";
        try        {            bool exists = System.Diagnostics.EventLog.SourceExists("eMAMGateway");            if (!exists)                System.Diagnostics.EventLog.CreateEventSource("eMAMGateway", "Application");

            objLogEntry = new LogEntry();
            /*************************************************************************************************************/
            objLogEntry.Title = " eventname Error";            objLogEntry.Severity = GetSeverity(logLevel);
            strMessage = ex.Data[ERRORPARAM.MESSAGE] != null ? ex.Data[ERRORPARAM.MESSAGE].ToString() : ex.Message;            strMethods = ex.Data[ERRORPARAM.METHOD_NAMES] != null ? ex.Data[ERRORPARAM.METHOD_NAMES].ToString() : string.Empty;            strFilePath = ex.Data[ERRORPARAM.FILE_PATH] != null ? ex.Data[ERRORPARAM.FILE_PATH].ToString() : string.Empty;            strStackTrace = ex.Data[ERRORPARAM.STACK_TRACE] != null ? ex.Data[ERRORPARAM.STACK_TRACE].ToString() : string.Empty;
            objLogEntry.Message = DateTime.Now.ToString("dd/MMM/yyyy HH:MM:ss") + ": " + GetLogType(logLevel) + ": " +                strFilePath + ":" + strMethods + ": " + strMessage + " " + "StackTrace=" + strStackTrace;
            objLogEntry.Categories = GetCategory(logLevel);
            /*************************************************************************************************************/
            Logger.Write(objLogEntry);
            return true;        }        catch (Exception ex2)        {            Trace.Write(ex2.Message);        }        finally        {            objLogEntry = null;        }
        return false;    }
    #endregion
    #region "Private Functions"    private static ICollection<string> GetCategory(LOGLEVEL logLevel)    {        ICollection<string> iCategories = new List<string>(0);
        try        {            switch (logLevel)            {                case LOGLEVEL.CRITICAL:                    iCategories.Add("EventLog");                    iCategories.Add("FileLog");                    iCategories.Add("Email");                    break;                case LOGLEVEL.ERROR:                    iCategories.Add("EventLog");                    iCategories.Add("FileLog");                    break;                case LOGLEVEL.DEBUG:                    iCategories.Add("FileLog");                    break;                case LOGLEVEL.INFO:                    iCategories.Add("FileLog");                    break;                default:                    iCategories.Add("EventLog");                    break;            }        }        catch (Exception ex)        {            Trace.Write(ex.Message);        }
        return iCategories;    }
    private static string GetLogType(LOGLEVEL logCategory)    {        try        {            switch (logCategory)            {                case LOGLEVEL.CRITICAL: return "CRITICAL";                case LOGLEVEL.DEBUG: return "DEBUG";                case LOGLEVEL.ERROR: return "ERROR";                case LOGLEVEL.INFO: return "INFO";                default:                    return "";            }        }        catch (Exception ex)        {            Trace.Write(ex.Message);
            return "";        }    }
    private static TraceEventType GetSeverity(LOGLEVEL logLevel)    {        try        {            switch (logLevel)            {                case LOGLEVEL.CRITICAL:                    return TraceEventType.Critical;                case LOGLEVEL.ERROR:                    return TraceEventType.Error;                case LOGLEVEL.DEBUG:                    return TraceEventType.Verbose;                case LOGLEVEL.INFO:                    return TraceEventType.Information;                default:                    return TraceEventType.Information;            }        }        catch (Exception ex)        {            Trace.Write(ex.Message);
            return TraceEventType.Information;        }    }    #endregion

Nov 23, 2010 at 2:45 AM
Edited Nov 23, 2010 at 8:16 AM

Ah I think this might be the solution.  Try setting the Revert Impersonation property (revertImpersonation attribute) to false of the Logging Application Block. 

Taken from the documentation of EntLib 4.1 (Changes in the Logging Application Block)

"Added: Configuration support to opt-out of the impersonation-reverting default setting has been added. This fixes the rolling flat file trace listener problem when used in a Web application and when impersonation is enabled. To opt-out of the impersonation-reverting default mode, set the new <section> revertImpersonation attribute to false. The default setting is true. This supports configuration support, design time support, and manageability support (both WMI and group policy)."

 

Sarah Urmeneta
Global Technologies & Solutions
Avanade, Inc.
entlib.support@avanade.com

Nov 24, 2010 at 6:48 AM

Thanks Sarah Urmeneta thanks you very much. its great solution and now in all the places both production and development error logging working without any issues.

 

Once again thank you very much for your great support.