【发布时间】:2020-04-03 09:54:36
【问题描述】:
问题是,当我从OctopusDeploy 下启动 Windows 服务时,如果服务无法启动 - 错误消息描述性不够。我正在使用 .net core 3.1 和 Microsoft.Extensions.Hosting.WindowsServices 包创建 Windows 服务。在本地很容易重现问题:
Start-Service MySvc
PowerShell 显示以下错误
Start-Service:由于以下错误,无法启动服务“MySvc (MySvc)”:无法在计算机“.”上启动服务 MySvc。在 line:1 char:1
Start-Service MySvc
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
如您所见,它缺少有关错误消息的任何信息。
构建器如下所示:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.DoCustomLogic();
services.AddHostedService<Mysvc>();
})
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder
.AddConsole(options => { options.IncludeScopes = true; })
.AddEventLog();
});
其实我很确定,方法DoCustomLogic()抛出了什么样的异常(为简单起见清理了实际代码):
public static void DoCustomLogic(this IServiceCollection services)
{
string exMsg = "my custom exception";
throw new Exception(exMsg);
}
此外,启动失败后 - 在Event Viewer 中有 2 条新记录:
.Net runtime 输出:
Application: MySvc.exe
CoreCLR Version: 4.700.19.60701
.NET Core Version: 3.1.1
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Exception: my custom exception
...
Exception Info: System.Exception: my custom exception
所以基本上,我是真正抛出异常的人,我确切地知道错误是什么。我的问题是——这是否可以将一些更有意义的信息输出到powershell 控制台中关于这种异常?
对于使用Octopus Deploy 的用户 - 日志中没有显示实际的错误消息是反直觉的,因此他们必须登录服务器并检查事件查看器日志。
我想一种可能的解决方案是创建一个可以检查事件的构建后脚本。但如果可能的话,我宁愿用 C# 来解决它。
【问题讨论】:
-
我不是专家,但
Start-Service只会检查服务是否启动成功并没有什么不合理的。服务背后可以有任何类型的进程,不仅仅是.net进程,所以我不明白为什么会有一种机制允许.net异常一直被抛出,将各种API 备份到启动服务的实体或进程。事件日志确实是此信息的正确位置。
标签: c# powershell windows-services .net-core-3.1