Skip to content
This repository has been archived by the owner on Oct 2, 2024. It is now read-only.

Allow to report errors to the module through a less intrusive mechanism #61

Merged
merged 4 commits into from
Feb 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: '{build}'
image: Visual Studio 2017
build_script:
- ps: ./Build.ps1 -majorMinor "4.2" -patch "$env:APPVEYOR_BUILD_VERSION" -customLogger "C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
- ps: ./Build.ps1 -majorMinor "5.0" -patch "$env:APPVEYOR_BUILD_VERSION" -customLogger "C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
artifacts:
- path: SerilogWeb.*.nupkg
deploy:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;

namespace SerilogWeb.Classic.Extensions
{
/// <summary>
///
/// </summary>
public static class SerilogWebRequestExtensions
{
/// <summary>
/// The key under which we store Exceptions to be logged by SerilogWeb.Classic in HttpContext.Current.Items
/// </summary>
private const string SerilogWebErrorKey = "SerilogWebClassic_Errors";

/// <summary>
/// Adds an error so that it can be logged by the SerilogWeb module at the end of the request process
/// </summary>
/// <param name="self">the HttpContextBase</param>
/// <param name="exception">the Exception to log</param>
public static void AddSerilogWebError(this HttpContextBase self, Exception exception)
{
if (self == null) throw new ArgumentNullException(nameof(self));
AddSerilogWebErrorInternal(self.Items, exception);

}

/// <summary>
/// Adds an error so that it can be logged by the SerilogWeb module at the end of the request process
/// </summary>
/// <param name="self">the HttpContext</param>
/// <param name="exception">the Exception to log</param>
public static void AddSerilogWebError(this HttpContext self, Exception exception)
{
if (self == null) throw new ArgumentNullException(nameof(self));
AddSerilogWebErrorInternal(self.Items, exception);
}

private static void AddSerilogWebErrorInternal(IDictionary items, Exception ex)
{
Stack<Exception> errors = null;
if (items.Contains(SerilogWebErrorKey))
{
errors = items[SerilogWebErrorKey] as Stack<Exception>;
}

errors = errors ?? new Stack<Exception>();

errors.Push(ex);
items[SerilogWebErrorKey] = errors;
}


/// <summary>
/// Retrieves the last error stored through <see cref="AddSerilogWebError(System.Web.HttpContextBase,System.Exception)"/> or null
/// </summary>
/// <param name="self">the HttpContextBase</param>
public static Exception GetLastSerilogWebError(this HttpContextBase self)
{
if (self == null) throw new ArgumentNullException(nameof(self));
return GetLastSerilogWebErrorInternal(self.Items);
}

/// <summary>
/// Retrieves the last error stored through <see cref="AddSerilogWebError(System.Web.HttpContext,System.Exception)"/> or null
/// </summary>
/// <param name="self">the HttpContextBase</param>
public static Exception GetLastSerilogWebError(this HttpContext self)
{
if (self == null) throw new ArgumentNullException(nameof(self));
return GetLastSerilogWebErrorInternal(self.Items);
}

private static Exception GetLastSerilogWebErrorInternal(IDictionary items)
{
if (!items.Contains(SerilogWebErrorKey))
{
return null;
}

var errors = items[SerilogWebErrorKey] as Stack<Exception>;

if (errors == null || errors.Count == 0)
{
return null;
}

return errors.Peek();
}
}
}
4 changes: 3 additions & 1 deletion src/SerilogWeb.Classic/Classic/WebRequestLoggingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using Serilog;
using Serilog.Events;
using SerilogWeb.Classic.Extensions;

