Graph Community: LoggingMessageHandler

The Graph Community library is not just about SharePoint stuff. While it does contain request builders and models for the SharePoint REST API, it also includes samples and utilities that will help you build better solutions. This post will cover one of the included utilities: the LoggingMessageHandler.

The GraphServiceClient object that is the core of the SDK uses the HttpMessage pipeline capabilities of .Net. This pipeline allows for multiple objects to "handle" the message, both on its way out (the request) and back in (the response) to your code. The SDK has several handlers that take care of the "plumbing" for us:

  • Authentication
  • Compression
  • Retry
  • Redirect

The LoggingMessageHandler provides the capability to get a log of requests and responses made by your code. The handler logs the Uri, headers and content of the request & response and makes the log available to your code as a string.

This is not intended to be a replacement for application logging and monitoring. The log is primarily a learning/debugging tool.

Insert the LoggingMessageHandler into the pipeline by using it your HttpProvider. (This snippet comes from the ImmutableIDs sample.)

var logger = new StringBuilderHttpMessageLogger();
/*
  *  Could also use the Console if preferred...
  *  
  *  var logger = new ConsoleHttpMessageLogger();
  */

var pca = PublicClientApplicationBuilder
            .Create(azureAdOptions.ClientId)
            .WithTenantId(azureAdOptions.TenantId)
            .Build();

var scopes = new string[] { "https://graph.microsoft.com/Mail.Read" };
IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
{
  GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);
  var result = await graphServiceClient.Me.Mail.GetAsync();

  var log = logger.GetLog();
}

(If you wish to add the LoggingMessageHandler alongside the built-in handlers, take care to change the load order. If it is "inside" the compression handler, it will not be able to log the content. If it is "outside" the retry and redirect handlers, those actions would not be logged.)