Answer a question

I'm migrating a legacy .NET 2.2 Core MVC App to .NET 6. One of my challenges is that Program.cs no longer calls Startup.cs so I need to migrate everything to Program.cs. Mostly, that's been fine with 1 problem. I can't get Serilog to work properly in Debug Mode using VS Code on a Mac. The problem is that it seems to work just fine using Visual Studio Community 2022 on Windows.

To replicate my issue:

  1. Make sure .NET 6 is installed on the Mac
  2. Open Visual Studio Code on Mac (I've tried this on x64 and Arm)
  3. Open the terminal and create a folder mkdir TestMVC and go into that folder cd TestMVC
  4. Create a vanilla MVC project in the terminal dotnet new mvc
  5. Open in Visual Studio Code and follow any setup directions (ex: install C# extensions, setup .Net Core Launch (web) launch.json and tasks.json)
  6. Add Serilog via nuget Install-Package Serilog -Version 2.10.0 and add Serilog.ASPNetCore Install-Package Serilog.AspNetCore -Version 4.1.0
  7. In Program.cs, add builder.Host.UseSerilog(); just below the var builder = WebApplication.CreateBuilder(args); line
  8. Run and Debug

It will compile and everything will look like its working but no browser window will launch and it will just stop after showing all the various DLLs. If you comment out the //builder.Host.UseSerilog(); everything works fine.

I don't think its Serilog because if I open that exact same project (no changes) in Visual Studio 2022 Preview on a Windows machine, it works fine.

Any suggestions or ideas that might help me?

Answers

VS Code monitors the console output to look for a specific regular expression defined in your launch.json under serverReadyAction, so if you don't write to the Console at all (as it seems to be your case) or if your write to the Console using an output template that doesn't match what's in the regex, then the browser is never launched.

"serverReadyAction": {
  "action": "openExternally",
  "pattern": "\\bNow listening on:\\s+(https?://\\S+)"  <<<<<<<<
}

Writing to the Console should be enough for the browser to be launched by VS Code using the default RegEx that comes with the default template nowadays (I know.... Don't shoot the messenger though, complain to the VS Code folks! 😄 ):

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console());

If that doesn't work and the RegEx doesn't match, you can either change the RegEx, or change the output template to match the RegEx (hacky and not my recommendation, but works):

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console(outputTemplate: "{Level:w4}: {SourceContext}[0] {NewLine}      {Message:lj}{Exception}{NewLine}"));
Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品