Search code examples
azureevent-logazure-diagnostics

WindowsEventLogs not logged on Azure


I have an Azure WebRole with the following code:

public override bool OnStart()
{
    setDiagnostics();

    TestClass test = new TestClass();

    return base.OnStart(); 
}

private void setDiagnostics()
{
    string wadConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";
    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(wadConnectionString));

    DeploymentDiagnosticManager deploymentDiagnosticManager = new DeploymentDiagnosticManager(cloudStorageAccount, RoleEnvironment.DeploymentId);
    RoleInstanceDiagnosticManager roleInstanceDiagnosticManager = cloudStorageAccount.CreateRoleInstanceDiagnosticManager(
        RoleEnvironment.DeploymentId,
        RoleEnvironment.CurrentRoleInstance.Role.Name,
        RoleEnvironment.CurrentRoleInstance.Id);

    DiagnosticMonitorConfiguration diagConfig = roleInstanceDiagnosticManager.GetCurrentConfiguration();

    if (diagConfig == null)
        diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

    diagConfig.WindowsEventLog.DataSources.Add("Application!*");
    diagConfig.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1D);

    roleInstanceDiagnosticManager.SetCurrentConfiguration(diagConfig);

    DiagnosticMonitor.Start(wadConnectionString, diagConfig);
}

In the constructor of my TestClass is the following code:

EventLog.WriteEntry("TestClass", "Before the try", EventLogEntryType.Information);
try
{
    EventLog.WriteEntry("TestClass", "In the try", EventLogEntryType.Information);
    Int32.Parse("abc");
}
catch (Exception ex)
{
    EventLog.WriteEntry("TestClass", ex.Message, EventLogEntryType.Error);
}

For some reason this code works well if I run it in debug mode with a break point on the OnStart method and running through the code with F11. However, I do not see any EventLog entries in my WADWindowsEventLogsTable if I remove all breakpoints and just run it. So this seems like a timing issue to me... Does anyone know why my code is performing this behaivor?

Thanks in advance!


Solution

  • The problem was the EventLog.WriteEntry() method. I used the source "TestClass" as EventLog source. However I never created this source with a startup task and due to insufficient privileges it failed to log my entries.

    So the solution: create an own source with a startup task or use trace messages.