Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enterprise Library Logging in Azure Database

0.00/5 (No votes)
11 Apr 2016 1  
Enterprise Library Logging in Azure Database

Introduction

Logging is useful for trouble-shooting, activity tracking, and audit. Every project should have logging implemented. There are number of logging technologies available like log4net, trace listeners, etc. Then what is different with Enterprise Library Logging? It simplifies login. It allow us to choose where you want to store your logs and it manages the rest of the things very easily.

Background

This article will help you to implement logging in Azure Database using Enterprise Library Logging. Any C# project which is using Azure Database connection, then this logging can implement with the same database.

Using the Code

Steps

  1. Install the following nuget packages:
    • Enterprise library logging
    • Windows Azure configuration manage r
  2. After successful installation of Enterprise logging package, open that package folder, you will see script files like shown below:

  3. Because you are having your Azure database already created, just run second script in the database.
  4. Windows Azure configuration manager package is required to apply logging configurations at Azure side.(Note: Because if you will try the logging without this package, logs will get stored on local DB, but not on Azure DB.)
  5. Configuration settings need to do as:
    • In <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"/>
    • In <configuration>, add the following code, where there is an option to define database context name in the field "databaseInstanceName". Specify your Azure DB context name there.
      <loggingConfiguration name="loggingConfiguration" 
      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.1304.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="{database context name}" 
            writeLogStoredProcName="WriteLog" 
            addCategoryStoredProcName="AddCategory" 
            traceOutputOptions="DateTime, Timestamp, ProcessId"/>
          </listeners>
          <categorySources>
            <add switchValue="All" name="General">
              <listeners>
                <add name="Database Trace Listener"/>
              </listeners>
            </add>
          </categorySources>
          <specialSources>
            <allEvents switchValue="All" name="All Events">
              <listeners>
                <add name="Database Trace Listener"/>
              </listeners>
            </allEvents>
            <notProcessed switchValue="All" name="Unprocessed Category">
              <listeners>
                <add name="Database Trace Listener"/>
              </listeners>
            </notProcessed>
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
              <listeners>
                <add name="Database Trace Listener"/>
              </listeners>
            </errors>
          </specialSources>
        </loggingConfiguration>
  6. Check versions of DLL here, it may be possible that you will use different versions.
  7. Now, you have log table in your Azure database and stored procedures to write logs also. You just need a code to call this. Let's create a separate class for log:
    • public static class Log
          {
              static Log()
              {
                  DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);
                  Logger.SetLogWriter(new LogWriterFactory().Create(), false);
              }
      
              public static void AddError(Exception exception, int priority = 0, string jsonModel = null)
              {
                  try
                  {
                      var msgBody = new StringBuilder();
                      msgBody.AppendLine("-----WebJobException Begin: {0}-----");
                      msgBody.AppendLine(string.Format("\tHostName: {0}", Dns.GetHostName()));
                      msgBody.AppendLine(string.Format("\tSiteName: {0}", HostingEnvironment.SiteName));
                      msgBody.AppendLine(string.Format("\tAction: {0}", exception.TargetSite));
                      msgBody.AppendLine(string.Format("\tModel: {0}", jsonModel));
                      msgBody.AppendLine(string.Format("\tExceptionType: {0}", exception.GetType()));
                      msgBody.AppendLine(string.Format("\tExceptionMessage: {0}", exception.Message));
                      msgBody.AppendLine(string.Format("\tStackTrace: {0}", exception.StackTrace));
      
                      if (exception.InnerException != null)
                      {
                          msgBody.AppendLine(string.Format("\tInnerExceptionType: {0}", exception.InnerException.GetType()));
                          msgBody.AppendLine(string.Format("\tInnerExceptionMessage: {0}", exception.InnerException.Message));
                          msgBody.AppendLine(string.Format("\tInnerExceptionStackTrace: {0}", exception.InnerException.StackTrace));
                      }
      
                      msgBody.AppendLine("-----WebJobException End: {0}-----"); WriteLog(msgBody.ToString(), TraceEventType.Error);
                  }
                  catch (Exception ex)
                  {
                      return;
                  }
              }
      
              public static void AddInformation(string message)
              {
                  try
                  {
                      WriteLog(message, TraceEventType.Information);
                  }
                  catch (Exception ex)
                  {
                      return;
                  }
              }
      
              private static void WriteLog(string message, TraceEventType information)
              {
                  try
                  {
                      var logEntry = new LogEntry { Message = message, Severity = information };
                      Logger.Write(logEntry);
                  }
                  catch (Exception ex)
                  {
                      return;
                  }
              }
          }
  8. I have created this adding error logic as per my requirements, you can edit and make changes as per your code and requirement.
  9. Now, just call these functions to log your entries.
  10. That's it! 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here