您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 Visual Studio 对 Azure 应用服务中的 Web 应用进行故障排除Troubleshoot a web app in Azure App Service using Visual Studio


本教程介绍如何使用 Visual Studio 工具,通过远程运行调试模式或查看应用程序日志和 Web 服务器日志帮助调试应用服务中的 Web 应用。This tutorial shows how to use Visual Studio tools to help debug a web app in App Service, by running in debug mode remotely or by viewing application logs and web server logs.


尽管本文中指的是 Web 应用,但内容同样适用于 API 应用和移动应用。Although this article refers to web apps, it also applies to API apps and mobile apps.

学习内容:You'll learn:

  • Visual Studio 中提供的 Azure Web 应用管理功能。Which Azure web app management functions are available in Visual Studio.
  • 如何使用 Visual Studio 远程视图在远程 Web 应用中进行快速更改。How to use Visual Studio remote view to make quick changes in a remote web app.
  • 项目在 Azure 中运行时,如何对 Web 应用和 WebJob 远程运行调试模式。How to run debug mode remotely while a project is running in Azure, both for a web app and for a WebJob.
  • 如何创建应用程序跟踪日志并在该应用程序创建日志时对其进行查看。How to create application trace logs and view them while the application is creating them.
  • 如何查看 Web 服务器日志,包括详细的错误消息和失败请求跟踪。How to view web server logs, including detailed error messages and failed request tracing.
  • 如何将诊断日志发送至 Azure 存储帐户并在其中进行查看。How to send diagnostic logs to an Azure Storage account and view them there.

如果有 Visual Studio Ultimate,还可以使用 IntelliTrace 进行调试。If you have Visual Studio Ultimate, you can also use IntelliTrace for debugging. 本教程未介绍 IntelliTrace。IntelliTrace is not covered in this tutorial.


本教程适用于在 Azure 和 ASP.NET 入门中设置的开发环境、Web 项目和 Azure Web 应用。This tutorial works with the development environment, web project, and Azure web app that you set up in Get started with Azure and ASP.NET. 对于 WebJobs 部分,需要用到在 Azure WebJobs SDK 入门中创建的应用程序。For the WebJobs sections, you'll need the application that you create in Get Started with the Azure WebJobs SDK.

在本教程中所示的代码示例适用于 C# MVC Web 应用程序,但对于 Visual Basic 和 Web 窗体应用程序,故障排除过程是一样的。The code samples shown in this tutorial are for a C# MVC web application, but the troubleshooting procedures are the same for Visual Basic and Web Forms applications.

本教程假设使用 Visual Studio 2017。The tutorial assumes you're using Visual Studio 2017.

流式日志功能仅适用于面向 .NET Framework 4 或更高版本的应用程序。The streaming logs feature only works for applications that target .NET Framework 4 or later.

Web 应用配置和管理Web app configuration and management

通过 Visual Studio,用户可以访问 Azure 门户中提供的 Web 应用管理功能和配置设置的子集。Visual Studio provides access to a subset of the web app management functions and configuration settings available in the Azure portal. 本节介绍使用“服务器资源管理器”可以实现的功能。In this section, you'll see what's available by using Server Explorer. 若要了解最新的 Azure 集成功能,请同时试用云资源管理器To see the latest Azure integration features, try out Cloud Explorer also. 可以从“视图”菜单打开这两个窗口。You can open both windows from the View menu.

  1. 如果还没有登录 Visual Studio 中的 Azure ,右键单击“Azure”,然后选择连接到“服务器资源管理器”中的“Microsoft Azure 订阅”。If you aren't already signed in to Azure in Visual Studio, right-click Azure and select Connect to Microsoft Azure Subscription in Server Explorer.

    另一种方法是安装可以访问帐户的管理证书。An alternative is to install a management certificate that enables access to your account. 如果选择安装证书,请右键单击“服务器资源管理器”中的“Azure”,然后选择上下文菜单中的“管理和筛选订阅”。If you choose to install a certificate, right-click the Azure node in Server Explorer, and then select Manage and Filter Subscriptions in the context menu. 在“管理 Microsoft Azure 订阅”对话框中,单击“证书”选项卡,然后单击“导入”。In the Manage Microsoft Azure Subscriptions dialog box, click the Certificates tab, and then click Import. 按照说明为 Azure 帐户下载并导入一个订阅文件(也称为 .publishsettings 文件)。Follow the directions to download and then import a subscription file (also called a .publishsettings file) for your Azure account.


    将此订阅文件下载并保存到源代码目录之外的文件夹中(例如,在 Downloads 文件夹中),然后在导入完成后将其删除。If you download a subscription file, save it to a folder outside your source code directories (for example, in the Downloads folder), and then delete it once the import has completed. 获得此订阅文件访问权的恶意用户可以编辑、创建和删除 Azure 服务。A malicious user who gains access to the subscription file can edit, create, and delete your Azure services.

    有关从 Visual Studio 连接至 Azure 资源的详细信息,请参阅管理帐户、订阅和管理角色For more information about connecting to Azure resources from Visual Studio, see Manage Accounts, Subscriptions, and Administrative Roles.

  2. 在“服务资源管理器”中,展开“Azure”,并展开“应用服务”。In Server Explorer, expand Azure and expand App Service.
  3. 展开包含在在 Azure 中创建 ASP.NET Web 应用中创建的 Web 应用的资源组,右键单击该 Web 应用节点,并单击“查看设置”。Expand the resource group that includes the web app that you created in Create an ASP.NET web app in Azure, and then right-click the web app node and click View Settings.


    此时会显示“Azure Web 应用”选项卡,可在此处查看 Visual Studio 中提供的 Web 应用管理和配置任务。The Azure Web App tab appears, and you can see there the web app management and configuration tasks that are available in Visual Studio.

    “Azure Web 应用”窗口

    本教程介绍如何使用日志记录和跟踪下拉列表。In this tutorial, you'll use the logging and tracing drop-downs. 其中,还将用到远程调试,但会通过不同方式启用该调试。You'll also use remote debugging but you'll use a different method to enable it.

    有关该窗口中“应用程序设置”和“连接字符串”框的信息,请参阅 Azure Web 应用:应用程序字符串和连接字符串的工作原理For information about the App Settings and Connection Strings boxes in this window, see Azure Web Apps: How Application Strings and Connection Strings Work.

    如果要执行的 Web 应用管理任务无法在此窗口进行,请单击“在管理门户中打开”,以便在浏览器窗口中打开 Azure 门户。If you want to perform a web app management task that can't be done in this window, click Open in Management Portal to open a browser window to the Azure portal.

