Skip to content

Commit

Permalink
Using new logging framework Serilog do trace errors more easily
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKert committed Apr 12, 2019
1 parent 91f935e commit 901673d
Show file tree
Hide file tree
Showing 24 changed files with 316 additions and 377 deletions.
20 changes: 20 additions & 0 deletions src/BuildVision.Common/ApplicationInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Diagnostics;

namespace BuildVision.Common
{
public static class ApplicationInfo
{
public const string ApplicationName = "BuildVision";

public static FileVersionInfo GetHostVersionInfo()
{
return Process.GetCurrentProcess().MainModule.FileVersionInfo;
}

public static Version GetPackageVersion(object package)
{
return package.GetType().Assembly.GetName().Version;
}
}
}
6 changes: 6 additions & 0 deletions src/BuildVision.Common/BuildVision.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@

<ItemGroup>
<PackageReference Include="AppInsights.WindowsDesktop" Version="2.10.17-preview" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.1" />
<PackageReference Include="Serilog" Version="2.5.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.0.0" targetFramework="net452" />
<PackageReference Include="Serilog.Sinks.File" Version="3.2.0" targetFramework="net452" />
<PackageReference Include="SerilogAnalyzer" Version="0.12.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
64 changes: 64 additions & 0 deletions src/BuildVision.Common/Logging/ILoggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Globalization;
using System.Threading.Tasks;
using Serilog;

namespace BuildVision.Common.Logging
{
public static class ILoggerExtensions
{
public static void Assert(this ILogger logger, bool condition, string messageTemplate)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate);
#pragma warning restore Serilog004
}
}

public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
}
}

public static void Time(this ILogger logger, string name, Action method)
{
var startTime = DateTime.Now;
method();
logger.Verbose("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
}

public static T Time<T>(this ILogger logger, string name, Func<T> method)
{
var startTime = DateTime.Now;
var value = method();
logger.Verbose("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
return value;
}

public static async Task TimeAsync(this ILogger logger, string name, Func<Task> methodAsync)
{
var startTime = DateTime.Now;
await methodAsync().ConfigureAwait(false);
logger.Verbose("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
}

public static async Task<T> TimeAsync<T>(this ILogger logger, string name, Func<Task<T>> methodAsync)
{
var startTime = DateTime.Now;
var value = await methodAsync().ConfigureAwait(false);
logger.Verbose("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
return value;
}

static string FormatSeconds(TimeSpan timeSpan) => timeSpan.TotalSeconds.ToString("0.##", CultureInfo.InvariantCulture);
}
}
13 changes: 13 additions & 0 deletions src/BuildVision.Common/Logging/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using Serilog;

namespace BuildVision.Common.Logging
{
public static class Log
{
private static Lazy<ILogger> Logger { get; } = new Lazy<ILogger>(() => LogManager.ForContext(typeof(Log)));

public static void Assert(bool condition, string messageTemplate)
=> Logger.Value.Assert(condition, messageTemplate);
}
}
56 changes: 56 additions & 0 deletions src/BuildVision.Common/Logging/LogManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.IO;
using Serilog;
using Serilog.Core;
using Serilog.Events;

namespace BuildVision.Common.Logging
{
public static class LogManager
{
#if DEBUG
private static LogEventLevel DefaultLoggingLevel = LogEventLevel.Debug;
#else
private static LogEventLevel DefaultLoggingLevel = LogEventLevel.Information;
#endif

private static LoggingLevelSwitch LoggingLevelSwitch = new LoggingLevelSwitch(DefaultLoggingLevel);

static Logger CreateLogger()
{
var logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
ApplicationInfo.ApplicationName,
"extension.log");

const string outputTemplate =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{ProcessId:00000}] {Level:u4} [{ThreadId:00}] {ShortSourceContext,-25} {Message:lj}{NewLine}{Exception}";

return new LoggerConfiguration()
.Enrich.WithProcessId()
.Enrich.WithThreadId()
.MinimumLevel.ControlledBy(LoggingLevelSwitch)
.WriteTo.File(logPath,
fileSizeLimitBytes: null,
outputTemplate: outputTemplate,
shared: true)
.CreateLogger();
}

public static void EnableTraceLogging(bool enable)
{
var logEventLevel = enable ? LogEventLevel.Verbose : DefaultLoggingLevel;
if (LoggingLevelSwitch.MinimumLevel != logEventLevel)
{
ForContext(typeof(LogManager)).Information("Set Logging Level: {LogEventLevel}", logEventLevel);
LoggingLevelSwitch.MinimumLevel = logEventLevel;
}
}

static Lazy<Logger> Logger { get; } = new Lazy<Logger>(CreateLogger);

public static ILogger ForContext<T>() => ForContext(typeof(T));

public static ILogger ForContext(Type type) => Logger.Value.ForContext(type).ForContext("ShortSourceContext", type.Name);
}
}
6 changes: 1 addition & 5 deletions src/BuildVision.UI/BuildVision.UI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,6 @@
<Compile Include="Settings\Models\BaseGridColumnSettings.cs" />
<Compile Include="Settings\Models\BuildMessagesSettings.cs" />
<Compile Include="Settings\Models\BuildProgressSettings.cs" />
<Compile Include="Common\Logging\BindingErrorListener.cs" />
<Compile Include="Common\Logging\TraceManager.cs" />
<Compile Include="Components\ErrorsGrid.xaml.cs">
<DependentUpon>ErrorsGrid.xaml</DependentUpon>
</Compile>
Expand Down Expand Up @@ -376,8 +374,6 @@
<Version>14.3.81-pre</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Commands\" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
16 changes: 0 additions & 16 deletions src/BuildVision.UI/Common/Logging/BindingErrorListener.cs

This file was deleted.

172 changes: 0 additions & 172 deletions src/BuildVision.UI/Common/Logging/TraceManager.cs

This file was deleted.

4 changes: 2 additions & 2 deletions src/BuildVision.UI/Components/ErrorsGrid.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using BuildVision.Common.Logging;
using BuildVision.Contracts;
using BuildVision.UI.Common.Logging;
using BuildVision.UI.Extensions;
using BuildVision.UI.Models;

Expand Down Expand Up @@ -50,7 +50,7 @@ private void ErrorsGridRowOnMouseLeftButtonUp(object sender, MouseButtonEventArg
}
catch (Exception ex)
{
ex.Trace("Navigate to error item exception.");
LogManager.ForContext<ErrorsGrid>().Error(ex, "Navigate to error item exception.");
}
}

Expand Down
Loading

0 comments on commit 901673d

Please sign in to comment.