Skip to content

Instantly share code, notes, and snippets.

@damianh
Created May 19, 2015 15:11
Show Gist options
  • Save damianh/bb1c6c04111210619811 to your computer and use it in GitHub Desktop.
Save damianh/bb1c6c04111210619811 to your computer and use it in GitHub Desktop.
namespace LibLog.Logging
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using YourRootNamespace.Logging;
public class Foo : IDisposable
{
private static ILog s_logger = LogProvider.For<Foo>();
public void Bar()
{
using (LogProvider.CurrentLogProvider.Here())
{
s_logger.Info("Baz");
}
}
}
public static class ILogProviderExtensions
{
public static IDisposable Here(this ILogProvider logProvider,
[CallerMemberName] string callerMethodName = null,
[CallerFilePath] string callerFilePath = null,
[CallerLineNumber] int callerLineNumber = -1)
{
IDisposable calledFromMethodContext = logProvider.OpenMappedContext("calledFromMethod", callerMethodName);
IDisposable calledFromFileContext = logProvider.OpenMappedContext("calledFromFile", Path.GetFileName(callerFilePath));
IDisposable calledFromLineContext = logProvider.OpenMappedContext("calledFromLine", callerLineNumber.ToString());
return new DisposableAction(() =>
{
calledFromMethodContext.Dispose();
calledFromFileContext.Dispose();
calledFromLineContext.Dispose();
});
}
private class DisposableAction : IDisposable
{
private readonly Action _action;
public DisposableAction(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment