Last active
February 28, 2020 07:34
-
-
Save wgross/085c0cede2e1185ce6d7d7fd80175fcd to your computer and use it in GitHub Desktop.
Logger facade with using and Caller-attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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