Build status NuGet Samples

Logging from Azure WebJobs

Logging errors from Azure WebJobs, requires only a few lines of code. To start logging exceptions from WebJobs, choose one of two methods:

Manually using Elmah.Io.Client (the stable choice)

Install the Elmah.Io.Client NuGet package into your WebJob project:

Install-Package Elmah.Io.Client

Add the following code to your Program.cs file:

class Program
{
    static void Main()
    {
        AppDomain.CurrentDomain.UnhandledException += Log;
        ...
    }

    private static void Log(object sender, UnhandledExceptionEventArgs e)
    {
        var exception = e.ExceptionObject as Exception;
        if (exception != null)
        {
            var logger = ElmahioAPI.Create("API_KEY");
            client.Messages.Error(new Guid("LOG_ID"), exception, "An error message");
        }
    }
}

Remember to replace API_KEY with your API key (Where is my API key?) and LOG_ID (Where is my log ID?) with the ID of the log you want to log to.

Azure WebJobs automatically executes the Log-method when an exception is thrown. In this example, we simply log the exception registered in UnhandledExceptionEventArgs.

Automatic using Elmah.Io.Functions (the prerelease choice)

We've created a client specifically for Azure WebJobs. Install the Elmah.Io.Functions package:

Install-Package Elmah.Io.Functions -Pre

Log all uncaught exceptions using the ElmahIoExceptionFilter attribute:

[ElmahIoExceptionFilter("API_KEY", "LOG_ID")]
public class Functions
{
    public static void ProcessQueueMessage([QueueTrigger("queue")] string msg, TextWriter log)
    {
        throw new Exception("Some exception");
    }
}

Replace API_KEY with your API key (Where is my API key?) and LOG_ID (Where is my log ID?) with your log ID.

If your WebJob method is declared as async, remember to change the return type to Task. Without it, ElmahIoExceptionFilter is never invoked.

The filter also supports config variables:

[ElmahIoExceptionFilter("%apiKey%", "%logId%")]

The variables above, would require you to add your API key and log ID to your App.config:

<configuration>
  <appSettings>
    <add key="apiKey" value="API_KEY"/>
    <add key="logId" value="LOG_ID"/>
  </appSettings>
</configuration>

This article was brought to you by the elmah.io team. elmah.io is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening and help you fix errors fast.

Monitor your website



Comments