dotnet / dotnet/command-line-api
Adding '--verbosity' global option best practices
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
I'm trying to add a **global option** named `--verbosity` with `-v` alias following [these set of designs](https://learn.microsoft.com/en-us/dotnet/standard/commandline/syntax#the---verbosity-option), specially this one:
>If you define aliases, use `-v` for `--verbosity` and make `-v` without an argument an alias for `--verbosity Diagnostic`.
Also, I'm using the *Middleware* to intercept the `--verbosity` and set the console log accordingly (not sure whether my code is the best way to accomplish this - but it's the only way I've found)
```
internal class MyRootCommand : RootCommand
{
public const string CommandName = "myroot";
public static readonly Option VerbosityOption = CreateVerbosityOption();
private static Option CreateVerbosityOption()
{
var verbosity = new Option("--verbosity", ParseVerbosity, isDefault: true, description: "Specifies how much output is sent to the console.")
.FromAmong(Verbosity.Quiet, Verbosity.Normal, Verbosity.Diagnostic);
verbosity.AddAlias("-v");
verbosity.AddValidator(ValidateVerbosity);
return verbosity;
}
private static Verbosity ParseVerbosity(ArgumentResult result)
{
if (result.Tokens.Count == 1)
return new Verbosity(result.Tokens[0].Value);
if (result.Tokens.Count == 1 && result.Tokens[0].Value == "-v")
return Verbosity.Diagnostic;
return Verbosity.Normal;
}
private static void ValidateVerbosity(OptionResult result)
{
//not called
}
public MyRootCommand() : base("blablabla")
{
AddGlobalOption(VerbosityOption);
```
Intercepting and adding `LoggerFactory` to the binding context, using the `verbosity` global.
```
private static async Task Middleware(InvocationContext context, Func next)
{
var verbosity = new Verbosity(context.ParseResult.GetValueForOption(MyRootCommand.VerbosityOption));
var loggerFactory = LoggerFactory.Create(builder =>
{
//will use 'verbosity' to set the level here
builder.AddConsole().SetMinimumLevel(LogLevel.Information);
});
context.BindingContext.AddService(s => loggerFactory);
```
Now, the `ValidateVerbosity(...)` is not called when I issue `myroot -v` to the command line. **Error**: _Required argument missing for option: '-v'._
Contributor guide
Assessment
This issue has not been assessed yet.