Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active December 15, 2015 16:59
Show Gist options
  • Save sandcastle/5293291 to your computer and use it in GitHub Desktop.
Save sandcastle/5293291 to your computer and use it in GitHub Desktop.
Simplified version of a logging project that captures multiple timing properties for a log entry using a DisposableTimer.
public class DisposableTimer : IDisposable
{
readonly string _name;
readonly IDelayedLogBuilder _logBuilder;
readonly Stopwatch _stopwatch;
internal DisposableTimer(IDelayedLogBuilder logBuilder, string name)
{
_name = name;
_logBuilder = logBuilder;
_stopwatch = new Stopwatch();
_stopwatch.Start();
}
public void Dispose()
{
_stopwatch.Stop();
_logBuilder.WithProperties(p => p.Add(_name, _stopwatch.Elapsed.ToString()));
}
}
//Required to capture multiple timings for a single log entry
public interface IDelayedLogBuilder : IDisposable
{
DisposableTimer Timer(string name);
IDelayedLogBuilder WithProperties(Action<LogPropertyFactory> action);
// A level needs to be set before dispose
AsDebug();
AsFatal();
}
public interface ILogBuilder
{
Write(LogEntry entry);
IDelayedLogBuilder Delayed();
ILogBuilder WithProperties(Action<LogPropertyFactory> action);
// Other methods
}
static class Program
{
void WithoutTimings()
{
var builder = Log.Build("A message")
.WithProperties(p => p.Add("Something", 123))
.AsDebug(); //builds log entry and writes
}
void WithTimings()
{
var builder = Log.Build("A message")
.WithProperties(p => p.Add("Something", 123))
.Delayed()
.AsDebug();
using (builder.Timer("Step 1"))
{
//...
}
using (builder.Timer("Step 2"))
{
//...
}
//builds log entry and writes
builder.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment