Click here to Skip to main content
15,878,970 members
Articles / Programming Languages / C#

Enterprise Library Logging in Azure Database

Rate me:
Please Sign up or sign in to vote.
3.86/5 (3 votes)
10 Apr 2016CPOL2 min read 13.4K   5  
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>
      XML
      <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.
      XML
      <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Saviant Consulting
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --