Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log non-output messages to stderr. #367

Merged
merged 1 commit into from
Oct 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ static async Task<int> Main(string[] args)
_ when ex is TaskCanceledException => string.Empty,
ODataError _e when ex is ODataError => $"Error {_e.ResponseStatusCode}({_e.Error?.Code}) from API:\n {_e.Error?.Message}",
ApiException _e when ex is ApiException => $"Error {_e.ResponseStatusCode} from API.",
AuthenticationFailedException e => $"Authentication failed: {e.Message}",
Identity.Client.MsalException e => $"Authentication failed: {e.Message}",
_ => ex.Message
};

Expand Down Expand Up @@ -124,7 +126,14 @@ static CommandLineBuilder BuildCommandLine()
builder.AddMiddleware(async (ic, next) =>
{
debugEnabled = ic.ParseResult.GetValueForOption<bool>(debugOption);
listener = AzureEventSourceListener.CreateConsoleLogger(debugEnabled ? EventLevel.LogAlways : EventLevel.Critical);
if (debugEnabled)
{
listener = CreateStdErrLogger(EventLevel.LogAlways);
}
else
{
listener = CreateStdErrLogger(EventLevel.Error);
}
await next(ic);
});

Expand Down Expand Up @@ -198,6 +207,9 @@ static IHostBuilder CreateHostBuilder(string[] args) =>
}).ConfigureLogging((ctx, logBuilder) =>
{
logBuilder.SetMinimumLevel(LogLevel.Warning);
logBuilder.ClearProviders();
// Log everything to stderr. Investigate if this breaks scripts that check for stderr instead of the exit code.
logBuilder.AddConsole(c => c.LogToStandardErrorThreshold = LogLevel.Trace);
// Allow runtime selection of log level
logBuilder.AddFilter("Microsoft.Graph.Cli", level => level >= (debugEnabled ? LogLevel.Debug : LogLevel.Warning));
});
Expand All @@ -214,5 +226,14 @@ static void ConfigureAppConfiguration(IConfigurationBuilder builder, string[] ar
builder.AddJsonFile(authCache.GetAuthenticationCacheFilePath(), optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables(prefix: "MGC_");
}

static AzureEventSourceListener CreateStdErrLogger(EventLevel level = EventLevel.Informational)
{
return new AzureEventSourceListener(delegate (EventWrittenEventArgs eventData, string text)
{
// By default, AzureEventSourceListener.CreateConsoleLogger logs to stdout. Use stderr instead.
Console.Error.WriteLine("[{1}] {0}: {2}", eventData.EventSource.Name, eventData.Level, text);
}, level);
}
}
}