Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated to NET8, Added Unit Tests #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 14 additions & 3 deletions serilog-enrichers-memory.sln
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.15
# Visual Studio Version 17
VisualStudioVersion = 17.10.35013.160
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{037440DE-440B-4129-9F7A-09B42D00397E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{E9D1B5E1-DEB9-4A04-8BAB-24EC7240ADAF}"
ProjectSection(SolutionItems) = preProject
Build.ps1 = Build.ps1
NuGet.Config = NuGet.Config
README.md = README.md
assets\SerilogMemory.snk = assets\SerilogMemory.snk
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Enrichers.Memory", "src\Serilog.Enrichers.Memory\Serilog.Enrichers.Memory.csproj", "{2312A998-5E53-4355-9CB6-6014252B3E88}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{F1A28E03-3590-4F6F-B0D7-7D3008BCDF23}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serilog.Enrichers.Memory.Tests", "tests\Serilog.Enrichers.Memory.Tests\Serilog.Enrichers.Memory.Tests.csproj", "{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -25,11 +28,19 @@ Global
{2312A998-5E53-4355-9CB6-6014252B3E88}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2312A998-5E53-4355-9CB6-6014252B3E88}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2312A998-5E53-4355-9CB6-6014252B3E88}.Release|Any CPU.Build.0 = Release|Any CPU
{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{2312A998-5E53-4355-9CB6-6014252B3E88} = {037440DE-440B-4129-9F7A-09B42D00397E}
{CC27194E-C8D2-4B1D-ACC5-28F9BDF49546} = {F1A28E03-3590-4F6F-B0D7-7D3008BCDF23}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CF4B9AB9-DF05-417C-A8DE-CEBD1695A26B}
EndGlobalSection
EndGlobal
37 changes: 19 additions & 18 deletions src/Serilog.Enrichers.Memory/Enrichers/MemoryUsageEnricher.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2017 Josh Schreuder
// Copyright 2017, 2024 Josh Schreuder
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,26 +16,27 @@
using Serilog.Core;
using Serilog.Events;

namespace Serilog.Enrichers
// ReSharper disable CheckNamespace
namespace Serilog.Enrichers;
// ReSharper restore CheckNamespace

/// <summary>
/// Enriches log events with a MemoryUsage property containing an estimation of the current process' memory usage in bytes.
/// </summary>
public class MemoryUsageEnricher : ILogEventEnricher
{
/// <summary>
/// Enriches log events with a MemoryUsage property containing an estimation of the current process' memory usage in bytes.
/// The property name added to enriched log events.
/// </summary>
public class MemoryUsageEnricher : ILogEventEnricher
{
/// <summary>
/// The property name added to enriched log events.
/// </summary>
public const string MemoryUsagePropertyName = "MemoryUsage";
public const string MemoryUsagePropertyName = "MemoryUsage";

/// <summary>
/// Enrich the log event.
/// </summary>
/// <param name="logEvent">The log event to enrich.</param>
/// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(MemoryUsagePropertyName, GC.GetTotalMemory(false)));
}
/// <summary>
/// Enrich the log event.
/// </summary>
/// <param name="logEvent">The log event to enrich.</param>
/// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(MemoryUsagePropertyName, GC.GetTotalMemory(false)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@
using Serilog.Configuration;
using Serilog.Enrichers;

namespace Serilog
// ReSharper disable CheckNamespace
namespace Serilog;
// ReSharper restore CheckNamespace

/// <summary>
/// Extends <see cref="LoggerConfiguration"/> to add enrichers related to memory.
/// capabilities.
/// </summary>
public static class ProcessLoggerConfigurationExtensions
{
/// <summary>
/// Extends <see cref="LoggerConfiguration"/> to add enrichers related to memory.
/// capabilities.
/// Enrich log events with memory usage/>.
/// </summary>
public static class ProcessLoggerConfigurationExtensions
{
/// <summary>
/// Enrich log events with memory usage/>.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithMemoryUsage(
this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With<MemoryUsageEnricher>();
}
}
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithMemoryUsage(
this LoggerEnrichmentConfiguration enrichmentConfiguration) =>
enrichmentConfiguration == null
? throw new ArgumentNullException(nameof(enrichmentConfiguration))
: enrichmentConfiguration.With<MemoryUsageEnricher>();
}
11 changes: 4 additions & 7 deletions src/Serilog.Enrichers.Memory/Serilog.Enrichers.Memory.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>The memory enricher for Serilog.</Description>
<VersionPrefix>1.0.3</VersionPrefix>
<Authors>Josh Schreuder</Authors>
<TargetFrameworks>net45;netstandard1.3;netcoreapp2.0;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net8.0</TargetFrameworks>
<AssemblyName>Serilog.Enrichers.Memory</AssemblyName>
<AssemblyOriginatorKeyFile>../../assets/SerilogMemory.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
Expand All @@ -15,15 +14,13 @@
<PackageProjectUrl>https://github.com/JoshSchreuder/serilog-enrichers-memory</PackageProjectUrl>
<PackageLicenseUrl>http://www.apache.org/licenses/LICENSE-2.0</PackageLicenseUrl>
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<Version>1.0.4</Version>
<Version>1.1.0</Version>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.0.0" />
<PackageReference Include="Serilog" Version="4.0.0" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
</Project>
</Project>
66 changes: 66 additions & 0 deletions tests/Serilog.Enrichers.Memory.Tests/MemoryUsageEnricherTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Diagnostics.CodeAnalysis;
using Moq;
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;

