using System; using System.CommandLine; using MfGames.ToolBuilder.Extensions; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Exceptions; namespace MfGames.ToolBuilder { /// /// A service for handling logging options. /// public class LoggingToolService { public LoggingToolService() { this.LogLevelOption = new Option( "--log-level", () => nameof(LogEventLevel.Information), string.Format( "Controls the verbosity of the output: {0}. Not case-sensitive and prefixes allowed.", string.Join(", ", Enum.GetNames()))); } /// /// Gets the common option for setting the log level. /// public Option LogLevelOption { get; } /// /// Adds the common options to the command. /// /// public void AddOptions(RootCommand root) { root.AddGlobalOption(this.LogLevelOption); } /// /// Sets up logging based on the global settings. /// /// The arguments to the command. public void Configure(string[] arguments) { // Figure out the logging level. string level = GlobalOptionHelper.GetArgumentValue( this.LogLevelOption, arguments, "Information"); LogEventLevel logLevel = level.GetEnumFuzzy( "log level"); // Figure out how we are going to configure the logger. var configuration = new LoggerConfiguration(); // Create the logger and set it. const string template = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] " + "{Message}" + "{NewLine}{Exception}"; Logger logger = configuration .Enrich.WithDemystifiedStackTraces() .Enrich.WithExceptionDetails() .MinimumLevel.Is(logLevel) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: template) .CreateLogger(); Log.Logger = logger; } } }