Last active
December 15, 2015 16:59
-
-
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.
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 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())); | |
} | |
} |
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
//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(); | |
} |
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 interface ILogBuilder | |
{ | |
Write(LogEntry entry); | |
IDelayedLogBuilder Delayed(); | |
ILogBuilder WithProperties(Action<LogPropertyFactory> action); | |
// Other methods | |
} |
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
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