namespace Serilog.Enrichers.Memory.Tests;

[ExcludeFromCodeCoverage]
public class MemoryUsageEnricherTests
{
[Fact]
public void Enrich_ShouldAddMemoryUsageProperty()
{
// Arrange
var enricher = new MemoryUsageEnricher();
var logEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, new MessageTemplate(new List<MessageTemplateToken>()), new List<LogEventProperty>());
var propertyFactoryMock = new Mock<ILogEventPropertyFactory>();
propertyFactoryMock.Setup(x => x.CreateProperty(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>()))
.Returns((string name, object value, bool destructureObjects) => new LogEventProperty(name, new ScalarValue(value)));

// Act
enricher.Enrich(logEvent, propertyFactoryMock.Object);

// Assert
var memoryUsageProperty = logEvent.Properties.FirstOrDefault(p => p.Key == MemoryUsageEnricher.MemoryUsagePropertyName);
Assert.NotNull(memoryUsageProperty.Value);
}

[Fact]
public void Enrich_ShouldAddMemoryUsageWithPositiveValue()
{
// Arrange
var enricher = new MemoryUsageEnricher();
var logEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, new MessageTemplate(new List<MessageTemplateToken>()), new List<LogEventProperty>());
var propertyFactoryMock = new Mock<ILogEventPropertyFactory>();
propertyFactoryMock.Setup(x => x.CreateProperty(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>()))
.Returns((string name, object value, bool destructureObjects) => new LogEventProperty(name, new ScalarValue(value)));

// Act
enricher.Enrich(logEvent, propertyFactoryMock.Object);

// Assert
var memoryUsageProperty = logEvent.Properties.FirstOrDefault(p => p.Key == MemoryUsageEnricher.MemoryUsagePropertyName);
Assert.True(memoryUsageProperty.Value is ScalarValue scalarValue && scalarValue.Value is long && (long)scalarValue.Value > 0);
}

[Fact]
public void Enrich_ShouldNotAddMemoryUsagePropertyTwice()
{
// Arrange
var enricher = new MemoryUsageEnricher();
var logEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, new MessageTemplate(new List<MessageTemplateToken>()), new List<LogEventProperty>());
var propertyFactoryMock = new Mock<ILogEventPropertyFactory>();
propertyFactoryMock.Setup(x => x.CreateProperty(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>()))
.Returns((string name, object value, bool destructureObjects) => new LogEventProperty(name, new ScalarValue(value)));

// Act
enricher.Enrich(logEvent, propertyFactoryMock.Object);
enricher.Enrich(logEvent, propertyFactoryMock.Object); // Enrich a second time

// Assert
var memoryUsageProperties = logEvent.Properties.Where(p => p.Key == MemoryUsageEnricher.MemoryUsagePropertyName);
Assert.Single(memoryUsageProperties);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Diagnostics.CodeAnalysis;
using Moq;
using Serilog.Configuration;

namespace Serilog.Enrichers.Memory.Tests;

[ExcludeFromCodeCoverage]
public class ProcessLoggerConfigurationExtensionsTests
{
[Fact]
public void WithMemoryUsage_ThrowsArgumentNullException_WhenEnrichmentConfigurationIsNull()
{
// Arrange
LoggerEnrichmentConfiguration enrichmentConfiguration = null;

// Act & Assert
Assert.Throws<ArgumentNullException>(() => ProcessLoggerConfigurationExtensions.WithMemoryUsage(enrichmentConfiguration));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.Enrichers.Memory\Serilog.Enrichers.Memory.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

</Project>