.NET Core MEL logging with syntax similar to Serilog

I’m using Serilog, but I prefer the MEL (Microsoft.Extensions.Logging) abstractions.

Some functionality in Serilog’s Serilog.ILogger is not available in MEL’s ILogger , or is available but extremely verbose.

I want to enrich a log event. With Serilog I’d use:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_logger
.ForContext("Foo", "abc")
.ForContext("Bar", 123)
.ForContext("Baz", true)
.Information("Process returned {Result}", 42);
</code>
<code>_logger .ForContext("Foo", "abc") .ForContext("Bar", 123) .ForContext("Baz", true) .Information("Process returned {Result}", 42); </code>
_logger
 .ForContext("Foo", "abc")
 .ForContext("Bar", 123)
 .ForContext("Baz", true)
 .Information("Process returned {Result}", 42);

But the MEL equivalent is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using (_logger.BeginScope(new Dictionary<string, object?> {
{ "Foo", "abc" },
{ "Bar", 123 },
{ "Baz", true }
})) {
_logger.LogInformation("Process returned {Result}", 42);
}
</code>
<code>using (_logger.BeginScope(new Dictionary<string, object?> { { "Foo", "abc" }, { "Bar", 123 }, { "Baz", true } })) { _logger.LogInformation("Process returned {Result}", 42); } </code>
using (_logger.BeginScope(new Dictionary<string, object?> { 
 { "Foo", "abc" },
 { "Bar", 123 },
 { "Baz", true }
})) {
 _logger.LogInformation("Process returned {Result}", 42);
}

That is not only ugly, but I always forget the syntax. And that applies even for one log event.

I’ve noticed there are various syntaxes for these sort of things, in addition to the ones above. Is there a simpler option?

I couldn’t find something simpler, so I created some adapters and extension methods.

To enrich multiple log events

An extension method with a signature closely reminiscent to that of Serilog.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>namespace Microsoft.Extensions.Logging;
public static class MultipleLogEventEnrichment
{
public static IDisposable? Enrich(this ILogger logger, params (string, object?)[] properties)
{
ArgumentNullException.ThrowIfNull(logger, nameof(logger));
ArgumentNullException.ThrowIfNull(properties, nameof(properties));
var state = properties.ToDictionary(k => k.Item1, v => v.Item2);
return logger.BeginScope(state);
}
}
</code>
<code>namespace Microsoft.Extensions.Logging; public static class MultipleLogEventEnrichment { public static IDisposable? Enrich(this ILogger logger, params (string, object?)[] properties) { ArgumentNullException.ThrowIfNull(logger, nameof(logger)); ArgumentNullException.ThrowIfNull(properties, nameof(properties)); var state = properties.ToDictionary(k => k.Item1, v => v.Item2); return logger.BeginScope(state); } } </code>
namespace Microsoft.Extensions.Logging;

public static class MultipleLogEventEnrichment
{

 public static IDisposable? Enrich(this ILogger logger, params (string, object?)[] properties)
 {
   ArgumentNullException.ThrowIfNull(logger, nameof(logger));
   ArgumentNullException.ThrowIfNull(properties, nameof(properties));

   var state = properties.ToDictionary(k => k.Item1, v => v.Item2);
   return logger.BeginScope(state);
 }

}

A callsite would look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using (_logger.Enrich(
("Foo", "abc"),
("Bar", 123),
("Baz", true)
)) {
_logger.LogInformation("Process returned {Result}", 42);
}
</code>
<code>using (_logger.Enrich( ("Foo", "abc"), ("Bar", 123), ("Baz", true) )) { _logger.LogInformation("Process returned {Result}", 42); } </code>
using (_logger.Enrich(
 ("Foo", "abc"),
 ("Bar", 123),
 ("Baz", true)
)) {
 _logger.LogInformation("Process returned {Result}", 42);
}

Less ugly than the MEL syntax, and easier to remember.

To enrich a single log event

I learnt that ordinarily I enrich a single log event only. Yet even for that simple case one must use the ugly MEL syntax.

