Sitefinity Part 1 — Capturing Sitefinity logs and pushing them to Azure Storage

This is the first part of the Sitefinity series. For your convenience you can find other parts using the links below (or by guessing the address):
Part 1 — Capturing logs
Part 2 — Dependency Injection
Part 3 — Changing connection string
Part 4 — Turning on Redis

Let’s assume that we have properly configured Sitefinity instance to work in Azure (which includes using Azure SQL database and Azure Redis instance). Now there is a question: how do we capture logs and send them to Azure Storage?

By default Sitefinity logs everything to files in App_Data\Sitefinity\Logs directory. We can easily use Azure logging facilities (which can be enabled in Azure Portal in section Diagnostic logs) but we need to log using Trace class. In order to do that, we need to implement custom listener and configure Sitefinity to use it. Let’s go.

Implementation

First, in Sitefinity we need to register for bootstrapping event when actual logging configuration is enabled. In Global.asax.cs add the following:

Sitefinity uses logging classes from Microsoft Enterprise Library (Entlib) to manage logs. We can extract configuration in runtime and replace it using custom listeners:

We extract listeners from Sitefinity internals. It is named collection describing how to create concrete loggers. There are loggers for errors (which by default log to Error.log file), debug, trace, etc. Since we would like to redirect all logs to Azure Storage, we need to remove all existing configurations and inject ours. To do that, we iterate over all loggers, remove them one by one and create custom loggers with same names.

Actual logger looks as follows:

In configuration class we want to log everything on all levels. Actual logger only redirects messages to Trace class.

Now, we need to configure logging to Azure Storage. First, we enable it in Azure Portal. Next, we need to add trace listener for Azure. We add the following to web.config:

We add to listeners: one for Azure and another to log to drive. The latter is useful for running application locally, it redirects all logs (errors, SQL changes, etc.) to one file.

You might also need to add the following to web.config

Now you can also configure Log Analytics and have Sitefinity logs in OMS.

Tested with Sitefinity version: 10.0.6411.0.