This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-toolbuilder-cil/src/MfGames.ToolBuilder/LoggingToolService.cs
Dylan R. E. Moonfire ad0525be04 feat: initial commit
2021-09-10 12:33:42 -05:00

78 lines
2.4 KiB
C#

using System;
using System.CommandLine;
using MfGames.ToolBuilder.Extensions;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Exceptions;
namespace MfGames.ToolBuilder
{
/// <summary>
/// A service for handling logging options.
/// </summary>
public class LoggingToolService
{
public LoggingToolService()
{
this.LogLevelOption = new Option<string>(
"--log-level",
() => nameof(LogEventLevel.Information),
string.Format(
"Controls the verbosity of the output: {0}. Not case-sensitive and prefixes allowed.",
string.Join(", ", Enum.GetNames<LogEventLevel>())));
}
/// <summary>
/// Gets the common option for setting the log level.
/// </summary>
public Option<string> LogLevelOption { get; }
/// <summary>
/// Adds the common options to the command.
/// </summary>
/// <param name="root"></param>
public void AddOptions(RootCommand root)
{
root.AddGlobalOption(this.LogLevelOption);
}
/// <summary>
/// Sets up logging based on the global settings.
/// </summary>
/// <param name="arguments">The arguments to the command.</param>
public void Configure(string[] arguments)
{
// Figure out the logging level.
string level = GlobalOptionHelper.GetArgumentValue(
this.LogLevelOption,
arguments,
"Information");
LogEventLevel logLevel = level.GetEnumFuzzy<LogEventLevel>(
"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;
}
}
}