Skip to content

LogToDb

Robert Brands edited this page Dec 11, 2018 · 8 revisions

This function reads a message intended to be used as activity log for an application from a message queue and writes it into a CosmosDB. For this to work the following preequisites must be fulfilled.

From connection string "AzureWebJobsStorage" the connection to a Azure Storage Account is read. Normally this will be the Storage Account associated with the Azure Functions App during creation. Messages are read from message queue "logging".

A message should be a Json document like this:

{
	"tenant": "MyTenant",
	"category": "Info",
	"user": "Username",
	"messageTag": "MessageTag",
	"message": "Plain text as message",
	"clientInfo": "Description of Client/browser"
}

The following example shows how to write into the Messasge Queue with C#

        public async Task LogToDb(ActivityLogItem logItem)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_functionsConfig.StorageConnectionString);
            // Create the queue client.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            // Retrieve a reference to a container.
            CloudQueue queue = queueClient.GetQueueReference("logging");
            // Create the queue if it doesn't already exist
            await queue.CreateIfNotExistsAsync();
            logItem.Tenant = _functionsConfig.DbTenant;
            string serializedLogActivity = JsonConvert.SerializeObject(logItem);
            // Create a message and add it to the queue.
            CloudQueueMessage queueMessage = new CloudQueueMessage(serializedLogActivity);
            await queue.AddMessageAsync(queueMessage);

            return;
        }

This message is written with a TTL of 2 days to CosmosDB. The connection string for this database must be stored as application Setting "CosmosDBConnection". Configure the Attributes of the function with the database name and collection.

To use the logging via HTTPS use QueueLogToDb

Clone this wiki locally