Skip to content

Instantly share code, notes, and snippets.

@bent-rasmussen
Created September 29, 2020 16:43
Show Gist options
  • Save bent-rasmussen/e793912137bbfccbdc5dd6a97d5fd40b to your computer and use it in GitHub Desktop.
Save bent-rasmussen/e793912137bbfccbdc5dd6a97d5fd40b to your computer and use it in GitHub Desktop.
An logger experiment for C# using the dynamic language feature.
<Query Kind="Program">
<NuGetReference>Serilog</NuGetReference>
<NuGetReference>Serilog.Sinks.LINQPad</NuGetReference>
<Namespace>System.Dynamic</Namespace>
<Namespace>Serilog</Namespace>
</Query>
// Just an experiment; you should probably never use this. :-)
// Would be nicer with compile-time function creation but not possible atm afaik.
void Main()
{
var lplogger =
new LoggerConfiguration()
.WriteTo.LINQPad()
.CreateLogger();
dynamic logger = new DynamicLogger(lplogger);
logger.StartedOperation1("Foo", "Bar", "Baz");
// Note: in linqpad you won't see the method names - but you should using other sinks.
logger.StartedOperation2(hoo: "Foo", hey: "Bar", hum: "Baz");
}
public class DynamicLogger : DynamicObject
{
public DynamicLogger(ILogger logger)
{
_logger = logger;
}
private readonly ILogger _logger;
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
//var str = $"{{method:l}}({String.Join(", ", binder.CallInfo.ArgumentNames.Select(argName => $"{{{argName}}}"))})";
var sb = new System.Text.StringBuilder();
sb.Append("{method:l}");
sb.Append("(");
var first = true;
var parameters = new object[args.Length + 1];
parameters[0] = binder.Name;
var hasAllNames = binder.CallInfo.ArgumentNames.Count == binder.CallInfo.ArgumentCount;
for (var i = 0; i < binder.CallInfo.ArgumentCount; i++)
{
var argName = hasAllNames ? binder.CallInfo.ArgumentNames[i] : $"arg{i}";
var arg = args[i];
if (first)
first = false;
else
sb.Append(", ");
sb.Append("{");
sb.Append(argName);
sb.Append("}");
parameters[i + 1] = arg;
}
sb.Append(")");
_logger.Information(sb.ToString(), parameters);
result = (object)null;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment