Skip to content

Instantly share code, notes, and snippets.

@lurumad
Created September 25, 2018 06:52
Show Gist options
  • Save lurumad/ca6fffb6aca94b107cbbd5de533f358a to your computer and use it in GitHub Desktop.
Save lurumad/ca6fffb6aca94b107cbbd5de533f358a to your computer and use it in GitHub Desktop.
APIM Logger

Create an API Management logger

https://{your service}.management.azure-api.net/loggers/{new logger name}?api-version=2017-03-01

Content-Type : application/json Authorization : SharedAccessSignature 58...

{
  "loggerType" : "AzureEventHub",
  "description" : "Sample logger description",
  "credentials" : {
    "name" : "Name of the Event Hub from the portal",
    "connectionString" : "Endpoint=Event Hub Sender connection string"
    }
}
{
    "id": "/loggers/{new logger name}",
    "loggerType": "azureEventHub",
    "description": "Sample logger description",
    "credentials": {
        "name": "Name of the Event Hub from the Portal",
        "connectionString": "{{Logger-Credentials-xxxxxxxxxxxxxxx}}"
    },
    "isBuffered": true,
    "resourceId": null
}

Configure log-to-eventhubs policies

<log-to-eventhub logger-id ='logger-id'>
  
</log-to-eventhub>

Create an Event Host Processor

class Program
    {
        static void Main(string[] args)
        {
            string eventHubConnectionString = "Endpoint=sb://...";
            string eventHubName = "api-pro-logs";
            string storageConnectionString = "UseDevelopmentStorage=true";
            string eventProcessorHostName = Guid.NewGuid().ToString();
            var eventProcessorHost = new EventProcessorHost(
                eventProcessorHostName,
                eventHubName,
                EventHubConsumerGroup.DefaultGroupName,
                eventHubConnectionString,
                storageConnectionString);
            eventProcessorHost.RegisterEventProcessorAsync<DkvProcessor>().Wait();
            Console.Read();
            eventProcessorHost.UnregisterEventProcessorAsync().Wait();
        } 
    }
class CustomEventProcessor : IEventProcessor
{
    public Task OpenAsync(PartitionContext context)
    {
        Console.WriteLine("Open");

        return Task.FromResult(0);
    }

    public Task CloseAsync(PartitionContext context, CloseReason reason)
    {
        Console.WriteLine("Close");

        return Task.FromResult(0);
    }

    public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
    {
        foreach (var message in messages)
        {
            Console.WriteLine(Encoding.UTF8.GetString(message.GetBytes()));
        }

        await context.CheckpointAsync();
    }

    public Task ProcessErrorAsync(PartitionContext context, Exception error)
    {
        Console.WriteLine($"{error.Message}");

        return Task.FromResult(0);
    }
}

Call APIM from Azure portal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment