Skip to content
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 Build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ if(Test-Path .\artifacts) {

$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"]
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "main" -and $revision -ne "local"]

echo "build: Version suffix is $suffix"

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

For an example, see [the _dotnetconf_ deep dive session](https://channel9.msdn.com/Events/dotnetConf/2016/ASPNET-Core--deep-dive-on-building-a-real-website-with-todays-bits).

![Screenshot](https://github.com/datalust/seq-extensions-logging/blob/master/asset/screenshot.png?raw=true)
![Screenshot](https://raw.githubusercontent.com/datalust/seq-extensions-logging/dev/asset/screenshot.png)

This package makes it a one-liner to configure ASP.NET Core logging with Seq.

Expand Down
4 changes: 2 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ artifacts:
deploy:
- provider: NuGet
api_key:
secure: 94298ksNMfJ2LkBV3Lw9o4JVzKvVPPMHF91p0XjsBhNWVeMX2NeROX4fpio6BsQy
secure: QYBIGd/prsJud8qlJati9FdnXbiA0VvyxO1z0TUiQV3svdpbD7ZaykJFTYKyIdQq
skip_symbols: true
on:
branch: /^(master|dev)$/
branch: /^(main|dev)$/
Binary file added asset/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion example/ConsoleApplication/ConsoleApplication.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
9 changes: 6 additions & 3 deletions example/WebApplication/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace WebApplication
{
public class Startup
{
public Startup(IHostingEnvironment env)
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
Expand All @@ -23,6 +25,8 @@ public Startup(IHostingEnvironment env)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(Configuration.GetSection("MvcOptions"));

services.AddLogging(loggingBuilder =>
{
// Add the Seq logger, with configuration from appsettings.json
Expand All @@ -37,12 +41,11 @@ public void ConfigureServices(IServiceCollection services)
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
Expand Down
8 changes: 3 additions & 5 deletions example/WebApplication/WebApplication.csproj
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>WebApplication</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>WebApplication</PackageId>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
</PropertyGroup>

<ItemGroup>
Expand All @@ -19,8 +17,8 @@
<ProjectReference Include="..\..\src\Seq.Extensions.Logging\Seq.Extensions.Logging.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<ItemGroup Condition="$(TargetFramework) == 'netcoreapp2.1'">
<PackageReference Include="Microsoft.AspNetCore.All" />
</ItemGroup>

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
Expand Down
3 changes: 3 additions & 0 deletions example/WebApplication/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,8 @@
"ServerUrl": "http://localhost:5341",
"ApiKey": ""
}
},
"MvcOptions": {
"EnableEndpointRouting": false
}
}
6 changes: 6 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "5.0.100",
"rollForward": "latestFeature"
}
}
3 changes: 3 additions & 0 deletions seq-extensions-logging.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "global", "global", "{B0D573
Build.ps1 = Build.ps1
LICENSE = LICENSE
README.md = README.md
global.json = global.json
.gitattributes = .gitattributes
.gitignore = .gitignore
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{D54DE844-AC36-4872-928F-5F573D41ACAE}"
Expand Down
3 changes: 3 additions & 0 deletions seq-extensions-logging.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"&gt;&lt;ExtraRule Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=appsettings/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Datalust/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Enricher/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Serilog/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
11 changes: 8 additions & 3 deletions src/Seq.Extensions.Logging/Seq.Extensions.Logging.csproj
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Add centralized structured log collection to ASP.NET Core apps with one line of code.</Description>
<VersionPrefix>5.0.0</VersionPrefix>
<Authors>Datalust and Contributors</Authors>
<TargetFrameworks>net462;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net462;netstandard2.0;net5.0</TargetFrameworks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyOriginatorKeyFile>../../asset/seqext.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageTags>aspnet;logging</PackageTags>
<PackageIconUrl>https://datalust.co/images/nuget/seq.png</PackageIconUrl>
<PackageIcon>icon.png</PackageIcon>
<PackageProjectUrl>https://github.com/datalust/seq-extensions-logging</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<RootNamespace/>
</PropertyGroup>

<ItemGroup>
Expand All @@ -22,4 +23,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="2.1.0" />
</ItemGroup>

<ItemGroup>
<None Include="..\..\asset\icon.png" Pack="true" Visible="false" PackagePath="" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2016 Datalust
// Copyright 2016-2020 Datalust and Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -23,15 +23,11 @@ class ExceptionDataEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.Exception == null)
var exceptionData = logEvent.Exception?.GetBaseException().Data;
if (exceptionData == null || exceptionData.Count == 0)
return;

var exception = logEvent.Exception.GetBaseException();

if (exception.Data == null || exception.Data.Count == 0)
return;

var data = exception.Data
var data = exceptionData
.Cast<DictionaryEntry>()
.Where(e => e.Key is string)
.Select(e => propertyFactory.CreateProperty((string)e.Key, e.Value));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using Serilog.Events;
Expand All @@ -15,14 +14,16 @@ namespace Serilog.Extensions.Logging
/// An <see cref="ILoggerProvider"/> that pipes events through Serilog.
/// </summary>
[ProviderAlias("Seq")]
class SerilogLoggerProvider : ILoggerProvider, ILogEventEnricher
class SerilogLoggerProvider : ILoggerProvider, ILogEventEnricher, ISupportExternalScope
{
internal const string OriginalFormatPropertyName = "{OriginalFormat}";
internal const string ScopePropertyName = "Scope";

readonly Logger _logger;
readonly Action _dispose;

IExternalScopeProvider _scopeProvider;

/// <summary>
/// Construct a <see cref="SerilogLoggerProvider"/>.
/// </summary>
Expand All @@ -44,44 +45,39 @@ public FrameworkLogger CreateLogger(string name)

public IDisposable BeginScope<T>(T state)
{
return new SerilogLoggerScope(this, state);
return _scopeProvider?.Push(state);
}

/// <inheritdoc />
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
List<LogEventPropertyValue> scopeItems = null;
for (var scope = CurrentScope; scope != null; scope = scope.Parent)
{
LogEventPropertyValue scopeItem;
scope.EnrichAndCreateScopeItem(logEvent, propertyFactory, out scopeItem);
var scopeItems = new List<LogEventPropertyValue>();

_scopeProvider?.ForEachScope((scopeState, state) =>
{
SerilogLoggerScope.EnrichAndCreateScopeItem(scopeState, state.logEvent, state.propertyFactory, out var scopeItem);

if (scopeItem != null)
{
scopeItems = scopeItems ?? new List<LogEventPropertyValue>();
scopeItems.Add(scopeItem);
state.scopeItems.Add(scopeItem);
}
}
}, (logEvent, propertyFactory, scopeItems));

if (scopeItems != null)
if (scopeItems.Count > 0)
{
scopeItems.Reverse();
logEvent.AddPropertyIfAbsent(new LogEventProperty(ScopePropertyName, new SequenceValue(scopeItems)));
}
}

readonly AsyncLocal<SerilogLoggerScope> _value = new AsyncLocal<SerilogLoggerScope>();

internal SerilogLoggerScope CurrentScope
{
get => _value.Value;
set => _value.Value = value;
}

/// <inheritdoc />
public void Dispose()
{
_dispose();
}

public void SetScopeProvider(IExternalScopeProvider scopeProvider)
{
_scopeProvider = scopeProvider;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,68 +1,33 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Modifications Copyright (c) Datalust and Contributors
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using Serilog.Core;
using Serilog.Events;

namespace Serilog.Extensions.Logging
{
class SerilogLoggerScope : IDisposable
static class SerilogLoggerScope
{
const string NoName = "None";

readonly SerilogLoggerProvider _provider;
readonly object _state;

// An optimization only, no problem if there are data races on this.
bool _disposed;

public SerilogLoggerScope(SerilogLoggerProvider provider, object state)
{
_provider = provider;
_state = state;

Parent = _provider.CurrentScope;
_provider.CurrentScope = this;
}

public SerilogLoggerScope Parent { get; }

public void Dispose()
{
if (!_disposed)
{
_disposed = true;

// In case one of the parent scopes has been disposed out-of-order, don't
// just blindly reinstate our own parent.
for (var scan = _provider.CurrentScope; scan != null; scan = scan.Parent)
{
if (ReferenceEquals(scan, this))
_provider.CurrentScope = Parent;
}
}
}

public void EnrichAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, out LogEventPropertyValue scopeItem)

public static void EnrichAndCreateScopeItem(object state, LogEvent logEvent, ILogEventPropertyFactory propertyFactory, out LogEventPropertyValue scopeItem)
{
if (_state == null)
if (state == null)
{
scopeItem = null;
return;
}

var stateProperties = _state as IEnumerable<KeyValuePair<string, object>>;
if (stateProperties != null)
if (state is IEnumerable<KeyValuePair<string, object>> stateProperties)
{
scopeItem = null; // Unless it's `FormattedLogValues`, these are treated as property bags rather than scope items.

foreach (var stateProperty in stateProperties)
{
if (stateProperty.Key == SerilogLoggerProvider.OriginalFormatPropertyName && stateProperty.Value is string)
{
scopeItem = new ScalarValue(_state.ToString());
scopeItem = new ScalarValue(state.ToString());
continue;
}

Expand All @@ -76,12 +41,12 @@ public void EnrichAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory
}

var property = propertyFactory.CreateProperty(key, stateProperty.Value, destructureObject);
logEvent.AddPropertyIfAbsent(property);
logEvent.AddOrUpdateProperty(property);
}
}
else
{
scopeItem = propertyFactory.CreateProperty(NoName, _state).Value;
scopeItem = propertyFactory.CreateProperty(NoName, state).Value;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net472;netcoreapp3.0</TargetFrameworks>
<TargetFrameworks>net472;netcoreapp3.1;net5.0</TargetFrameworks>
<AssemblyOriginatorKeyFile>../../asset/seqext.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
Expand All @@ -20,8 +20,4 @@
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>

<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>

</Project>
Loading