namespace SerilogWeb.Classic
{
Expand Down Expand Up @@ -41,7 +42,8 @@ internal void OnLogRequest(SerilogWebClassicConfiguration configuration)
if (request == null || configuration.RequestFilter(_application.Context))
return;

var error = _application.Server.GetLastError();
var error = _application.Context.GetLastSerilogWebError() ?? _application.Server.GetLastError();

var level = error != null || _application.Response.StatusCode >= 500 ? LogEventLevel.Error : configuration.RequestLoggingLevel;

if (level == LogEventLevel.Error && error == null && _application.Context.AllErrors != null)
Expand Down
3 changes: 2 additions & 1 deletion src/SerilogWeb.Classic/SerilogWeb.Classic.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Serilog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
<HintPath>..\..\packages\Serilog.2.6.0\lib\net45\Serilog.dll</HintPath>
<HintPath>..\..\packages\Serilog.2.7.1\lib\net45\Serilog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
Expand All @@ -55,6 +55,7 @@
<ItemGroup>
<Compile Include="Classic\ApplicationLifecycleModule.cs" />
<Compile Include="Classic\SerilogWebClassicConfigurationBuilder.cs" />
<Compile Include="Classic\Extensions\SerilogWebRequestExtensions.cs" />
<Compile Include="SerilogWebClassicLoggerConfigurationExtensions.cs" />
<Compile Include="Classic\WebRequestLoggingHandler.cs" />
<Compile Include="Classic\Enrichers\ClaimValueEnricher.cs" />
Expand Down
2 changes: 1 addition & 1 deletion src/SerilogWeb.Classic/SerilogWeb.Classic.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<description>Logs details of System.Web HTTP requests through Serilog.</description>
<language>en-US</language>
<projectUrl>https://github.com/serilog-web/classic</projectUrl>
<licenseUrl>https://www.apache.org/licenses/LICENSE-2.0</licenseUrl>
<license type="expression">Apache-2.0</license>
<iconUrl>https://serilog-web.github.io/pages/images/serilog-web.png</iconUrl>
<tags>serilog logging aspnet</tags>
</metadata>
Expand Down
2 changes: 1 addition & 1 deletion src/SerilogWeb.Classic/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Serilog" version="2.6.0" targetFramework="net45" />
<package id="Serilog" version="2.7.1" targetFramework="net45" />
</packages>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using SerilogWeb.Classic.Extensions;
using SerilogWeb.Classic.Tests.Support;
using Xunit;

namespace SerilogWeb.Classic.Tests.Extensions
{
public class SerilogWebRequestExtensionsTests
{
[Fact]
public void AddSerilogWebErrorCanBeRetrievedOnHttpContextBase()
{
var app = new FakeHttpApplication();
var context = app.Context;

var original = new Exception("It failed");
context.AddSerilogWebError(original);

var returned = context.GetLastSerilogWebError();

Assert.Same(original, returned);
}

[Fact]
public void GetLastSerilogWebErrorReturnsNullWhenThereIsNoError()
{
var app = new FakeHttpApplication();
var context = app.Context;

var returned = context.GetLastSerilogWebError();

Assert.Null(returned);
}

[Fact]
public void GetLastSerilogWebErrorReturnsLastAddedError()
{
var app = new FakeHttpApplication();
var context = app.Context;

var first = new Exception("It failed once");
context.AddSerilogWebError(first);

var second = new Exception("It failed twice");
context.AddSerilogWebError(second);

var returned = context.GetLastSerilogWebError();

Assert.Same(second, returned);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.6.1" />
<PackageReference Include="Serilog" Version="2.6.0" />
<PackageReference Include="Serilog" Version="2.7.1" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
</ItemGroup>
Expand Down
23 changes: 23 additions & 0 deletions test/SerilogWeb.Classic.Tests/WebRequestLoggingHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Serilog;
using Serilog.Core;
using Serilog.Events;
using SerilogWeb.Classic.Extensions;
using SerilogWeb.Classic.Tests.Support;
using Xunit;

Expand Down Expand Up @@ -475,5 +476,27 @@ public void RequestWithoutServerLastErrorButStatusCode500AreLoggedAsErrorWithLas
Assert.Equal(LogEventLevel.Error, LastEvent.Level);
Assert.Same(secondError, LastEvent.Exception);
}

[Fact]
public void RequestWithSerilogWebErrorAreLoggedAsError()
{
var error = new InvalidOperationException("Epic fail #1", new NotImplementedException());
TestContext.SimulateRequest(
(req) => { },
() =>
{
App.Context.AddSerilogWebError(error);


Assert.Null(App.Server.GetLastError());
Assert.NotNull(App.Context.GetLastSerilogWebError());

return new FakeHttpResponse();
});

Assert.NotNull(LastEvent);
Assert.Equal(LogEventLevel.Error, LastEvent.Level);
Assert.Same(error, LastEvent.Exception);
}
}
}
2 changes: 1 addition & 1 deletion test/SerilogWeb.Test/SerilogWeb.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Serilog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
<HintPath>..\..\packages\Serilog.2.6.0\lib\net45\Serilog.dll</HintPath>
<HintPath>..\..\packages\Serilog.2.7.1\lib\net45\Serilog.dll</HintPath>
</Reference>
<Reference Include="Serilog.Settings.AppSettings, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
<HintPath>..\..\packages\Serilog.Settings.AppSettings.2.1.2\lib\net45\Serilog.Settings.AppSettings.dll</HintPath>
Expand Down
2 changes: 1 addition & 1 deletion test/SerilogWeb.Test/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<packages>
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net451" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net451" developmentDependency="true" />
<package id="Serilog" version="2.6.0" targetFramework="net451" />
<package id="Serilog" version="2.7.1" targetFramework="net451" />
<package id="Serilog.Settings.AppSettings" version="2.1.2" targetFramework="net451" />
<package id="Serilog.Sinks.Trace" version="2.1.0" targetFramework="net451" />
</packages>