在服务器资源管理器中访问 Web 应用文件Access web app files in Server Explorer

部署 Web 项目时,Web.config 文件中的 customErrors 标志通常设置为 OnRemoteOnly,这意味着如果出现问题你不会收到任何有帮助的错误消息。You typically deploy a web project with the customErrors flag in the Web.config file set to On or RemoteOnly, which means you don't get a helpful error message when something goes wrong. 无论发生何种错误,获得的都是类似如下所示的页面:For many errors, all you get is a page like one of the following ones:

'/' 应用程序中出现服务器错误:Server Error in '/' Application:


发生错误:An error occurred:


网站无法显示页面The website cannot display the page


找出错误原因的最简捷方法通常是启用详细错误消息,之前保留的屏幕截图中的第一个截图会告诉你如何做。Frequently the easiest way to find the cause of the error is to enable detailed error messages, which the first of the preceding screenshots explains how to do. 而实现此目的需要在部署的 Web.config 文件中进行更改。That requires a change in the deployed Web.config file. 可以编辑项目中的 Web.config 文件,并重新部署该项目,或创建 Web.config 转换并部署调试版本,但还有一个更快捷的方式:在“解决方案资源管理器”中,可以通过使用远程视图功能直接查看并编辑远程 Web 应用上的文件。You could edit the Web.config file in the project and redeploy the project, or create a Web.config transform and deploy a debug build, but there's a quicker way: in Solution Explorer, you can directly view and edit files in the remote web app by using the remote view feature.

  1. 在“服务器资源管理器”中,依次展开“Azure”、“应用服务”、Web 应用所在的资源组以及 Web 应用的节点。In Server Explorer, expand Azure, expand App Service, expand the resource group that your web app is located in, and then expand the node for your web app.

    会看到允许访问 Web 应用的内容文件和日志文件的节点。You see nodes that give you access to the web app's content files and log files.

  2. 展开“文件”节点,并双击 Web.config 文件。Expand the Files node, and double-click the Web.config file.

    打开 Web.config

    Visual Studio 将从远程 Web 应用打开 Web.config 文件,并在标题栏中的文件名旁显示 [远程]。Visual Studio opens the Web.config file from the remote web app and shows [Remote] next to the file name in the title bar.

  3. 将以下行添加到 system.web 元素:Add the following line to the system.web element:

    <customErrors mode="Off"></customErrors>

    编辑 Web.config

  4. 刷新显示无用错误消息的浏览器,现在会获得详细的错误消息,如下所示:Refresh the browser that is showing the unhelpful error message, and now you get a detailed error message, such as the following example:


    (通过以红色显示的行添加到 Views\Home\Index.cshtml 创建显示的错误。)(The error shown was created by adding the line shown in red to Views\Home\Index.cshtml.)

编辑 Web.config 文件示例演示了能够读取并编辑 Azure Web 应用上的文件使得故障排除变得更加简单,而这仅仅只是其中之一。Editing the Web.config file is only one example of scenarios in which the ability to read and edit files on your Azure web app make troubleshooting easier.

远程调试 Web 应用Remote debugging web apps

如果详细的错误消息提供的信息量不够,且无法本地重新创建该错误,则可以采用远程运行调试模式进行故障排除.If the detailed error message doesn't provide enough information, and you can't re-create the error locally, another way to troubleshoot is to run in debug mode remotely. 可以设置断点、直接操作内存、逐行执行代码,甚至更改代码路径。You can set breakpoints, manipulate memory directly, step through code, and even change the code path.

远程调试不适用于 Visual Studio Express 版。Remote debugging does not work in Express editions of Visual Studio.

本部分介绍如何使用在在 Azure 中创建 ASP.NET Web 应用中创建的项目进行远程调试。This section shows how to debug remotely using the project you create in Create an ASP.NET web app in Azure.

  1. 打开在在 Azure 中创建 ASP.NET Web 应用中创建的 Web 项目。Open the web project that you created in Create an ASP.NET web app in Azure.

  2. 打开 Controllers\HomeController.csOpen Controllers\HomeController.cs.

  3. 删除 About() 方法并在其位置插入以下代码。Delete the About() method and insert the following code in its place.

public ActionResult About()
    string currentTime = DateTime.Now.ToLongTimeString();
    ViewBag.Message = "The current time is " + currentTime;
    return View();
  1. ViewBag.Message 行上设置一个断点Set a breakpoint on the ViewBag.Message line.

  2. 在“解决方案资源管理器”中,右键单击该项目并单击“发布”。In Solution Explorer, right-click the project, and click Publish.

  3. 在“配置文件”下拉列表中,选择在在 Azure 中创建 ASP.NET Web 应用中使用的相同配置文件。In the Profile drop-down list, select the same profile that you used in Create an ASP.NET web app in Azure. 然后,单击“设置”。Then, click Settings.

  4. 在“发布”对话框中,单击“设置”选项卡,将“配置”更改为“调试”,然后单击“保存”。In the Publish dialog, click the Settings tab, and then change Configuration to Debug, and then click Save.


  5. 单击“发布” 。Click Publish. 部署结束后,浏览器将打开 Web 应用的 Azure URL,关闭浏览器。After deployment finishes and your browser opens to the Azure URL of your web app, close the browser.

  6. 在“服务器资源管理器”中,右键单击该 Web 应用,并单击“附加调试器”。In Server Explorer, right-click your web app, and then click Attach Debugger.


    浏览器会自动打开运行在 Azure 中的主页。The browser automatically opens to your home page running in Azure. 可能需要等待大约 20 秒,以便 Azure 针对调试设置服务器。You might have to wait 20 seconds or so while Azure sets up the server for debugging. 此延迟只在 48 小时内首次于 Web 应用上运行调试模式时出现。This delay only happens the first time you run in debug mode on a web app in a 48-hour period. 如果在同一时段再次开始调试,不会发生延迟。When you start debugging again in the same period, there isn't a delay.


    如果启动调试器时出现问题,请尝试使用“云资源管理器”而不是“服务器资源管理器”执行此操作。If you have any trouble starting the debugger, try to do it by using Cloud Explorer instead of Server Explorer.

  7. 单击菜单中的“关于”。Click About in the menu.

    Visual Studio 会在断点处停止,代码在 Azure 中运行,而不是在本地计算机上。Visual Studio stops on the breakpoint, and the code is running in Azure, not on your local computer.

  8. 将鼠标悬停在 currentTime 变量上查看时间值。Hover over the currentTime variable to see the time value.

    在运行于 Azure 中的调试模式下查看变量

    看到的时间是 Azure 服务器时间,可能与本地计算机所处时区不同。The time you see is the Azure server time, which may be in a different time zone than your local computer.

  9. currentTime 变量输入一个新值,如“Now running in Azure”。Enter a new value for the currentTime variable, such as "Now running in Azure".

  10. 按 F5 继续运行。Press F5 to continue running.

    运行于 Azure 中的“关于”页面会显示在 currentTime 变量中输入的新值。The About page running in Azure displays the new value that you entered into the currentTime variable.


