Skip to content

Instantly share code, notes, and snippets.

@wgross
Last active February 28, 2020 07:34
Show Gist options
  • Save wgross/085c0cede2e1185ce6d7d7fd80175fcd to your computer and use it in GitHub Desktop.
Save wgross/085c0cede2e1185ce6d7d7fd80175fcd to your computer and use it in GitHub Desktop.
Logger facade with using and Caller-attributes
public class ClassLogger
{
private readonly string typeName;
public static ClassLogger Make<T>(T instance)
{
return new ClassLogger(typeof(T).Name);
}
public ClassLogger(string typeName)
{
this.typeName = typeName;
}
public MethodLogger StepIn([CallerMemberName] string memberName = "")
{
var typeMemberName = $"{this.typeName}.{memberName}";
var logger = new MethodLogger(typeMemberName);
logger.Log($"{typeMemberName}:StepIn");
return logger;
}
}
public readonly struct MethodLogger : IDisposable
{
private readonly string memberName;
internal MethodLogger(string memberName)
{
this.memberName = memberName;
}
public void Dispose() => $"{this.memberName}:StepOut".Dump();
public void Log(string message, params string[] p)
=> (message + string.Join(" ", p)).Dump("Info");
}
public class Class
{
private readonly ClassLogger classLogger;
public Class() => this.classLogger = ClassLogger.Make(this);
public void Method()
{
using (var logger = this.classLogger.StepIn())
logger.Log("blah", "1", "3");
"do something".Dump();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment