Instantly share code, notes, and snippets.

@takeshik /log.cs
Last active Aug 29, 2015

Embed
What would you like to do?
public class Log
{
public delegate string HeaderFunc(
[CallerFilePath] string file = "",
[CallerLineNumber] int line = 0,
[CallerMemberName] string member = ""
);
internal class Disposable : IDisposable
{
private readonly object _obj;
internal Disposable(object obj)
{
this._obj = obj;
}
public void Dispose()
{
var obj = ((Stack<object>) CallContext.GetData("LoggingObjects")).Pop();
Debug.Assert(obj != this._obj);
}
}
public static IDisposable Start(object obj)
{
var stack = (Stack<object>) CallContext.GetData("LoggingObjects");
if (stack == null)
{
stack = new Stack<object>();
CallContext.SetData("LoggingObjects", stack);
}
stack.Push(obj);
return new Disposable(obj);
}
public static void Write(Func<HeaderFunc, string> header, string format, params object[] args)
{
Console.WriteLine(header(Caller) + " " + format, args);
}
public static string Caller(
[CallerFilePath] string callerFilePath = "",
[CallerLineNumber] int callerLineNumber = 0,
[CallerMemberName] string callerMemberName = "")
{
var obj = ((Stack<object>) CallContext.GetData("LoggingObjects")).Peek();
return string.Format("{0}:L{1} [{2}.{3}]", callerFilePath, callerLineNumber, obj.GetType().Name, callerMemberName);
}
}
c:\….cs:L41 [Foo.Hoge] 12 34 56
c:\….cs:L54 [Bar.Fugo] ほげ-foo
c:\….cs:L55 [Bar.Fugo] ふご-bar
c:\….cs:L43 [Foo.Hoge] 78 90 12
void Main()
{
new Foo().Hoge();
}
public class Foo
{
public void Hoge()
{
using (Log.Start(this))
{
Log.Write(_ => _(), "{0} {1} {2}", 12, 34, 56);
new Bar().Fugo();
Log.Write(_ => _(), "{0} {1} {2}", 78, 90, 12);
}
}
}
public class Bar
{
public void Fugo()
{
using (Log.Start(this))
{
Log.Write(_ => _(), "{0}-{1}", "ほげ", "foo");
Log.Write(_ => _(), "{0}-{1}", "ふご", "bar");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment