Preparing for Application and Service Deployment-Debugging and Troubleshooting Windows Azure Applic

http://msdn.microsoft.com/en-us/library/ff966484.aspx

This appendix describes some of the technique specific to Windows Azure™ technology platform applications that will help you to detect and resolve issues when building, deploying, and running Windows Azure applications. It contains the following topics:

  • "Dependencies for Azure Applications and Projects"
  • "Debugging Azure Applications Locally During Development"
  • "Common Setup and Deployment Errors with Windows Azure"
  • "Using IntelliTrace with Applications Deployed to Windows Azure"
  • "Using Windows Azure Diagnostics"
  • "Resolving Permission Issues in Partial Trust Mode"
  • "More Information"

Dependencies for Azure Applications and Projects

To ensure that your Windows Azure projects will build and deploy correctly, ensure that you have the most recent versions of the Windows Azure tools installed and configured. Full integration with Windows Azure is available in Microsoft® Visual Studio® 2008 development system and Visual Studio 2010. If you want to use Microsoft IntelliTrace™ software to help debug your applications, you must install Visual Studio 2010 Ultimate Edition. IntelliTrace is described in the section, "Using IntelliTrace with Applications Deployed to Windows Azure," later in this appendix.  

You must also install the Visual Studio Tools for Windows Azure and the Windows Azure SDK. For more information about the requirements for building Windows Azure applications, see "Windows Azure Platform" on MSDN® (http://msdn.microsoft.com/en-gb/azure/default.aspx). This page also contains a section, "Interop SDKs and Tools," that provides links to tools for platforms other than the Microsoft Windows® operating system and tools other than Visual Studio.

Debugging Azure Applications Locally During Development

When working in Visual Studio, the techniques used to debug a Windows Azure application are generally identical to those for non-Azure applications. In addition, you can use the IntelliTrace feature in Visual Studio 2010 Ultimate Edition to output trace and debugging information from an application deployed to Windows Azure. IntelliTrace is described in the section, "Using IntelliTrace with Applications Deployed to Windows Azure," later in this appendix.

One point to be aware of when you are debugging applications locally is that you should not use the Debug.WriteLine orConsole.WriteLine methods to output debugging information or trace messages. Instead, use Trace.Write statements (or other methods of the Trace class) to write to the Diagnostic Monitor type (DiagnosticMonitorTraceListener) that Visual Studio automatically adds to your configuration file for each role. The following XML shows the section of the configuration file that adds the Diagnostic Monitor Trace Listener.

XML
<configuration>
  <system.diagnostics>
    <trace>
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics
                  .DiagnosticMonitorTraceListener,
                  Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0,
                  Culture=neutral, PublicKeyToken=31bf3856ad364e35"
             name="AzureDiagnostics">
          <filter type="" />
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
  ...

Common Setup and Deployment Errors with Windows Azure

The following are some of the common errors that you may encounter when running an application deployed to Windows Azure:

  • Failing to set Internet Information Services (IIS) to load the user profile if the application will use the Data Protection Application Programming Interface (DPAPI). To resolve this, open Internet Information Services (IIS) Manager, click Application Pools in the left pane, and then click the ASP.NET v4.0 application pool in the list of application pools. Click Advanced Settings in the Actions pane, and then change the value of the Load User Profile setting in the Profiles section to True.
  • Failing to enable the HTTP Redirection modules in IIS. MVC 2 and ASP.NET 4 Web Forms applications that use URLs without an extension (such as a URL ending in an action name) might return an HTTP 404 error (see Knowledge Base article 2023146 athttp://support.microsoft.com/?kbid=2023146). To resolve this, open Programs and Features in Control Panel, and then click Turn Windows Features On or Off. Expand the Internet Information Services node, expand World Wide Web Services, and then expand Common HTTP Features. Ensure that HTTP Error Redirection option is selected, and then allow the corresponding feature to be installed.
  • Omitting a required assembly or other type of resource from your deployment because you did not set the Copy Local property for the assembly or resource. This will be reported as a FileNotFoundException.
  • Using an incorrect Windows Azure storage connection string. This will show up in the method calls that use the connection string.
  • Attempting to use a native code library that you forgot to deploy, or using a 32-bit .NET code library, will usually throw aBadImageException.
  • Attempting to perform a task in your code for which it does not have permission. This will usually throw anUnauthorizedAccessException. For information about the permissions available in a Windows Azure application, see the section, "Resolving Permission Issues in Partial Trust Mode," later in this appendix.
  • Using a SQL Server connection string that points to the local SQL Server® or SQL Server Express instance. This will be shown asanHttpException with the error message, "Unable to connect to SQL Server database."
  • Using HTTP endpoints or the default local storage account in a diagnostics connection string for a deployed account. This will throwanArgumentException.
  • Attempting to read from a queue or table that is not created or initialized.
  • Using a certificate that does not have an exported private key. If you use Windows Certificate Manager to create a certificate, you must set the option to export the private key when you export the certificate.
  • Including a return statement or code in a worker role that terminates execution of the role. Windows Azure will attempt to restart the role.

You can detect many of the deployment errors using IntelliTrace, as described in the next section, "Using IntelliTrace with Applications Deployed to Windows Azure."

Using IntelliTrace with Applications Deployed to Windows Azure

IntelliTrace is a feature in Visual Studio 2010 Ultimate Edition that makes debugging code easier by showing events that occurred in your application as it ran, and the context in which they occurred. It maintains a list of breakpoints hit by your code and the full run-time context of the application at each one. You can review the complete state of the application at each breakpoint to determine where issues arise. You can configure the events that are recorded for each breakpoint; also, you can switch on collection of additional data, such as the parameter values and return values of methods that were called by the code.

IntelliTrace is a useful tool when debugging applications locally, but it is also useful for discovering errors in applications that you deploy to Windows Azure. For example, if a deployed application fails to execute, you can use IntelliTrace to provide information about the cause of the failure. When you use IntelliSense with a deployed Windows Azure application, it automatically collects information about the parameter values and return values of methods that were called by the code.

To use IntelliTrace in a deployed Windows Azure application

  1. After you finish creating and testing your application within the local development fabric, right-click the Windows Azure service node in Solution Explorer, and then click Publish.
  2. In the Publish Cloud Service dialog box, enter the deployment information required to deploy your application to Windows Azure.
  3. At the bottom of the Publish Cloud Service dialog box, select the Enable IntelliTrace for .NET 4 roles check box, and then click OKto publish your application.
  4. After deployment is complete and the application is executing, open Server Explorer and expand the Windows Azure Compute node to show a list of attached services.
  5. If the service you have deployed is not shown in the list, right-click the Windows Azure Compute node, point to Add Slot, and then click New. Enter the credentials to connect to the service.
  6. In the list of services under the Windows Azure Compute node, you will see the word IntelliTrace in brackets after the service name and deployment state for services that have IntelliTrace enabled. Expand the enabled service node to show a list of roles and expand the role you want to view to show the role instances. The icon for the instance indicates if it is executing, paused, or stopped.
  7. Right-click a role instance in a service that has IntelliTrace enabled, and then click View IntelliTrace Logs to start downloading the data. After the download completes, the IntelliTrace data opens in a Visual Studio window.
  8. To examine details of the IntelliTrace data, select an exception on the Exception Data page, and then click Start Debugging or double-click a thread in the list. This opens the IntelliTrace window where you can browse and filter, and view the call stack.
  9. To step through your local code using the downloaded IntelliTrace data, open the code, right-click a code line, and then click Search For This Line In IntelliTrace. Select a role instance from the list that displays. You can then step through the code and view the values of variables, the call stack, and other useful debugging information.
Ff966484.note(en-us,PandP.10).gifNote:
You should enable IntelliTrace only while debugging an application or role. When IntelliTrace is enabled, the application and roles will not automatically restart after a failure. This allows Windows Azure to persist the IntelliTrace data about the failure. You must manually restart the application or role.

For more information about using IntelliTrace, see "Debugging with IntelliTrace" on MSDN (http://msdn.microsoft.com/en-us/library/dd264915.aspx).

Using Windows Azure Diagnostics

Windows Azure provides integrated features for monitoring, logging, and tracing within the deployed environment; generally referred to asdiagnostics. These features are most suited to monitoring performance of applications over time, though they can also be used for debugging purposes as well.

Typically, you will use the monitoring features for tasks such as performance and resource usage measurement over time, capacity planning, traffic analysis, billing, and auditing. However, you can also use the capability to create trace messages and log entries, and to access log files and performance counters to perform debugging tasks after the application is deployed to Windows Azure.

About Windows Azure Diagnostics

Windows Azure provides the following diagnostic features:

  • A logging trace listener that allows you to write Event Tracing for Windows (ETW), trace, and debug information that you can upload into table storage and access from there. During development, when running locally, the trace information is accessible within the development fabric user interface.
  • A monitoring agent that allows you to upload the contents of event logs, IIS logs, crash dumps, and the output from performance counters to BLOB storage and then access it from there. You can determine the appropriate number of instances of each type of data.
  • Remote configuration for logging and monitoring that allows you to issue commands from the desktop that cause data to be uploaded to table storage or BLOB storage for specified services and roles. Data can also be automatically uploaded to table storage or BLOB storage on a predefined schedule.

Figure 1 shows an overview of the processes within the Windows Azure diagnostics features. A Windows Azure role can specify configuration information for the Diagnostics Monitor and start monitoring (step 1 in the diagram). The Diagnostics Monitor collects trace and debugging messages generated by the role (2). If the Diagnostics Monitor configuration specifies the collection of data from Windows data sources such as Event logs, performance counters, or IIS logs, this data is also collected (3).

Ff966484.50c7cd46-601e-4864-820c-54d49275ddb3-thumb(en-us,PandP.10).png

Figure 1

Overview of Windows diagnostics operation

The trace, counter, and log data collected from all sources is stored in the local directory storage (4). The maximum total storage size is 4 gigabytes(GB), but you can enforce quotas for each type of information. The stored data is then transferred to the appropriate type of Windows Azure storage (BLOB storage for data from event sources, and table storage for trace and debugging output), either through a scheduled uploaded or by issuing a command to upload specific sets of the data (5). The data can then be accessed using Windows Azure tools from a remote desktop (6).

Ff966484.note(en-us,PandP.10).gifNote:
Future updates for Windows Azure monitoring will include a dashboard that makes it easy to aggregate monitoring data collected on an hourly, daily, and weekly basis, and integration with Microsoft System Center to allow remote monitoring of applications as part of an enterprise monitoring strategy.

The following table shows the default setting of the Diagnostics Monitor for each type of diagnostics data source, the ways that you initially configure it for each type of data source, and the type of storage to which the data for each type of source is uploaded.

Data source

Default configuration

How to configure

Storage

Trace logs

Enabled, stored locally

Diagnostics API, trace listener

Table

Performance counters

Disabled

Diagnostics API

Table

Windows Event logs *

Disabled

Diagnostics API

Table

Infrastructure logs

Enabled, stored locally

Diagnostics API

Table

IIS logs

Enabled, stored locally

Diagnostics API, Web.config

BLOB

IIS Failed Request logs

Disabled

Diagnostics API, Web.config

BLOB

Application crash dumps

Disabled

Diagnostics API, Crash API

BLOB

Arbitrary logs and files

Disabled

Diagnostics API

BLOB

* You cannot access the Windows Security Event log to extract events because the Windows Azure run-time account does not have permission to access this log.

You can configure a data retention policy for each type of data source, including the quota and removal of aged data. The data stored in table storage is partitioned by the high-order bits of the tick count, so queries that select data based on a time range are efficient.

Ff966484.note(en-us,PandP.10).gifNote:
The IIS Failed Request Log includes requests that are not completed within a specific interval, as well as requests that fail for other reasons. However, collecting this information incurs considerable performance overhead and can only be enabled or disabled by uploading a configuration update for the service.

You can also use the Diagnostics Monitor with some application logging frameworks to generate trace and debugging information. For example, you can use it with the Enterprise Library Logging Application Block. The Logging Application Block makes it easy to centralize logging by providing an easy to use and highly configurable mechanism to generating log entries. By configuring theMicrosoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener class as a trace listener within the configuration of the Logging Application Block, you can use the Enterprise Library LogWriter and TraceManager objects to generate log trace messages within the local directory storage that you then upload into table storage. The aExpense application that is part of the patterns & practices Windows Azure Guidance project uses this approach.

Limitations of Windows Azure Diagnostics

Although the Windows Azure diagnostics mechanism provides comprehensive information, it is not an ideal solution for debugging and troubleshooting applications during development and deployment. The main issue is the effort required to enable and disable tracing and debugging features, and the delay until the resulting data is available.

To change the configuration of the Diagnostics Monitor, you must upload a new configuration and wait for the application to read and enable this configurationTo change the tracing and debugging code, you must redeploy the application to Windows Azure and wait until the service upgrade process completes before data becomes available. In addition, the delays in obtaining data mean that long-term performance counter polling rates of less than approximately 15 minutes are not practical, which reduces the capability to easily detect run-time issues.

In addition, when a service fails completely, it will generally remove all locally buffered data, including any monitoring and trace information that has not yet been transferred to table or BLOB storage.

However, the diagnostics features are useful for troubleshooting after a failure within a role, because you can download a wide range of information and study it to ascertain the circumstances of the failure and the likely contributing causes.

Using a Custom Tracing, and Debugging Agent

To resolve the two main issues encountered when debugging a deployed application, you can use a custom agent to collect the monitoring, debugging, and trace information and send it back immediately to a client application running on your local computer, or you can write it directly to BLOB or table storage—instead of holding it in the local directory buffer and then transferring it to BLOB or table storage. This helps to overcome the delay encountered while uploading data to storage, and it means that data in the local buffer is not lost if the application fails completely.

An example of a custom monitoring agent is included in the samples provided with the Windows Azure platform AppFabric SDK. Version 1.0 (April 2010) of the Windows Azure platform AppFabric SDK is available from the Microsoft Download Center (http://www.microsoft.com/downloads/details.aspx?FamilyID=39856a03-1490-4283-908f-c8bf0bfad8a5&displaylang=en). The sample named CloudTrace (in the ServiceBus\Scenarios subfolder) implements a class named CloudTraceListener that extends TraceListener to send trace events over the service bus to a remote client using one-way multicast events. The project also contains a client console that listens for and displays these events in real time.

You can use this sample as it is, or you can modify it to suit your own requirements. For example, you might adapt it to write the trace messages into table storage in your storage account and then monitor items in this storage account using a remote tool running on your local computer.

Ff966484.note(en-us,PandP.10).gifNote:
You should use debugging tools such as those described here only while testing and debugging your deployed application. The overhead incurred by diagnostics, especially when the sample rate is high or there is a large number of trace messages, is generally not acceptable for a production application.

Tools for Working with Windows Azure Diagnostics

There is a growing set of tools available that allow you to view the remote diagnostics information in table storage and BLOB storage, configure diagnostics, and manage Windows Azure services. Within Visual Studio, you can use the Server Manager user interface to view and interact with deployed services. Other tools are Windows Azure Storage Explorer (see http://azurestorageexplorer.codeplex.com/), Windows Azure Web Storage Explorer (see http://storageexplorer.codeplex.com/), and the Windows Azure Management Tool (MMC) athttp://code.msdn.microsoft.com/windowsazuremmc.

There is also a set of PowerShell cmdlets (single-function command-line tools) that allow you to manage diagnostics on a remote server. You can use them to script deployments, manage upgrades, and configure scaling of a Windows Azure application in addition to managing the diagnostics configuration. For more information, see "Windows Azure Service Management CmdLets" in the MSDN Code Gallery (http://code.msdn.microsoft.com/azurecmdlets).

As an example of the capabilities of the remote tools, Figure 2 shows the Diagnostics section of the Windows Azure Management Tool (MMC). You can use this section to change the configuration of the Windows Azure Diagnostics Monitor for a deployed service, to schedule uploads of the data to Windows Azure storage, and to perform on-demand data transfers to storage. It also provides features for downloading and analyzing the diagnostic data held in BLOB and table storage. You can even create your own custom extensions for the tool to implement other data analysis options.

Ff966484.0c104ec8-1405-4f2b-b1c6-502539322ac0-thumb(en-us,PandP.10).png

Figure 2 

Windows Azure Management Tool (MMC) Diagnostics section

Configuring Diagnostics Using Configuration Files

When you create a Windows Azure project in Visual Studio, it automatically adds the Diagnostic Monitor type (DiagnosticMonitorTraceListener) to your configuration file for each role.

XML
<configuration>
  <system.diagnostics>
    <trace>
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics
                  .DiagnosticMonitorTraceListener,
                  Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0,
                  Culture=neutral, PublicKeyToken=31bf3856ad364e35"
             name="AzureDiagnostics">
          <filter type="" />
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
  ...

The default configuration settings in the ServiceConfiguration.cscfg file also specify the location of the storage account to use for trace and monitoring data. During development and local debugging, you can use the default value UseDevelopmentStorage=true, as shown here.

XML
<ServiceConfiguration serviceName="MyService" xmlns="...">
  <Role name="MyRole">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="DiagnosticsConnectionString"
               value="UseDevelopmentStorage=true" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

To specify a cloud storage account in your configuration file, use the following syntax.

XML
<Setting name="DiagnosticsConnectionString" 
  value="DefaultEndpointsProtocol=https;AccountName=...;AccountKey=..." />

You can also use the configuration files to specify additional shared listeners and set the levels at which they will report diagnostics information. When you upload a new configuration for a role to an Azure application, it detects the configuration change and (by default) restarts the role. However, you can vary this default behavior by editing the code in the RoleEnvironment.Changing andRoleEnvironment.Changed event handlers. For more information, see "Handling Configuration Changes" at on MSDN (http://msdn.microsoft.com/en-us/library/ee848064.aspx).

Using the Diagnostics API in a Windows Azure Application

In addition to being able to configure diagnostics for a deployed application using a configuration file and the tools described in the previous sections of this guidance, you can also access the diagnostics API using code within your application to configure and start diagnostic monitoring and write debugging and trace information. In your code, you can accomplish the following tasks:

  • Specify any changes required from the default configuration of the Diagnostics Monitor.
  • Optionally configure scheduled uploads of the diagnostic data to table or BLOB storage.
  • Start the Diagnostics Monitor.
  • Generate the any debugging and trace messages you require. These will be output to the local buffer ready for upload to storage, along with any other data sources that you enable.
Configuring Diagnostics Using the API

This section briefly describes the options available for configuring the Diagnostics Monitor using code. The basic approach is to obtain a reference to the initial default configuration for the Diagnostics Monitor and change it as required. Typically, you will locate this code in theOnStart method of your role. After you configure your monitoring requirements, you must call the Start method of the Diagnostics Monitor, as shown in the section, "Activating Monitoring," later in this appendix.

An instance of the DiagnosticMonitorConfiguration class holds the configuration information for a Diagnostics Monitor, exposing it through a series of properties such as DiagnosticInfrastructureLogsDirectoriesLogsPerformanceCounters, and WindowsEventLog. The DirectoriesPerformanceCounters, and WindowsEventLog properties expose a DataSources collection that specifies the items to monitor. Each data source you add can be configured using properties specific to the type and common properties that set the buffer quota and transfer interval.

The following example updates the initial default configuration by setting the polling interval (the interval at which the Diagnostics Monitor will check for configuration changes which is, by default, every minute), and the buffer quota for diagnostic logs. Then it adds to the configuration a performance counter and two Windows Event logs.

C#
// Obtain a reference to the initial default configuration.
DiagnosticMonitorConfiguration config 
    = DiagnosticMonitor.GetDefaultInitialConfiguration();

// Change the polling interval and buffer quota for logs. 
config.ConfigurationChangePollInterval = TimeSpan.FromSeconds(30.0);
config.DiagnosticInfrastructureLogs.BufferQuotaInMB = 256;

// Set the transfer interval for all logs. 
config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

// Configure monitoring of a Windows performance counter
// and add it to the configuration.
PerformanceCounterConfiguration perfConfig 
    = new PerformanceCounterConfiguration();
perfConfig.CounterSpecifier = @"\Processor(*)\% Processor Time";
perfConfig.SampleRate = TimeSpan.FromSeconds(15.0);
config.PerformanceCounters.DataSources.Add(perfConfig);

// Configure monitoring of Windows Application and System Event logs,
// including the quota and scheduled transfer interval, and add them 
// to the configuration.
WindowsEventLogsBufferConfiguration eventsConfig 
    = new WindowsEventLogsBufferConfiguration();
eventsConfig.BufferQuotaInMB = 256;
eventsConfig.ScheduledTransferLogLevelFilter = LogLevel.Warning;
eventsConfig.ScheduledTransferPeriod = TimeSpan.FromMinutes(10.0);
eventsConfig.DataSources.Add("Application!*");
eventsConfig.DataSources.Add("System!*");
config.WindowsEventLog = eventsConfig;
// Now remember to start the diagnostics monitor with this configuration.
// For more information, see the section "Activating Monitoring."

For more information about the settings available for the DiagnosticMonitorConfiguration class, see "DiagnosticMonitorConfiguration Members" on MSDN (http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.diagnostics.diagnosticmonitorconfiguration_members.aspx).

To obtain a list of counter names, execute the command TypePerf/q in a Command window.

When adding a Windows Event log to the configuration, you specify it using an XPath statement of the form channel!xpath-query. In the preceding example, Application!* specifies the Windows Application event log. For more information about XPath expressions that identify events, see "Consuming Events" on MSDN (http://msdn.microsoft.com/en-us/library/dd996910(VS.85).aspx).

If you want to capture the contents of a crash dump, you call one of the methods of the CrashDumps class once before starting monitoring. The simplest overload takes a Boolean parameter that specifies if you want the full dump (true) or a mini-dump (false).

C#
CrashDumps.EnableCollection(false);

You can optionally specify the directory to store the crash dump using the overload that takes a string containing the full absolute path to the required directory.

Ff966484.note(en-us,PandP.10).gifNote:
Web role requests that encounter an error and cause the role to fail are usually caught by ASP.NET, which prevents crash dump generation.

Activating Monitoring

This section briefly describes how you activate monitoring using the diagnostics API. The Start method of the DiagnosticMonitor class starts the Diagnostic Monitor using a configuration that you specify. The Shutdown method stops the Diagnostic Monitor. The following code starts the Diagnostic Monitor using the configuration instance created in the previous section.

C#
// Start the Diagnostics Monitor. 
DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

The first parameter is the name of a setting in the ServiceConfiguration.cscfg file that specifies the storage location for uploaded diagnostics data.

Alternatively, you can create an instance of the CloudStorageAccount class, set the properties (such as the storage endpoints and credentials), and then pass this as the first parameter of the Start method. If you do not specify a configuration instance when you call theStart method, the Diagnostics Monitor will use the default configuration. Ensure that you use the correct connection string, because an incorrect string may cause monitoring to fail without causing a run-time error.

Avoid calling the Start method of the Diagnostic Monitor more than once. Changes you make to the configuration are automatically detected at intervals determined by the value of the ConfigurationChangePollInterval property.

Generating Diagnostics Data Within the Application

This section briefly describes how you can write information to the Diagnostics Monitor using the diagnostics API. Typically, you would add code to generate trace messages containing debugging information at any point in the code for your role where you need to generate information to assist in debugging or monitoring the application.

The following line writes a warning message to the Diagnostics Monitor to indicate that monitoring has been configured and started.

C#
// Write a trace message to the Diagnostic Monitor.
string roleInstance = RoleEnvironment.CurrentRoleInstance.Id; 
System.Diagnostics.Trace.TraceWarning("Diagnostics configured and started "
                                      + "for role instance: " + roleInstance);

You can use the other methods of the System.Diagnostics.Trace class to write information in the exact format you require. For more information about these methods and the other members of the class, see "Trace Members" on MSDN (http://msdn.microsoft.com/en-us/library/system.diagnostics.trace_members.aspx).

In addition to generating debugging and trace log entries, one typical requirement for generating diagnostic data within an application is to support data sources that are not directly available in the Windows Azure diagnostics framework. An example of this is Windows Management Instrumentation (WMI) events, which are not available through the diagnostics API. Instead, you may consider capturing WMI events in your code and then generating log entries for an arbitrary log. You configure arbitrary logs using the DataSources collection of the Logs property of the configuration instance.

Transferring Diagnostics Data to Storage

This section briefly describes how you can transfer diagnostics data from the local buffer to table and BLOB storage using the diagnostics API. If you have configured scheduled upload transfers using the diagnostics configuration API or a remote tool, you do not need to perform any additional tasks.However, you can execute an on-demand upload of the monitoring data in the local directory buffer to BLOB and table storage, irrespective of whether you have configured scheduled uploads.

When you initiate a transfer of data to storage, consider filtering it on the verbosity to minimize storage requirements and transaction costs. For example, transfer only warning and critical event data.

The following code example shows a method that you can call to initiate an on-demand transfer of diagnostics data to storage. It contains hard-coded specifications of values, such as the target storage account and the transfer options. However, you can adapt the method code to accept any of the values as parameters if you want to create a more generic version.

The first stage is to create a Deployment Diagnostic Manager for the target storage account. You can specify the account using the name and key or as a connection string in your ServiceConfiguration.cscfg file.

C#
public Guid StartOnDemandTransfer()
{
  // Create a CloudStorageAccount for a specified name and key.
  StorageCredentialsAccountAndKey accountAndKey 
      = new StorageCredentialsAccountAndKey("account-name", "account-key");
  CloudStorageAccount storageAccount 
      = new CloudStorageAccount(accountAndKey, false);

  // Specify the deployment ID of the target storage account.
  string deploymentId = "target-storage-account-deployment-id";

  // Create a Deployment Diagnostic Manager for this target storage account.
  DeploymentDiagnosticManager ddm 
      = new DeploymentDiagnosticManager(storageAccount, deploymentId);
  ...

Alternatively, you can use the name of a storage account connection setting defined in the ServiceConfiguration.cscfg file.

C#
  ...
  DeploymentDiagnosticManager ddm 
      = new DeploymentDiagnosticManager("StorageAccountConnectionString",
                                         deploymentId);
  ...

For more information about the Deployment Diagnostic Manager, see "DeploymentDiagnosticManager Members" on MSDN (http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.diagnostics.management.deploymentdiagnosticmanager_members.aspx).

Next, you create a Role Instance Diagnostic Manager for the role containing the diagnostics data you want to transfer. This example assumes you want to transfer data from the current role in which the code is executing. You can, if required, specify the ID and name of a different role.

C#
  ...
  string roleId = RoleEnvironment.CurrentRoleInstance.Id;
  string roleName = RoleEnvironment.CurrentRoleInstance.Role.Name;
  RoleInstanceDiagnosticManager rdm 
      = ddm.GetRoleInstanceDiagnosticManager(roleName, roleId);
  ...

Another approach is to iterate through the roles and instances in your application using the methods of the Role Instance Diagnostic Manager. The following shows two examples of iterating through all the available instances for all roles in order to demonstrate some of the methods available to you.

C#
  // Alternative approaches for accessing roles and instances.
  foreach (string roleName in ddm.GetRoleNames())
  {
    foreach (string instanceID in ddm.GetRoleInstanceIdsForRole(roleName))
    {
      RoleInstanceDiagnosticManager rdm 
          = ddm.GetRoleInstanceDiagnosticManager(roleName, instanceID);
      // Use the Role Instance Diagnostic Manager here ...
    }
  }

  foreach (string roleName in ddm.GetRoleNames())
  {
    IEnumerable<RoleInstanceDiagnosticManager> rdmList 
        = ddm.GetRoleInstanceDiagnosticManagersForRole(roleName);
    foreach (RoleInstanceDiagnosticManager rdm in rdmList)
    {
      // Use the Role Instance Diagnostic Manager here ...
    }
  }

After you obtain a Role Instance Diagnostic Manager, you specify the options for the transfer of the diagnostics data from the buffer to storage using an instance of the OnDemandTransferOptions class, as shown here.

C#
  ...
  // Create a configuration options instance for the transfer
  // and set the required property values.
  OnDemandTransferOptions options = new OnDemandTransferOptions();
  options.NotificationQueueName = "transfer-queue-name";
  options.From = new DateTime(2010, 6, 10, 12, 0, 0);
  options.To = DateTime.UtcNow;
  options.LogLevelFilter = LogLevel.Critical;
  ...

The NotificationQueueName is the name of a queue to which the Role Instance Diagnostic Manager will send a notification that the transfer has completed. If you are not interested in receiving a notification, you can ignore this property.

Finally, you start the transfer by calling the BeginOnDemandTransfer method of the Role Instance Diagnostic Manager, specifying the type of data source for which you want to transfer data and the options instance you created. The method returns a GUID that identifies the notification message that will be sent to the queue you specified as the value of the NotificationQueueName property.

C#
  ...
  // Start the transfer and return the GUID that identifies it. 
  return rdm.BeginOnDemandTransfer(DataBufferName.WindowsEventLogs, options);
}

Other methods of the Role Instance Diagnostic Manager allow you to cancel a specific transfer, cancel all transfers, iterate over the list of active transfers, and modify the configuration settings for the transfer. For more information, see "RoleInstanceDiagnosticManager Members" on MSDN (http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.diagnostics.management.roleinstancediagnosticmanager_members.aspx).

Resolving Permission Issues in Partial Trust Mode

By default, code within all Windows Azure application roles runs in full-trust mode that grants your application permissions to perform operations such as invoking non-.NET code, using .NET Framework libraries that require full trust or inter-process communication using named pipes. However, even in full-trust mode, Windows Azure applications cannot perform some operations, such as modifying the registry or writing to the system directory.

You can configure code within Windows Azure application roles to run in partial-trust mode that is approximately equivalent to ASP.NET medium-trust level. This means that some operations your code may execute, such as attempting to use sockets for network access, will cause a run-time error because of insufficient permissions. For a full list of permission settings, see "Windows Azure Partial Trust Policy Reference" on MSDN (http://msdn.microsoft.com/en-us/library/dd573355(v=MSDN.10).aspx).

To enable partial-trust mode, add the enableNativeCodeExecution="false" attribute to the role configuration in the Service Definition file, as shown here.

XML
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="MyService"
   xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
  <WebRole name="MyWebRole" enableNativeCodeExecution="false">
    <InputEndpoints>
      ...
    </InputEndpoints>
  </WebRole>
  ...
</ServiceDefinition>

You can also enable partial-trust mode through the configuration of the role in your cloud project.

More Information

For more information about debugging and troubleshooting Windows Azure applications, see the following resources:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值