Skip to content

Instantly share code, notes, and snippets.

@takeshik
Created March 11, 2014 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takeshik/9480859 to your computer and use it in GitHub Desktop.
Save takeshik/9480859 to your computer and use it in GitHub Desktop.
void Main()
{
new Foo().Hoge();
}
public class Foo
{
public void Hoge()
{
using (Log.Start(this))
{
Log.Write(Log.Caller(), "{0} {1} {2}", 12, 34, 56);
new Bar().Fugo();
Log.Write(Log.Caller(), "{0} {1} {2}", 78, 90, 12);
}
}
}
public class Bar
{
public void Fugo()
{
using (Log.Start(this))
{
Log.Write(Log.Caller(), "{0} {1} {2}", 1, "foo", 2);
Log.Write(Log.Caller(), "{0} {1} {2}", 2, "bar", 3);
Log.Write(Log.Caller(), "{0} {1} {2}", 3, "baz", 4);
}
}
}
// Define other methods and classes here
public class Log
{
internal class Disposable : IDisposable
{
private readonly object _obj;
internal Disposable(object obj)
{
this._obj = obj;
}
public void Dispose()
{
if (((Stack<object>) CallContext.GetData("LoggingObjects")).Pop() != this._obj)
{
throw new InvalidOperationException();
}
}
}
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(string header, string format, params object[] args)
{
var obj = ((Stack<object>) CallContext.GetData("LoggingObjects")).Peek();
Console.WriteLine(header + " " + 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}:{1} [{2}.{3}]", callerFilePath, callerLineNumber, obj.GetType().Name, callerMemberName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment