且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何调试(***在 IDE 中)MSBuild 脚本?

更新时间:2023-10-23 23:39:04

我使用 /v:diagnostic 命令行开关.MSBuild 会输出一些非常详细的输出.您还可以使用 /fl[n] 命令行开关将详细输出发送到日志文件而不是控制台,然后使用 /flp[n](filelogparameter) 开关以指定详细级别,例如 /flp:Verbosity=diagnostic;LogFile=latest_diagnostic.log

I use the /v:diagnostic command-line switch. MSBuild spits out some pretty verbose output. You can also spit the verbose output to a log file instead of the console, using the /fl[n] command line switch, and then use the /flp[n] (filelogparameter) switch to specify the verbosity level, e.g., /flp:Verbosity=diagnostic;LogFile=latest_diagnostic.log

您必须从一开始就设计构建脚本,以便更轻松地进行故障排除.执行以下操作:

You have to design your build scripts from the start to make troubleshooting easier. Do things like:

使每个目标尽可能细化,以便您可以单独调用每个目标.这有助于加快调试过程.

Make each target as granular as possible, so you can call each target individually. This helps make the debugging process much quicker.

确保您的任务继承自 Microsoft.Build.Utilities.Task 类.它公开了一个 Log 属性,该属性具有太多的日志记录功能.我通常会谨慎使用 LogMessage(MessageImportance,string,params object[]).我的调试消息获得了 MessageImportance.Low 的消息重要性,因此它们仅在详细模式为诊断时出现.

Make sure your tasks inherit from the Microsoft.Build.Utilities.Task class. It exposes a Log property that has way too many logging functions. I typically err on the side of caution use the LogMessage(MessageImportance,string,params object[]). My debugging messages get a message importance of MessageImportance.Low so they only appear when the verbosity mode is diagnostic.

使用 System.Diagnostics.Trace.WriteLine 输出级别太低而无法记录的消息.我使用 DebugView 来查看这些消息.

Use System.Diagnostics.Trace.WriteLine for outputting messages that are are too low-level to log. I use DebugView to look at those messages.

最后,尽量不要在 MSBuild 脚本本身中做非常复杂的事情.MSBuild 擅长管理依赖项、文件列表和运行任务.任何更复杂或更高级的东西都应该转移到用您选择的 .NET 语言编写的自定义任务中.这还有一个额外的好处,那就是让事情更加更容易调试.当您在代码中获得逻辑后,您可以使用 System.Diagnostics.Debugger.Launch() 方法,这将允许您将 MSBuild 附加到正在运行的 Visual Studio 实例中的调试器(希望一个已经加载了您的自定义任务的任务).

Lastly, try not to do really complicated things in the MSBuild script itself. MSBuild excels at managing dependencies, lists of files, and running tasks. Anything more complicated or advanced should be moved to custom tasks written in your .NET language of choice. This has the added benefit of making things much easier to debug. When you've got your logic in code, you can use System.Diagnostics.Debugger.Launch() method, which will allow you to attach MSBuild to the debugger in a running instance of Visual Studio (hopefully one that has your custom task already loaded).

祝你好运!