feat(*): Update DisposableStopWatch to work without a logger

This commit is contained in:
Josh Creek
2021-12-14 22:52:16 +00:00
parent d8ab65334a
commit 4b8acdf4d9
3 changed files with 34 additions and 4 deletions
@@ -19,8 +19,8 @@
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<RepositoryType>git</RepositoryType>
<PackageTags>creek</PackageTags>
<Version>1.4.1</Version>
<AssemblyVersion>1.4.0.1</AssemblyVersion>
<Version>1.4.3</Version>
<AssemblyVersion>1.4.0.3</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
@@ -6,14 +6,16 @@ namespace Creek.HelpfulExtensions
{
public class DisposableStopWatch : IDisposable
{
private ILogger _logger;
private readonly ILogger _logger;
private Stopwatch _stopWatch;
private string _message;
private bool _useConsole;
private bool _useConsoleOnly;
public DisposableStopWatch(ILogger logger, string message = null, bool useConsole = false)
{
_logger = logger;
_useConsoleOnly = false;
_stopWatch = new Stopwatch();
_message = message ?? string.Empty;
_useConsole = useConsole;
@@ -33,13 +35,30 @@ namespace Creek.HelpfulExtensions
_stopWatch.Start();
}
public DisposableStopWatch(string message = null)
{
_useConsoleOnly = true;
_stopWatch = new Stopwatch();
_message = message ?? string.Empty;
string startMessage = $"Start: {message}";
Console.WriteLine(startMessage);
_stopWatch.Start();
}
public void Dispose()
{
_stopWatch.Stop();
string endMessage = $"Complete:{_message}: Elapsed: {_stopWatch.Elapsed}";
if (_useConsole)
if (_useConsoleOnly)
{
Console.WriteLine(endMessage);
}
else if (_useConsole)
{
_logger.LogInformation(endMessage);
Console.WriteLine(endMessage);
@@ -54,5 +73,7 @@ namespace Creek.HelpfulExtensions
public static class DisposableStopWatchExtension
{
public static DisposableStopWatch DisposableStopWatch(this ILogger logger, string message = null, bool useConsole = false) => new DisposableStopWatch(logger, message, useConsole);
public static DisposableStopWatch DisposableStopWatch(this string message) => new DisposableStopWatch(message);
}
}
+9
View File
@@ -157,4 +157,13 @@ using (_logger.DisposableStopWatch("A message", true))
}
```
You can also make use of it without a logger for very barebones console applications.
```csharp
using ("A message".DisposableStopWatch())
{
...
}
```
You get a `Start:` log, with the message appended if you've passed it, and once your code within the using block has run you get `Complete:` with the messaged appended if you've passed it, then on the same line `Elapsed:` and the time elapsed in HH:MM:SS:MS..... format.