Start-Service 没有 return 足够的失败信息

Start-Service does not return enough information about the failure

问题是,当我从 OctopusDeploy 下启动 Windows 服务时,如果服务启动失败 - 错误消息描述性不够。我正在使用 .net core 3.1Microsoft.Extensions.Hosting.WindowsServices 包来创建 windows 服务。很容易在本地重现该问题:

Start-Service MySvc

以下错误显示自 PowerShell

Start-Service : Service 'MySvc (MySvc)' cannot be started due to the following error: Cannot start service MySvc on computer '.'. At 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 的用户 - 日志中没有显示实际的错误消息是违反直觉的,因此他们必须登录到服务器并检查事件查看器日志。

我想一个可能的解决方案是创建一个 post-build 脚本来检查事件..但如果可能的话我宁愿用 C# 解决它..

很遗憾,我无法为您测试,但是添加 -ErrorAction Stop 并捕获异常呢?

try {
    Start-Service MySvc -ErrorAction Stop
} catch {
    # Examine and play with one of the following objects
    Write-Host "$($error[0].Exception)"
    Write-Host "$($_.exception)"
}

我最终创建了 octopus deploy 脚本来打印 Windows 事件中的最后 3 个错误。

$EntryType = 'Error'
$LogName = 'Application'
$Source = '.NET Runtime'
$EventCount = 3

Write-Host ' '
Write-Host "Searching for the last $EventCount events of source $Source.."
$evts = Get-EventLog -LogName $LogName -Newest $EventCount -EntryType $EntryType -Source $Source -ErrorAction SilentlyContinue # | Format-List -Property *
if($evts){
    Write-Host ' '
    $i = 1;
    $evts | ForEach-Object -Process {
        Write-Host "`tPrinting event $i"

        $obj = $_#$evts | Select-Object -Property TimeGenerated, Message
        $time = $obj."TimeGenerated"
        $message = $obj."Message" # or $obj | Select -ExpandProperty "SomeProp"

        Write-Host "`tTime: $time"
        Write-Host "`tMessage: $message"
        Write-Host ' '
        $i++;
    }

} else{
    Write-Host "No events found with the name $Source"
}

Write-Host ' '
Exit 0