Skip to content

Commit abd5ac4

Browse files
committed
Added logging generator example
1 parent acf532e commit abd5ac4

File tree

7 files changed

+120
-1
lines changed

7 files changed

+120
-1
lines changed

BlazorClientLoadingScreen/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ If you are using Blazor WebAssembly aka client-side Blazor you are faced with an
44

55
Depending on the connection of your client there is a time where basically nothing happens. The default template just has a simple "Loading..." text. So let's change that.
66

7-
Found [here](https://steven-giesel.com/update/6dc1be8f-159c-45fb-90c3-7ec87bfd7e3b)
7+
Found [here](https://steven-giesel.com/blogPost/6dc1be8f-159c-45fb-90c3-7ec87bfd7e3b)
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using BenchmarkDotNet.Attributes;
2+
using BenchmarkDotNet.Running;
3+
using LoggingSourceCodeGenerator;
4+
using Microsoft.Extensions.Logging;
5+
6+
BenchmarkRunner.Run<Benchmark>();
7+
8+
[MemoryDiagnoser]
9+
public class Benchmark
10+
{
11+
private readonly UserCreationService _service = new(new NoLogger());
12+
private readonly User _user = new("Steven", "Giesel");
13+
private readonly DateTime _now = DateTime.UtcNow;
14+
15+
[Benchmark]
16+
public void LogCreateUserBad() => _service.LogCreateUserBad(_user, _now);
17+
18+
[Benchmark]
19+
public void LogCreateUserTraditionally() => _service.LogCreateUserTraditionally(_user, _now);
20+
21+
[Benchmark]
22+
public void LogCreateUser() => _service.LogCreateUser(_user, _now);
23+
}
24+
25+
public class NoLogger : ILogger
26+
{
27+
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
28+
{ }
29+
30+
public bool IsEnabled(LogLevel logLevel) => true;
31+
32+
public IDisposable BeginScope<TState>(TState state) => default;
33+
}
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using Microsoft.Extensions.Logging;
2+
3+
namespace LoggingSourceCodeGenerator;
4+
5+
public partial class UserCreationService
6+
{
7+
private ILogger _logger;
8+
9+
public UserCreationService(ILogger logger)
10+
{
11+
_logger = logger;
12+
}
13+
14+
public void LogCreateUserBad(User user, DateTime when)
15+
{
16+
// That is the "worst" approach as you lose structured logging
17+
// Helpers like JetBrains Resharper or Rider will even warn you
18+
_logger.LogInformation($"Creating user: {user} at {when}");
19+
}
20+
21+
public void LogCreateUserTraditionally(User user, DateTime when)
22+
{
23+
_logger.LogInformation("Creating user: {User} at {When}", user, when);
24+
}
25+
26+
// The function has to be partial as the source code generator has to provide the implementation
27+
// We can also set the LogLevel and an EventId
28+
// The source code generator will automatically look for an `ILogger` field to log its stuff
29+
[LoggerMessage(Message = "Creating user: {user} at {when}", Level = LogLevel.Information, EventId = 1)]
30+
public partial void LogCreateUser(User user, DateTime when);
31+
32+
[LoggerMessage(Message = "Creating user: {user} at {when}", Level = LogLevel.Information, EventId = 1)]
33+
public static partial void LogStaticVersion(ILogger logger, User user, DateTime when);
34+
35+
public static void ExampleUsage()
36+
{
37+
var logger = LoggerFactory.Create(l => l.AddConsole()).CreateLogger(typeof(UserCreationService));
38+
var userService = new UserCreationService(logger);
39+
var user = new User("Steven", "Giesel");
40+
userService.LogCreateUser(user, DateTime.Now);
41+
}
42+
}
43+
44+
public record User(string FirstName, string LastName);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
13+
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
14+
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1" />
15+
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
16+
</ItemGroup>
17+
18+
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggingSourceCodeGenerator", "LoggingSourceCodeGenerator.csproj", "{EBDA8A5E-70DB-42D7-8A45-81B38EF8A741}"
4+
EndProject
5+
Global
6+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
7+
Debug|Any CPU = Debug|Any CPU
8+
Release|Any CPU = Release|Any CPU
9+
EndGlobalSection
10+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
11+
{EBDA8A5E-70DB-42D7-8A45-81B38EF8A741}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
12+
{EBDA8A5E-70DB-42D7-8A45-81B38EF8A741}.Debug|Any CPU.Build.0 = Debug|Any CPU
13+
{EBDA8A5E-70DB-42D7-8A45-81B38EF8A741}.Release|Any CPU.ActiveCfg = Release|Any CPU
14+
{EBDA8A5E-70DB-42D7-8A45-81B38EF8A741}.Release|Any CPU.Build.0 = Release|Any CPU
15+
EndGlobalSection
16+
EndGlobal

LoggingSourceCodeGenerator/README.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Logging Source Code Generators
2+
3+
Since .NET6 we have the possibility to define an easy way of logging common statements:
4+
5+
Meet **Compile-time logging source generators**. This article will show why we have them and how to use them. Of course a smaller benchmark will also follow.
6+
7+
Found [here](https://steven-giesel.com/blogPost/48697958-4aee-474a-8920-e266d1d7b8fa)

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Contains all of my examples from various blog posts. You can find a comprehensiv
44

55
| BlogPost | Publish Date |
66
| ---------------------------------------------------------------------------------------- | ------------ |
7+
| [Logging Source Code Generators](LoggingSourceCodeGenerator/) | 27.07.2022 |
78
| [Blazor Client - Loading Screen](BlazorClientLoadingScreen/) | 12.07.2022 |
89
| [Central nuget store for your UNO Platform App](UnoDirectoryBuildProps/) | 23.06.2022 |
910
| [ObjectPool - Rent and return some instances](ObjectPool/) | 02.06.2022 |

0 commit comments

Comments
 (0)