An alternative, as an adapter:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>namespace Microsoft.Extensions.Logging;
public sealed class SingleLogEventAdapter
{
private readonly ILogger _logger;
private readonly Dictionary<string, object?> _state = [];
public SingleLogEventAdapter(ILogger logger) =>
// if you place these classes in a separate common/utils project, then make this ctor internal
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
public SingleLogEventAdapter Enrich(string key, object? value)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(key, nameof(key));
_state.Add(key, value);
return this;
}
private void Log(LogLevel logLevel, string message, params object?[] args)
{
if (!Enum.IsDefined(logLevel)) throw new ArgumentOutOfRangeException(nameof(logLevel));
ArgumentNullException.ThrowIfNullOrWhiteSpace(message, nameof(message));
ArgumentNullException.ThrowIfNull(args, nameof(args));
using (_logger.BeginScope(_state)) _logger.Log(logLevel, message, args);
}
public void LogTrace (string message, params object?[] args) => Log(LogLevel.Trace, message, args);
public void LogDebug (string message, params object?[] args) => Log(LogLevel.Debug, message, args);
public void LogInformation(string message, params object?[] args) => Log(LogLevel.Information, message, args);
public void LogWarning (string message, params object?[] args) => Log(LogLevel.Warning, message, args);
public void LogCritical (string message, params object?[] args) => Log(LogLevel.Critical, message, args);
}
public static class SingleLogEventAdapterExtensions
{
public static SingleLogEventAdapter Enrich(this ILogger logger, string key, object? value)
{
var adapter = new SingleLogEventAdapter(logger);
adapter.Enrich(key, value);
return adapter;
}
}
</code>
<code>namespace Microsoft.Extensions.Logging; public sealed class SingleLogEventAdapter { private readonly ILogger _logger; private readonly Dictionary<string, object?> _state = []; public SingleLogEventAdapter(ILogger logger) => // if you place these classes in a separate common/utils project, then make this ctor internal _logger = logger ?? throw new ArgumentNullException(nameof(logger)); public SingleLogEventAdapter Enrich(string key, object? value) { ArgumentNullException.ThrowIfNullOrWhiteSpace(key, nameof(key)); _state.Add(key, value); return this; } private void Log(LogLevel logLevel, string message, params object?[] args) { if (!Enum.IsDefined(logLevel)) throw new ArgumentOutOfRangeException(nameof(logLevel)); ArgumentNullException.ThrowIfNullOrWhiteSpace(message, nameof(message)); ArgumentNullException.ThrowIfNull(args, nameof(args)); using (_logger.BeginScope(_state)) _logger.Log(logLevel, message, args); } public void LogTrace (string message, params object?[] args) => Log(LogLevel.Trace, message, args); public void LogDebug (string message, params object?[] args) => Log(LogLevel.Debug, message, args); public void LogInformation(string message, params object?[] args) => Log(LogLevel.Information, message, args); public void LogWarning (string message, params object?[] args) => Log(LogLevel.Warning, message, args); public void LogCritical (string message, params object?[] args) => Log(LogLevel.Critical, message, args); } public static class SingleLogEventAdapterExtensions { public static SingleLogEventAdapter Enrich(this ILogger logger, string key, object? value) { var adapter = new SingleLogEventAdapter(logger); adapter.Enrich(key, value); return adapter; } } </code>
namespace Microsoft.Extensions.Logging;

public sealed class SingleLogEventAdapter
{

  private readonly ILogger _logger;
  private readonly Dictionary<string, object?> _state = [];

  public SingleLogEventAdapter(ILogger logger) =>
    // if you place these classes in a separate common/utils project, then make this ctor internal
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));

  public SingleLogEventAdapter Enrich(string key, object? value)
  {
    ArgumentNullException.ThrowIfNullOrWhiteSpace(key, nameof(key));
    _state.Add(key, value);
    return this;
  }

  private void Log(LogLevel logLevel, string message, params object?[] args)
  {
    if (!Enum.IsDefined(logLevel)) throw new ArgumentOutOfRangeException(nameof(logLevel));
    ArgumentNullException.ThrowIfNullOrWhiteSpace(message, nameof(message));
    ArgumentNullException.ThrowIfNull(args, nameof(args));
    using (_logger.BeginScope(_state)) _logger.Log(logLevel, message, args);
  }

  public void LogTrace      (string message, params object?[] args) => Log(LogLevel.Trace,       message, args);
  public void LogDebug      (string message, params object?[] args) => Log(LogLevel.Debug,       message, args);
  public void LogInformation(string message, params object?[] args) => Log(LogLevel.Information, message, args);
  public void LogWarning    (string message, params object?[] args) => Log(LogLevel.Warning,     message, args);
  public void LogCritical   (string message, params object?[] args) => Log(LogLevel.Critical,    message, args);

}


public static class SingleLogEventAdapterExtensions
{

  public static SingleLogEventAdapter Enrich(this ILogger logger, string key, object? value)
  {
    var adapter = new SingleLogEventAdapter(logger);
    adapter.Enrich(key, value);
    return adapter;
  }

}

A callsite would look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_logger
.Enrich("Foo", "abc")
.Enrich("Bar", 123)
.Enrich("Baz", true)
.LogInformation("Process returned {Result}", 42);
</code>
<code>_logger .Enrich("Foo", "abc") .Enrich("Bar", 123) .Enrich("Baz", true) .LogInformation("Process returned {Result}", 42); </code>
_logger
  .Enrich("Foo", "abc")
  .Enrich("Bar", 123)
  .Enrich("Baz", true)
  .LogInformation("Process returned {Result}", 42);

Much better!

The problem is that in a high-throughput path, that results in allocations just for aesthetic purposes. A native option would be much better.

Final note

These are workarounds for an unwieldy native syntax. I opened an issue on the repo requesting some syntactic sugar. Please upvote that issue if you’d like a friendlier API.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật