Home > Software design >  Console logging is disabled for local build, but not after publishing as a dotnet tool
Console logging is disabled for local build, but not after publishing as a dotnet tool

Time:10-20

I've developed a tool built with .Net 6 which serves a rest api. I modified the appsettings.json file so that it suppresses the default "info" messages that usually appear in the console when running an api project:

"Logging": {
  "LogLevel": {
    "Default": "Warning",
    "Microsoft.AspNetCore": "Warning",
    "Microsoft": "Warning",
    "System": "None"
  }
}

This works fine for my local build, and all but my custom log messages are suppressed, but after publishing as a dotnet tool, unfortunately the default info messages continue to be displayed to the cli. How can these be suppressed?

Edit: More details -- I've confirmed the appsettings.json file is located in the package, and it is installed in the global tool installation folder. I've also confirmed that the tool runs as intended after copy/pasting the appsettings.json file into the same directory of the executable, which indicates that the executable could not find the appsettings.json file.

This is just a shot in the dark, but, the tool name (and executable name) differs from the package name and its associated directory in .store. I have to wonder if this could be related to the executable search path for the settings file.

CodePudding user response:

This problem was caused by the executable being unable to locate the appsettings.json file included with the distribution. According to this source it looks like this is intentional behavior:

The IHostEnvironment.ContentRootPath property represents the default directory where appsettings.json and other content files are loaded in a hosted application, including ASP.NET apps. This property's value defaults to Environment.CurrentDirectory, which is the current working directory of the application. This behavior allows the same app to be executed under different working directories and use the content from each directory.

When a Windows process (either application or service) is launched without specifying a working directory, the working directory of the process that created it is used.

Being that this is my first dotnet tool as a webdev unfamiliar with the use of .Net for most CLI applications, this was a curveball for me, but once I understood the issue the fix was relatively straight foward.

My tool has no need to be configured using local settings, so the WebHost content root path had to be updated in Program.cs as follows:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
    ContentRootPath = Directory.GetParent(Assembly.GetExecutingAssembly().Location)?.FullName
});
  • Related