远程调试 WebJobsRemote debugging WebJobs

本部分说明如何使用在 Azure WebJobs SDK 入门中创建的项目和 Web 应用进行远程调试。This section shows how to debug remotely using the project and web app you create in Get Started with the Azure WebJobs SDK.

本部分所示的功能只能在 Visual Studio 2013 Update 4 或更高版本中使用。The features shown in this section are available only in Visual Studio 2013 with Update 4 or later.

远程调试仅适用于连续 WebJobs。Remote debugging only works with continuous WebJobs. 计划的和按需 WebJobs 不支持调试。Scheduled and on-demand WebJobs don't support debugging.

  1. 打开在 Azure WebJobs SDK 入门中创建的 Web 项目。Open the web project that you created in Get Started with the Azure WebJobs SDK.

  2. 在 ContosoAdsWebJob 项目中,打开 Functions.csIn the ContosoAdsWebJob project, open Functions.cs.

  3. GnerateThumbnail 方法的第一个语句中设置一个断点Set a breakpoint on the first statement in the GnerateThumbnail method.


  4. 在“解决方案资源管理器”中,右键单击该 Web 项目(而非 WebJob 项目),并单击“发布”。In Solution Explorer, right-click the web project (not the WebJob project), and click Publish.

  5. 在“配置文件”下拉列表中,选择与 Azure WebJobs SDK 入门中所用相同的配置文件。In the Profile drop-down list, select the same profile that you used in Get Started with the Azure WebJobs SDK.

  6. 单击“设置”选项卡,将“配置”更改为“调试”,然后单击“发布”。Click the Settings tab, and change Configuration to Debug, and then click Publish.

    Visual Studio 将部署 Web 和 WebJob 项目,浏览器将打开 Web 应用的 Azure URL。Visual Studio deploys the web and WebJob projects, and your browser opens to the Azure URL of your web app.

  7. 在“服务器资源管理器”中,展开“Azure”>“应用服务”> 资源组 > Web 应用 >“WebJobs”>“连续”,然后右键单击“ContosoAdsWebJob”。In Server Explorer, expand Azure > App Service > your resource group > your web app > WebJobs > Continuous, and then right-click ContosoAdsWebJob.

  8. 单击“附加调试器”。Click Attach Debugger.


    浏览器会自动打开运行在 Azure 中的主页。The browser automatically opens to your home page running in Azure. 可能需要等待大约 20 秒,以便 Azure 针对调试设置服务器。You might have to wait 20 seconds or so while Azure sets up the server for debugging. 此延迟只在 48 小时内首次于 Web 应用上运行调试模式时出现。This delay only happens the first time you run in debug mode on a web app in a 48-hour period. 如果在同一时段再次开始调试,不会发生延迟。When you start debugging again in the same period, there isn't a delay.

  9. 在打开 Contoso 广告主页的 Web 浏览器中,创建新的广告。In the web browser that is opened to the Contoso Ads home page, create a new ad.

    创建广告会导致创建队列消息,WebJob 拾取并处理该消息。Creating an ad causes a queue message to be created, which is picked up by the WebJob and processed. 当 WebJobs SDK 调用函数处理该队列消息时,代码命中断点。When the WebJobs SDK calls the function to process the queue message, the code hits your breakpoint.

  10. 当调试器在断点处中断时,可以在程序运行云的同时,检查并更改变量值。When the debugger breaks at your breakpoint, you can examine and change variable values while the program is running the cloud. 在下图中,调试器显示了传递给 GenerateThumbnail 方法的 blobInfo 对象的内容。In the following illustration, the debugger shows the contents of the blobInfo object that was passed to the GenerateThumbnail method.

    调试器中的 blobInfo 对象

  11. 按 F5 继续运行。Press F5 to continue running.

    GenerateThumbnail 方法将完成创建缩略图。The GenerateThumbnail method finishes creating the thumbnail.

  12. 在浏览器中刷新“索引”页,会看到缩略图。In the browser, refresh the Index page and you see the thumbnail.

  13. 在 Visual Studio 中,按 SHIFT+F5 停止调试。In Visual Studio, press SHIFT+F5 to stop debugging.

  14. 在“服务器资源管理器”中,右键单击 ContosoAdsWebJob 节点,并单击“查看仪表板”。In Server Explorer, right-click the ContosoAdsWebJob node and click View Dashboard.

  15. 使用 Azure 凭据登录,并单击 WebJob 名称转到 WebJob 的页面。Sign in with your Azure credentials, and then click the WebJob name to go to the page for your WebJob.

    单击 ContosoAdsWebJob

    仪表板会显示最近执行的 GenerateThumbnail 函数。The Dashboard shows that the GenerateThumbnail function executed recently.

    (下次单击“查看仪表板”时无需登录,浏览器会直接转到 WebJob 的页面。)(The next time you click View Dashboard, you don't have to sign in, and the browser goes directly to the page for your WebJob.)

  16. 单击函数名称可查看有关函数执行的详细信息。Click the function name to see details about the function execution.


如果将函数写入了日志,可以单击“ToggleOutput”查看日志。If your function wrote logs, you could click ToggleOutput to see them.

有关远程调试的说明Notes about remote debugging

  • 不建议在生产环境中以调试模式运行。Running in debug mode in production is not recommended. 如果生产 Web 应用未进行扩展以容纳多个服务器实例,则调试会阻止 Web 服务器响应其他请求。If your production web app is not scaled out to multiple server instances, debugging prevents the web server from responding to other requests. 如果具有多个 Web 服务器实例,在附加至调试程序时会获得一个随机实例,但无法确保后续浏览器请求将前往相同的实例。If you do have multiple web server instances, when you attach to the debugger, you get a random instance, and you have no way to ensure that subsequent browser requests go to the same instance. 此外,调试版本一般不会部署到生产环境,针对版本生成的编译器优化可以逐行显示源代码中出现的情况。Also, you typically don't deploy a debug build to production, and compiler optimizations for release builds might make it impossible to show what is happening line by line in your source code. 至于如何解决生产环境中出现的问题,可利用的最佳资源是应用程序跟踪和 Web 服务器日志。For troubleshooting production problems, your best resource is application tracing and web server logs.
  • 远程调试时避免长时间停止在断点处。Avoid long stops at breakpoints when remote debugging. Azure 会将停止时间超过几分钟的进程视为无反应进程而将其关闭。Azure treats a process that is stopped for longer than a few minutes as an unresponsive process, and shuts it down.
  • 进行调试的时候,服务器会向 Visual Studio 发送数据,这可能会影响到带宽费用。While you're debugging, the server is sending data to Visual Studio, which could affect bandwidth charges. 有关带宽费率的信息,请参阅 Azure 定价For information about bandwidth rates, see Azure Pricing.
  • 请确保 Web.config 文件中 compilation 元素的 debug 属性设置为 true。Make sure that the debug attribute of the compilation element in the Web.config file is set to true. 在发布调试版本配置时,默认设置为 true。It is set to true by default when you publish a debug build configuration.
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  • 如果发现调试程序没有针对希望调试的代码展开行动,可能需要更改“仅我的代码”设置。If you find that the debugger doesn't step into the code that you want to debug, you might have to change the Just My Code setting. 有关详细信息,请参阅指定是否仅使用 Visual Studio 中的“仅我的代码”调试用户代码For more information, see Specify whether to debug only user code using Just My Code in Visual Studio.
  • 启用远程调试功能时,服务器上会出现一个计时器,48 小时后该功能会自动关闭。A timer starts on the server when you enable the remote debugging feature, and after 48 hours the feature is automatically turned off. 这一 48 小时的限制是出于安全性与性能的考虑。This 48-hour limit is done for security and performance reasons. 可以根据需要轻松地多次重启该功能。You can easily turn the feature back on as many times as you like. 我们建议,在不主动进行调试的时候,保持其处于禁用状态。We recommend leaving it disabled when you are not actively debugging.
  • 可以手动将调试器附加到任何进程,而不仅仅是 Web 应用进程 (w3wp.exe)。You can manually attach the debugger to any process, not only the web app process (w3wp.exe). 有关如何在 Visual Studio 中使用调试模式的信息,请参阅在 Visual Studio 中进行调试For more information about how to use debug mode in Visual Studio, see Debugging in Visual Studio.

诊断日志概述Diagnostic logs overview

运行在 Azure Web 应用中的 ASP.NET 应用程序可以创建以下几类日志:An ASP.NET application that runs in an Azure web app can create the following kinds of logs:

  • 应用程序跟踪日志Application tracing logs
    应用程序通过调用 System.Diagnostics.Trace 类的方法创建这些日志。The application creates these logs by calling methods of the System.Diagnostics.Trace class.
  • Web 服务器日志Web server logs
    Web 服务器为每一个 Web 应用的 HTTP 请求创建一个日志条目。The web server creates a log entry for every HTTP request to the web app.
  • 详细错误消息日志Detailed error message logs
    Web 服务器为失败的 HTTP 请求(导致状态代码 400 或更大数字的请求)创建带有一些额外信息的 HTML 页面。The web server creates an HTML page with some additional information for failed HTTP requests (requests that result in status code 400 or greater).
  • 失败请求跟踪日志Failed request tracing logs
    Web 服务器为失败的 HTTP 请求创建带有详细跟踪信息的 XML 文件。The web server creates an XML file with detailed tracing information for failed HTTP requests. Web 服务器还可提供 XSL 文件以格式化浏览器中的 XML。The web server also provides an XSL file to format the XML in a browser.

日志记录会影响 Web 应用性能,因此 Azure 允许提供根据需要启用或禁用各种类型的日志。Logging affects web app performance, so Azure gives you the ability to enable or disable each type of log as needed. 对于应用程序日志,可以指定只写入特定严重级别以上的日志。For application logs, you can specify that only logs above a certain severity level should be written. 创建新的 Web 应用时,默认为禁用所有日志记录功能。When you create a new web app, by default all logging is disabled.

日志将写入 Web 应用文件系统中 LogFiles 文件夹内的文件,并可通过 FTP 访问。Logs are written to files in a LogFiles folder in the file system of your web app and are accessible via FTP. Web 服务器日志和应用程序日志也可写入 Azure 存储帐户。Web server logs and application logs can also be written to an Azure Storage account. 可在存储帐户中为日志留出大于文件系统预留量的空间。You can retain a greater volume of logs in a storage account than is possible in the file system. 使用文件系统时,最多可存储 100 兆字节的日志。You're limited to a maximum of 100 megabytes of logs when you use the file system. (文件系统日志仅适合短期保留。(File system logs are only for short-term retention. 达到限制后,Azure 将删除旧日志文件以便为新日志腾出空间。)Azure deletes old log files to make room for new ones after the limit is reached.)

创建并查看应用程序跟踪日志Create and view application trace logs

在本部分中执行以下任务:In this section, you do the following tasks:

  • 将跟踪语句添加到在 Azure 和 ASP.NET 入门中创建的 Web 项目。Add tracing statements to the web project that you created in Get started with Azure and ASP.NET.
  • 本地运行该项目时查看日志。View the logs when you run the project locally.
  • 查看由运行于 Azure 中的应用程序生成的日志。View the logs as they are generated by the application running in Azure.

有关如何在 WebJobs 中创建应用程序日志的信息,请参阅如何使用 WebJobs SDK 处理 Azure 队列存储 - 如何写入日志For information about how to create application logs in WebJobs, see How to work with Azure queue storage using the WebJobs SDK - How to write logs. 以下有关查看日志以及控制其在 Azure 中的存储方式的说明,同样适用于 WebJobs 创建的应用程序日志。The following instructions for viewing logs and controlling how they're stored in Azure apply also to application logs created by WebJobs.

向应用程序添加跟踪语句Add tracing statements to the application

  1. 打开 Controllers\HomeController.cs 并将 IndexAboutContact 方法替换为以下代码,以便为 System.Diagnostics 添加 Trace 语句和 using 语句:Open Controllers\HomeController.cs, and replace the Index, About, and Contact methods with the following code in order to add Trace statements and a using statement for System.Diagnostics:
public ActionResult Index()
    Trace.WriteLine("Entering Index method");
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
    Trace.TraceInformation("Displaying the Index page at " + DateTime.Now.ToLongTimeString());
    Trace.WriteLine("Leaving Index method");
    return View();

public ActionResult About()
    Trace.WriteLine("Entering About method");
    ViewBag.Message = "Your app description page.";
    Trace.TraceWarning("Transient error on the About page at " + DateTime.Now.ToShortTimeString());
    Trace.WriteLine("Leaving About method");
    return View();

public ActionResult Contact()
    Trace.WriteLine("Entering Contact method");
    ViewBag.Message = "Your contact page.";
    Trace.TraceError("Fatal error on the Contact page at " + DateTime.Now.ToLongTimeString());
    Trace.WriteLine("Leaving Contact method");
    return View();
  1. using System.Diagnostics; 语句添加到文件顶部。Add a using System.Diagnostics; statement to the top of the file.

本地查看跟踪输出View the tracing output locally

  1. 按 F5 以调试模式运行应用程序。Press F5 to run the application in debug mode.

    默认跟踪侦听器将所有跟踪输出写入“输出”窗口,同时还有其他调试输出。The default trace listener writes all trace output to the Output window, along with other Debug output. 下图显示了来自添加到 Index 方法的跟踪语句的输出。The following illustration shows the output from the trace statements that you added to the Index method.


    以下步骤介绍如何在网页中查看跟踪输出而无需在调试模式下进行编译。The following steps show how to view trace output in a web page, without compiling in debug mode.

  2. 打开应用程序 Web.config 文件(位于项目文件夹中),将 <system.diagnostics> 元素添加到文件末尾的关闭 </configuration> 元素之前:Open the application Web.config file (the one located in the project folder) and add a <system.diagnostics> element at the end of the file just before the closing </configuration> element:
    <add name="WebPageTraceListener"
        PublicKeyToken=b03f5f7f11d50a3a" />

WebPageTraceListener 允许通过浏览至 /trace.axd 查看跟踪输出。The WebPageTraceListener lets you view trace output by browsing to /trace.axd.

  1. 跟踪元素添加到 Web.config file 文件中的 <system.web> 下面,如下所示:Add a trace element under <system.web> in the Web.config file, such as the following example:
<trace enabled="true" writeToDiagnosticsTrace="true" mostRecent="true" pageOutput="false" />
  1. 按 Ctrl+F5 运行应用程序。Press CTRL+F5 to run the application.
  2. 在浏览器窗口的地址栏中,将 trace.axd 添加到 URL,然后按 Enter(URL 类似于 http://localhost:53370/trace.axd))。In the address bar of the browser window, add trace.axd to the URL, and then press Enter (the URL is similar to http://localhost:53370/trace.axd).
  3. 在“应用程序跟踪”页面上,单击第一行中(非浏览器链接中)的“查看详细信息”。On the Application Trace page, click View Details on the first line (not the BrowserLink line).


    “请求细节”页面显示,在“跟踪信息”部分会看到添加到 Index 方法的跟踪语句的输出。The Request Details page appears, and in the Trace Information section you see the output from the trace statements that you added to the Index method.


    默认情况下,trace.axd 仅供本地使用。By default, trace.axd is only available locally. 如果希望可以从远程 Web 应用使用,可将 localOnly="false" 添加到 trace 元素(位于 Web.config 文件中),如下所示:If you wanted to make it available from a remote web app, you could add localOnly="false" to the trace element in the Web.config file, as shown in the following example:

     <trace enabled="true" writeToDiagnosticsTrace="true" localOnly="false" mostRecent="true" pageOutput="false" />

    但是,出于安全考虑,不推荐在生产 web 应用中启用 trace.axdHowever, enabling trace.axd in a production web app is not recommended for security reasons. 以下部分将介绍在 Azure web 应用中读取跟踪日志的更简单方法。In the following sections, you'll see an easier way to read tracing logs in an Azure web app.

在 Azure 中查看跟踪输出View the tracing output in Azure

  1. 在“解决方案资源管理器”中,右键单击该 Web 项目,并单击“发布”。In Solution Explorer, right-click the web project and click Publish.
  2. 在“发布 Web”对话框中,单击“发布”。In the Publish Web dialog box, click Publish.

    在 Visual Studio 发布更新后,将打开一个主页的浏览器窗口(假设没有清除“连接”选项卡上的“目标 URL”)。After Visual Studio publishes your update, it opens a browser window to your home page (assuming you didn't clear Destination URL on the Connection tab).

  3. 在“服务器资源管理器”中,右键单击 Web 应用,并选择“查看流式传输日志”。In Server Explorer, right-click your web app and select View Streaming Logs.


    “输出”窗口显示已连接至日志流式传输服务,每过一分钟没有要显示的日志,就添加一个通知行。The Output window shows that you are connected to the log-streaming service, and adds a notification line each minute that goes by without a log to display.


  4. 在显示应用程序主页的浏览器窗口,单击“联系人”。In the browser window that shows your application home page, click Contact.

    几秒钟内,添加到 Contact 方法的错误级跟踪的输出显示在“输出”窗口中。Within a few seconds, the output from the error-level trace you added to the Contact method appears in the Output window.


    Visual Studio 仅显示错误级跟踪,因为这是启用日志监视服务时的默认设置。Visual Studio is only showing error-level traces because that is the default setting when you enable the log monitoring service. 创建新的 Azure Web 应用时,默认禁用所有日志记录,正如之前打开设置页面时所见:When you create a new Azure web app, all logging is disabled by default, as you saw when you opened the settings page earlier:


    然而,如果选择“查看流式传输日志”,Visual Studio 会自动将“应用程序日志记录(文件系统)”更改为“错误”,这意味着将报告错误级日志。However, when you selected View Streaming Logs, Visual Studio automatically changed Application Logging(File System) to Error, which means error-level logs get reported. 为了查看所有跟踪日志,可将该设置更改为“详细”。In order to see all of your tracing logs, you can change this setting to Verbose. 如果选择的严重级别低于错误,也将报告所有更高严重级别的日志。When you select a severity level lower than error, all logs for higher severity levels are also reported. 因此,如果选择“详细”,还可查看信息、警告以及错误日志。So when you select verbose, you also see information, warning, and error logs.

  5. 在“服务器资源管理器”中,右键单击 Web 应用,并如之前所做单击“查看设置”。In Server Explorer, right-click the web app, and then click View Settings as you did earlier.

  6. 将“应用程序日志记录(文件系统)”更改为“详细”,然后单击“保存”。Change Application Logging (File System) to Verbose, and then click Save.


  7. 现在,在显示“联系人”页面的浏览器窗口中,单击“主页”,并依次单击“关于”和“联系人”。In the browser window that is now showing your Contact page, click Home, then click About, and then click Contact.

    几秒钟内,“输出”窗口会显示所有跟踪输出。Within a few seconds, the Output window shows all of your tracing output.


    在本节中,已通过使用 Azure Web 应用设置启用和禁用日志记录。In this section, you enabled and disabled logging by using Azure web app settings. 此外,还可以通过修改 Web.config 文件启用和禁用跟踪侦听器。You can also enable and disable trace listeners by modifying the Web.config file. 然而,修改 Web.config 文件会导致应用域回收,而通过 Web 应用配置启用日志记录则不会出此情况。However, modifying the Web.config file causes the app domain to recycle, while enabling logging via the web app configuration doesn't do that. 如果问题重现需要花费较长时间或呈间歇性,回收应用域可能会“修复”该问题并强迫你一直等到其再次出现。If the problem takes a long time to reproduce, or is intermittent, recycling the app domain might "fix" it and force you to wait until it happens again. 通过启用 Azure 中的诊断,可以立即开始捕获错误信息,并且不需要回收应用域。Enabling diagnostics in Azure lets you start capturing error information immediately without recycling the app domain.

输出窗口特性Output window features

“输出”窗口的“Microsoft Azure 日志”选项卡上有若干按钮和一个文本框:The Microsoft Azure Logs tab of the Output Window has several buttons and a text box:


这些控件执行以下功能:These perform the following functions:

  • 清理“输出”窗口。Clear the Output window.
  • 启用或禁用自动换行。Enable or disable word wrap.
  • 启动或停止监视日志。Start or stop monitoring logs.
  • 指定要监视的日志。Specify which logs to monitor.
  • 下载日志。Download logs.
  • 基于搜索字符串或正则表达式筛选日志。Filter logs based on a search string or a regular expression.
  • 关闭“输出”窗口。Close the Output window.

如果输入搜索字符串或正则表达式,Visual Studio 会在客户端筛选日志记录信息。If you enter a search string or regular expression, Visual Studio filters logging information at the client. 这意味着可以在日志显示在“输出”窗口后输入条件,并可更改筛选条件而不必重新生成日志。That means you can enter the criteria after the logs are displayed in the Output window and you can change filtering criteria without having to regenerate the logs.

查看 Web 服务器日志View web server logs

Web 服务器日志将记录 Web 应用上所有的 HTTP 活动。Web server logs record all HTTP activity for the web app. 若要在“输出”窗口中查看这些日志,必须为 Web 应用启用日志并告知 Visual Studio 希望对其进行监视。In order to see them in the Output window, you must enable them for the web app and tell Visual Studio that you want to monitor them.

  1. 在通过“服务器资源管理器”打开的“Azure Web 应用配置”选项卡上,将“Web 服务器日志记录”的状态更改为“开启”,然后单击“保存”。In the Azure Web App Configuration tab that you opened from Server Explorer, change Web Server Logging to On, and then click Save.

    启用 Web 服务器日志记录

  2. 在“输出”窗口中,单击“指定要监视的 Microsoft Azure 日志”按钮。In the Output Window, click the Specify which Microsoft Azure logs to monitor button.

    指定要监视的 Azure 日志。

  3. 在“Microsoft Azure 日志记录选项”对话框中,选择“Web 服务器日志”,然后单击“确定”。In the Microsoft Azure Logging Options dialog box, select Web server logs, and then click OK.

    监视 Web 服务器日志

  4. 在显示 Web 应用的浏览器窗口中,依次单击“主页”、“关于”、“联系人”。In the browser window that shows the web app, click Home, then click About, and then click Contact.

    应用程序日志通常第一个显示,其后是 Web 服务器日志。The application logs generally appear first, followed by the web server logs. 可能需要等待一段时间日志才会显示。You might have to wait a while for the logs to appear.

    输出窗口中的 Web 服务器日志

默认情况下,通过使用 Visual Studio 第一次启用 Web 服务器日志时,Azure 会将日志写入文件系统。By default, when you first enable web server logs by using Visual Studio, Azure writes the logs to the file system. 或者,可以使用 Azure 门户指定将 Web 服务器日志写入存储帐户的 Blob 容器。As an alternative, you can use the Azure portal to specify that web server logs should be written to a blob container in a storage account.

如果使用门户将 Web 服务器日志记录写入 Azure 存储帐户,之后在 Visual Studio 中禁用日志记录,则在 Visual Studio 中重新启用日志记录时,存储帐户设置将还原。If you use the portal to enable web server logging to an Azure storage account, and then disable logging in Visual Studio, when you re-enable logging in Visual Studio your storage account settings are restored.

查看详细的错误消息日志View detailed error message logs

详细的错误日志提供了有关导致错误响应代码(400 或更大)的 HTTP 请求的一些额外信息。Detailed error logs provide some additional information about HTTP requests that result in error response codes (400 or above). 若要在“输出”窗口中查看这些日志,必须为 Web 应用启用日志并告知 Visual Studio 希望对其进行监视。In order to see them in the Output window, you have to enable them for the web app and tell Visual Studio that you want to monitor them.

  1. 在通过“服务器资源管理器”打开的“Azure Web 应用配置”选项卡上,将“详细的错误消息”的状态更改为“开启”,然后单击“保存”。In the Azure Web App Configuration tab that you opened from Server Explorer, change Detailed Error Messages to On, and then click Save.


  2. 在“输出”窗口中,单击“指定要监视的 Microsoft Azure 日志”按钮。In the Output Window, click the Specify which Microsoft Azure logs to monitor button.

  3. 在“Microsoft Azure 日志记录选项”对话框中,单击“所有日志”,然后单击“确定”。In the Microsoft Azure Logging Options dialog box, click All logs, and then click OK.


  4. 在浏览器的地址栏中,向 URL 添加一个额外字符以导致 404 错误(例如 http://localhost:53370/Home/Contactx),并按 Enter。In the address bar of the browser window, add an extra character to the URL to cause a 404 error (for example, http://localhost:53370/Home/Contactx), and press Enter.

    几秒后,详细的错误日志显示在 Visual Studio 的“输出”窗口中。After several seconds, the detailed error log appears in the Visual Studio Output window.

    详细的错误日志 - 输出窗口

    Control + 单击该链接可在浏览器中看到排好格式的日志输出。Control+click the link to see the log output formatted in a browser:

    详细的错误日志 - 浏览器窗口

下载文件系统日志Download file system logs

任何可在“输出”窗口中监视的日志都可作为 .zip 文件进行下载。Any logs that you can monitor in the Output window can also be downloaded as a .zip file.

  1. 在“输出”窗口中单击“下载流式传输日志”。In the Output window, click Download Streaming Logs.


    “文件资源管理器”打开,其中显示 Downloads 文件夹中已下载文件处于选定状态。File Explorer opens to your Downloads folder with the downloaded file selected.


  2. 提取该 .zip 文件,会看到以下文件夹结构:Extract the .zip file, and you see the following folder structure:


    • 应用程序跟踪日志位于 LogFiles\Application 文件夹的 .txt 文件中。Application tracing logs are in .txt files in the LogFiles\Application folder.
    • Web 服务器日志位于 LogFiles\http\RawLogs 文件夹的 .log 文件中。Web server logs are in .log files in the LogFiles\http\RawLogs folder. 可以使用诸如 Log Parser 之类的工具查看并处理这些文件。You can use a tool such as Log Parser to view and manipulate these files.
    • 详细的错误消息日志位于 LogFiles\DetailedErrors 文件夹的 .html 文件中。Detailed error message logs are in .html files in the LogFiles\DetailedErrors folder.

      deployments 文件夹内是由源代码管理发布创建的文件;其中没有任何有关 Visual Studio 发布的内容。(The deployments folder is for files created by source control publishing; it doesn't have anything related to Visual Studio publishing. Git 文件夹内是与源代码管理发布以及日志文件流式传输服务相关的跟踪。)The Git folder is for traces related to source control publishing and the log file streaming service.)

查看失败请求跟踪日志View failed request tracing logs

在出现诸如 URL 重写或身份验证问题之类的情况下,需要详细了解 IIS 如何处理 HTTP 请求时可求助于失败请求跟踪日志。Failed request tracing logs are useful when you need to understand the details of how IIS is handling an HTTP request, in scenarios such as URL rewriting or authentication problems.

Azure Web 应用使用 IIS 7.0 及更高版本中提供的相同失败请求跟踪功能。Azure web apps use the same failed request tracing functionality that has been available with IIS 7.0 and later. IIS 设置经过配置可记录指定错误,但无法访问该设置。You don't have access to the IIS settings that configure which errors get logged, however. 启用失败请求跟踪后,所有错误都将纳入捕获范围内。When you enable failed request tracing, all errors are captured.

使用 Visual Studio 可启用失败请求跟踪,但却无法在 Visual Studio 中对其进行查看。You can enable failed request tracing by using Visual Studio, but you can't view them in Visual Studio. 这些日志是 XML 文件。These logs are XML files. 这些流式传输日志服务只监视认为在纯文本模式下可读的文件:.txt.html.log 文件。The streaming log service only monitors files that are deemed readable in plain text mode: .txt, .html, and .log files.

可以通过 FTP 直接在浏览器中查看失败请求跟踪日志,或使用 FTP 工具将其下载到本地计算机后进行本地查看。You can view failed request tracing logs in a browser directly via FTP or locally after using an FTP tool to download them to your local computer. 在本节中,将直接在浏览器中查看这些日志。In this section, you'll view them in a browser directly.

  1. 在从“服务器资源管理器”打开的“Azure Web 应用”窗口的“配置”选项卡中,将“失败请求跟踪”的状态更改为“开启”,然后单击“保存”。In the Configuration tab of the Azure Web App window that you opened from Server Explorer, change Failed Request Tracing to On, and then click Save.


  2. 在显示该 Web 应用的浏览器窗口的地址栏中,向 URL 添加一个额外字符,单击 Enter 将引发 404 错误。In the address bar of the browser window that shows the web app, add an extra character to the URL and click Enter to cause a 404 error.

    这会导致创建失败请求跟踪日志,以下步骤介绍如何查看或下载该日志。This causes a failed request tracing log to be created, and the following steps show how to view or download the log.

  3. 在 Visual Studio 中,在“Azure Web 应用”窗口的“配置”选项卡中,单击“在管理门户中打开”。In Visual Studio, in the Configuration tab of the Azure Web App window, click Open in Management Portal.

  4. Azure 门户中 Web 应用的“设置”页面上,单击“部署凭据”,并输入新的用户名和密码。In the Azure portal Settings page for your web app, click Deployment credentials, and then enter a new user name and password.

    新建 FTP 用户名和密码


    登录时,必须使用以 Web 应用名称为前缀的完整用户名。When you log in, you have to use the full user name with the web app name prefixed to it. 例如,如果输入“myid”作为用户名,而站点为“myexample”,请使用“myexample\myid”登录。For example, if you enter "myid" as a user name and the site is "myexample", you log in as "myexample\myid".

  5. 在新的浏览器窗口中,转到显示在 Web 应用的“概述”页中“FTP 主机名”或“FTPS 主机名”下面的 URL。In a new browser window, go to the URL that is shown under FTP hostname or FTPS hostname in the Overview page for your web app.

  6. 使用之前创建的 FTP 凭据(包括作为用户名前缀的 Web 应用名称)登录。Log in using the FTP credentials that you created earlier (including the web app name prefix for the user name).

    浏览器会显示该 Web 应用的根文件夹。The browser shows the root folder of the web app.

  7. 打开 LogFiles 文件夹。Open the LogFiles folder.

    打开 LogFiles 文件夹

  8. 打开名为 W3SVC 加数值的文件夹。Open the folder that is named W3SVC plus a numeric value.

    打开 W3SVC 文件夹

    该文件夹包含启用失败请求跟踪之后记录在案的任何错误的 XML 文件,以及一个可供浏览器格式化 XML 的 XSL 文件。The folder contains XML files for any errors that have been logged after you enabled failed request tracing, and an XSL file that a browser can use to format the XML.

    W3SVC 文件夹

  9. 单击希望查看跟踪信息的失败请求的 XML 文件。Click the XML file for the failed request that you want to see tracing information for.

    下图显示了示例错误的部分跟踪信息。The following illustration shows part of the tracing information for a sample error.


后续步骤Next Steps

以上部分介绍了如何通过 Visual Studio 轻松查看由 Azure Web 应用创建的日志。You've seen how Visual Studio makes it easy to view logs created by an Azure web app. 以下部分提供了相关主题中其他资源的链接:The following sections provide links to more resources on related topics:

  • Azure Web 应用故障排除Azure web app troubleshooting
  • 在 Visual Studio 中进行调试Debugging in Visual Studio
  • 在 Azure 中进行远程调试Remote debugging in Azure
  • 在 ASP.NET 应用程序中进行跟踪Tracing in ASP.NET applications
  • 分析 Web 服务器日志Analyzing web server logs
  • 分析失败请求跟踪日志Analyzing failed request tracing logs
  • 调试云服务Debugging Cloud Services

Azure Web 应用故障排除Azure web app troubleshooting

有关对 Azure 应用服务中的 Web 应用进行故障排除的详细信息,请参阅以下资源:For more information about troubleshooting web apps in Azure App Service, see the following resources:

若要针对特定故障排除问题寻求帮助,可在以下论坛之一开启话题讨论:For help with a specific troubleshooting question, start a thread in one of the following forums:

在 Visual Studio 中进行调试Debugging in Visual Studio

有关如何在 Visual Studio 中使用调试模式的详细信息,请参阅在 Visual Studio 中进行调试使用 Visual Studio 2010 进行调试的提示For more information about how to use debug mode in Visual Studio, see Debugging in Visual Studio and Debugging Tips with Visual Studio 2010.

在 Azure 中进行远程调试Remote debugging in Azure

有关 Azure Web 应用和 WebJobs 远程调试的详细信息,请参阅以下资源:For more information about remote debugging for Azure web apps and WebJobs, see the following resources:

如果 Web 应用使用 Azure Web API 或移动服务后端且需要进行调试,请参阅在 Visual Studio 中调试 .NET 后端If your web app uses an Azure Web API or Mobile Services back-end and you need to debug that, see Debugging .NET Backend in Visual Studio.

在 ASP.NET 应用程序中进行跟踪Tracing in ASP.NET applications

Internet 上对于 ASP.NET 跟踪没有全面且最新的介绍。There are no thorough and up-to-date introductions to ASP.NET tracing available on the Internet. 最佳做法是以针对 Web 窗体编写的老旧介绍性材料为主(因为 MVC 彼时并不存在),以专注于特定问题的新兴博客文章为辅。The best you can do is get started with old introductory materials written for Web Forms because MVC didn't exist yet, and supplement that with newer blog posts that focus on specific issues. 以下资源可作为比较好的入门资源:Some good places to start are the following resources:

   // Your code that might cause an exception to be thrown.
catch (Exception ex)
    Trace.TraceError("Exception: " + ex.ToString());

对于错误日志记录,若不想编写自己的跟踪代码,可以使用开源日志记录框架,如 ELMAHFor error logging, an alternative to writing your own tracing code is to use an open-source logging framework such as ELMAH. 有关详细信息,请参阅 Scott Hanselman 有关 ELMAH 的博客文章For more information, see Scott Hanselman's blog posts about ELMAH.

并且,不需要使用 ASP.NET 或 System.Diagnostics 跟踪来获取来自 Azure 的流式处理日志。Also, you don't need to use ASP.NET or System.Diagnostics tracing to get streaming logs from Azure. 该 Azure web 应用流式处理日志服务对其在 LogFiles 文件夹中找到的所有 .txt、.html 或 .log 文件进行流式处理。The Azure web app streaming log service streams any .txt, .html, or .log file that it finds in the LogFiles folder. 因此,可以创建自己的日志记录系统,该系统写入 web 应用的文件系统,文件会自动进行流式处理和下载。Therefore, you could create your own logging system that writes to the file system of the web app, and your file is automatically streamed and downloaded. 所要做的就是编写在 d:\home\logfiles 文件夹中创建文件的应用程序代码。All you have to do is write application code that creates files in the d:\home\logfiles folder.

分析 Web 服务器日志Analyzing web server logs

有关分析 Web 服务器日志的详细信息,请参阅以下资源:For more information about analyzing web server logs, see the following resources:

分析失败请求跟踪日志Analyzing failed request tracing logs

Microsoft TechNet 网站包含使用失败请求跟踪部分,有助于你了解如何使用这些日志。The Microsoft TechNet website includes a Using Failed Request Tracing section, which may be helpful for understanding how to use these logs. 然而,该文档主要着重于在 IIS 中配置失败请求跟踪,并不适用于 Azure Web 应用。However, this documentation focuses mainly on configuring failed request tracing in IIS, which you can't do in Azure Web Apps.