如何从失败的 Windows 服务中获取 .NET 异常消息和堆栈跟踪?

How to get the .NET exception message and stack trace from a failing Windows Service?

我已经用 C#/.NET 编写了一个 Windows 服务,但到目前为止它还没有启动。在其 OnStart 方法中抛出异常。

因为我没有在 Windows 事件日志中找到任何关于未处理异常的信息(除了不是很有用的 P4: System.Data),我正在寻找另一种简单的方法来获取堆栈跟踪和异常消息。

我知道,我可以尝试 debug the Windows Service but since it fails in the OnStart method which runs under a timeout,调试不好玩。此外,它需要以管理员身份启动 VS。

或者我应该将所有内容都包装在 try-catch 中并在某处记录异常?如果是这样,去哪里?最佳做法是什么?

将代码的所有关键部分包装在单独的 try/catch 块中,将日志写入 windows 事件日志,安装全局异常处理程序。将这些异常也写入 windows 事件日志。

你应该在一个服务中完成所有这些,即使它无论如何都不会崩溃。