Skip to content

Instantly share code, notes, and snippets.

@maryamariyan
Last active November 27, 2020 01:19
Show Gist options
  • Save maryamariyan/8fdf800318f61b1244b42c185b83b179 to your computer and use it in GitHub Desktop.
Save maryamariyan/8fdf800318f61b1244b42c185b83b179 to your computer and use it in GitHub Desktop.
custom formatter implementation template
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using System;
using System.IO;
namespace ConsoleApp46
{
public class CustomFormatter : ConsoleFormatter, IDisposable
{
private IDisposable _optionsReloadToken;
public CustomFormatter(IOptionsMonitor<CustomOptions> options)
// case insensitive name for the formatter
: base("customName")
{
ReloadLoggerOptions(options.CurrentValue);
_optionsReloadToken = options.OnChange(ReloadLoggerOptions);
}
private void ReloadLoggerOptions(CustomOptions options)
{
FormatterOptions = options;
}
public CustomOptions FormatterOptions { get; set; }
public void Dispose()
{
_optionsReloadToken?.Dispose();
}
public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter)
{
string message = logEntry.Formatter(logEntry.State, logEntry.Exception);
if (logEntry.Exception == null && message == null)
{
return;
}
if (!FormatterOptions.ExcludeNotes)
{
textWriter.WriteLine("TEMPLATE NOTE: Logic to write/format the log message goes here!");
if (!FormatterOptions.DisableColors)
{
textWriter.WriteLineWithColor("TEMPLATE NOTE: To get colors in the log, message would need to get embedded with ANSI color codes.", ConsoleColor.Black, ConsoleColor.Yellow);
}
textWriter.WriteLine("TEMPLATE NOTE: sample logic: https://github.com/dotnet/runtime/blob/23611e/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs#L29-L97");
}
textWriter.WriteLine(message);
}
}
}
using Microsoft.Extensions.Logging.Console;
using System;
namespace ConsoleApp46
{
public class CustomOptions : JsonConsoleFormatterOptions
{
public bool ExcludeNotes { get; set; }
public bool DisableColors { get; set; }
}
}
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace ConsoleApp46
{
class Program
{
public static async Task Main(string[] args)
{
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddConsole(o =>
{
o.FormatterName = "customName";
o.LogToStandardErrorThreshold = LogLevel.Trace;
})
.AddConsoleFormatter<CustomFormatter, CustomOptions>(o =>
{
o.IncludeScopes = true;
o.TimestampFormat = "HH:mm:ss ";
});
});
var logger = loggerFactory.CreateLogger<Program>();
using (logger.BeginScope("This is a scope message with number: {CustomNumber}", 123))
{
logger.LogInformation("Random log message");
}
}
}
}
using System;
using System.IO;
namespace ConsoleApp46
{
public static class TextWriterExtensions
{
public static void WriteLineWithColor(this TextWriter textWriter, string message, ConsoleColor? background, ConsoleColor? foreground)
{
// Order: backgroundcolor, foregroundcolor, Message, reset foregroundcolor, reset backgroundcolor
if (background.HasValue)
{
textWriter.Write(GetBackgroundColorEscapeCode(background.Value));
}
if (foreground.HasValue)
{
textWriter.Write(GetForegroundColorEscapeCode(foreground.Value));
}
textWriter.WriteLine(message);
if (foreground.HasValue)
{
textWriter.Write(DefaultForegroundColor); // reset to default foreground color
}
if (background.HasValue)
{
textWriter.Write(DefaultBackgroundColor); // reset to the background color
}
}
internal const string DefaultForegroundColor = "\x1B[39m\x1B[22m"; // reset to default foreground color
internal const string DefaultBackgroundColor = "\x1B[49m"; // reset to the background color
internal static string GetForegroundColorEscapeCode(ConsoleColor color)
{
return color switch
{
ConsoleColor.Black => "\x1B[30m",
ConsoleColor.DarkRed => "\x1B[31m",
ConsoleColor.DarkGreen => "\x1B[32m",
ConsoleColor.DarkYellow => "\x1B[33m",
ConsoleColor.DarkBlue => "\x1B[34m",
ConsoleColor.DarkMagenta => "\x1B[35m",
ConsoleColor.DarkCyan => "\x1B[36m",
ConsoleColor.Gray => "\x1B[37m",
ConsoleColor.Red => "\x1B[1m\x1B[31m",
ConsoleColor.Green => "\x1B[1m\x1B[32m",
ConsoleColor.Yellow => "\x1B[1m\x1B[33m",
ConsoleColor.Blue => "\x1B[1m\x1B[34m",
ConsoleColor.Magenta => "\x1B[1m\x1B[35m",
ConsoleColor.Cyan => "\x1B[1m\x1B[36m",
ConsoleColor.White => "\x1B[1m\x1B[37m",
_ => DefaultForegroundColor // default foreground color
};
}
internal static string GetBackgroundColorEscapeCode(ConsoleColor color)
{
return color switch
{
ConsoleColor.Black => "\x1B[40m",
ConsoleColor.DarkRed => "\x1B[41m",
ConsoleColor.DarkGreen => "\x1B[42m",
ConsoleColor.DarkYellow => "\x1B[43m",
ConsoleColor.DarkBlue => "\x1B[44m",
ConsoleColor.DarkMagenta => "\x1B[45m",
ConsoleColor.DarkCyan => "\x1B[46m",
ConsoleColor.Gray => "\x1B[47m",
_ => DefaultBackgroundColor // Use default background color
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment