Skip to content

Commit 84cf681

Browse files
authored
Split logging examples to ASP.NET web app and MS.EXT.Hosting console projects (#598)
1 parent 72593b4 commit 84cf681

File tree

9 files changed

+235
-74
lines changed

9 files changed

+235
-74
lines changed

Akka.Hosting.sln

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Persistence.Hosting",
3232
EndProject
3333
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Persistence.Hosting.Tests", "src\Akka.Persistence.Hosting.Tests\Akka.Persistence.Hosting.Tests.csproj", "{876DE0B6-5FA8-4F79-876E-92EF5E9E7011}"
3434
EndProject
35-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Hosting.LoggingDemo", "src\Examples\Akka.Hosting.LoggingDemo\Akka.Hosting.LoggingDemo.csproj", "{4F79325B-9EE7-4501-800F-7A1F8DFBCC80}"
35+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Hosting.Asp.LoggingDemo", "src\Examples\Akka.Hosting.Asp.LoggingDemo\Akka.Hosting.Asp.LoggingDemo.csproj", "{4F79325B-9EE7-4501-800F-7A1F8DFBCC80}"
3636
EndProject
3737
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Hosting.TestKit", "src\Akka.Hosting.TestKit\Akka.Hosting.TestKit.csproj", "{E28D4F3C-6C34-497B-BDC8-F2B3EA8BA309}"
3838
EndProject
@@ -42,6 +42,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Akka.Hosting.API.Tests", "s
4242
EndProject
4343
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Remote.Hosting.Tests", "src\Akka.Remote.Hosting.Tests\Akka.Remote.Hosting.Tests.csproj", "{11062839-0674-4DF9-AB8B-B7901A564ADC}"
4444
EndProject
45+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Hosting.LoggingDemo", "src\Examples\Akka.Hosting.LoggingDemo\Akka.Hosting.LoggingDemo.csproj", "{298D7727-FDC6-49B2-9030-CC7F0E09B0B8}"
46+
EndProject
4547
Global
4648
GlobalSection(SolutionConfigurationPlatforms) = preSolution
4749
Debug|Any CPU = Debug|Any CPU
@@ -104,13 +106,18 @@ Global
104106
{11062839-0674-4DF9-AB8B-B7901A564ADC}.Debug|Any CPU.Build.0 = Debug|Any CPU
105107
{11062839-0674-4DF9-AB8B-B7901A564ADC}.Release|Any CPU.ActiveCfg = Release|Any CPU
106108
{11062839-0674-4DF9-AB8B-B7901A564ADC}.Release|Any CPU.Build.0 = Release|Any CPU
109+
{298D7727-FDC6-49B2-9030-CC7F0E09B0B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
110+
{298D7727-FDC6-49B2-9030-CC7F0E09B0B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
111+
{298D7727-FDC6-49B2-9030-CC7F0E09B0B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
112+
{298D7727-FDC6-49B2-9030-CC7F0E09B0B8}.Release|Any CPU.Build.0 = Release|Any CPU
107113
EndGlobalSection
108114
GlobalSection(SolutionProperties) = preSolution
109115
HideSolutionNode = FALSE
110116
EndGlobalSection
111117
GlobalSection(NestedProjects) = preSolution
112118
{5F6A7BE8-6906-46CE-BA1C-72EA11EFA33B} = {EFA970FF-6BCC-4C38-84D8-324D40F2BF03}
113119
{4F79325B-9EE7-4501-800F-7A1F8DFBCC80} = {EFA970FF-6BCC-4C38-84D8-324D40F2BF03}
120+
{298D7727-FDC6-49B2-9030-CC7F0E09B0B8} = {EFA970FF-6BCC-4C38-84D8-324D40F2BF03}
114121
EndGlobalSection
115122
GlobalSection(ExtensibilityGlobals) = postSolution
116123
SolutionGuid = {B99E6BB8-642A-4A68-86DF-69567CBA700A}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
<PropertyGroup>
3+
<TargetFramework>net6.0</TargetFramework>
4+
<Nullable>enable</Nullable>
5+
<ImplicitUsings>enable</ImplicitUsings>
6+
<IsPackable>false</IsPackable>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<ProjectReference Include="..\..\Akka.Cluster.Hosting\Akka.Cluster.Hosting.csproj" />
11+
</ItemGroup>
12+
13+
<ItemGroup>
14+
<None Update="appsettings.json">
15+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
16+
</None>
17+
<None Update="appsettings.Development.json">
18+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
19+
</None>
20+
</ItemGroup>
21+
22+
</Project>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
namespace Akka.Hosting.Asp.LoggingDemo;
2+
3+
public struct Echo{}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
using Akka.Hosting;
2+
using Akka.Actor;
3+
using Akka.Actor.Dsl;
4+
using Akka.Cluster.Hosting;
5+
using Akka.Event;
6+
using Akka.Hosting.Asp.LoggingDemo;
7+
using Akka.Remote.Hosting;
8+
using LogLevel = Akka.Event.LogLevel;
9+
10+
var builder = WebApplication.CreateBuilder(args);
11+
builder.Services.AddAkka("MyActorSystem", (configurationBuilder, serviceProvider) =>
12+
{
13+
configurationBuilder
14+
.ConfigureLoggers(setup =>
15+
{
16+
// This sets the minimum log level
17+
setup.LogLevel = LogLevel.DebugLevel;
18+
19+
// Clear all loggers (remove the default console logger)
20+
setup.ClearLoggers();
21+
22+
// Add the ILoggerFactory logger
23+
// NOTE:
24+
// - You can also use setup.AddLogger<LoggerFactoryLogger>();
25+
// - To use a specific ILoggerFactory instance, you can use setup.AddLoggerFactory(myILoggerFactory);
26+
setup.AddLoggerFactory();
27+
})
28+
.WithRemoting("localhost", 8110)
29+
.WithClustering(new ClusterOptions {
30+
Roles = ["myRole"],
31+
SeedNodes = ["akka.tcp://MyActorSystem@localhost:8110"]
32+
})
33+
.WithActors((system, registry) =>
34+
{
35+
var echo = system.ActorOf(act =>
36+
{
37+
act.ReceiveAny((o, context) =>
38+
{
39+
Logging.GetLogger(context.System, "echo").Info($"Actor received {o}");
40+
context.Sender.Tell($"{context.Self} rcv {o}");
41+
});
42+
}, "echo");
43+
registry.TryRegister<Echo>(echo); // register for DI
44+
});
45+
});
46+
47+
var app = builder.Build();
48+
49+
app.MapGet("/", async (context) =>
50+
{
51+
var echo = context.RequestServices.GetRequiredService<ActorRegistry>().Get<Echo>();
52+
var body = await echo.Ask<string>(context.TraceIdentifier, context.RequestAborted).ConfigureAwait(false);
53+
await context.Response.WriteAsync(body);
54+
});
55+
56+
app.Run();
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft": "Warning",
6+
"Microsoft.Hosting.Lifetime": "Information"
7+
}
8+
}
9+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft": "Warning",
6+
"Microsoft.Hosting.Lifetime": "Information",
7+
"Akka": "Debug"
8+
}
9+
},
10+
"AllowedHosts": "*"
11+
}
Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
1-
<Project Sdk="Microsoft.NET.Sdk.Web">
2-
<PropertyGroup>
3-
<TargetFramework>net6.0</TargetFramework>
4-
<Nullable>enable</Nullable>
5-
<ImplicitUsings>enable</ImplicitUsings>
6-
<IsPackable>false</IsPackable>
7-
</PropertyGroup>
1+
<Project Sdk="Microsoft.NET.Sdk">
82

9-
<ItemGroup>
10-
<ProjectReference Include="..\..\Akka.Cluster.Hosting\Akka.Cluster.Hosting.csproj" />
11-
</ItemGroup>
3+
<PropertyGroup>
4+
<TargetFramework>net6.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<IsPackable>false</IsPackable>
8+
<OutputType>Exe</OutputType>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0"/>
13+
</ItemGroup>
14+
15+
<ItemGroup>
16+
<ProjectReference Include="..\..\Akka.Cluster.Hosting\Akka.Cluster.Hosting.csproj" />
17+
</ItemGroup>
18+
19+
<ItemGroup>
20+
<None Update="appsettings.json">
21+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
22+
</None>
23+
<None Update="appsettings.Development.json">
24+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
25+
</None>
26+
</ItemGroup>
1227

13-
<ItemGroup>
14-
<PackageReference Include="Akka.Logger.Serilog" Version="1.5.25" />
15-
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
16-
</ItemGroup>
1728
</Project>

src/Examples/Akka.Hosting.LoggingDemo/Program.cs

Lines changed: 46 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,68 +3,55 @@
33
using Akka.Actor.Dsl;
44
using Akka.Cluster.Hosting;
55
using Akka.Event;
6-
using Akka.Hosting.Logging;
76
using Akka.Hosting.LoggingDemo;
8-
using Akka.Logger.Serilog;
97
using Akka.Remote.Hosting;
10-
using Serilog;
8+
using Microsoft.Extensions.DependencyInjection;
9+
using Microsoft.Extensions.Hosting;
1110
using LogLevel = Akka.Event.LogLevel;
1211

13-
Serilog.Log.Logger = new LoggerConfiguration()
14-
.WriteTo.Console()
15-
.MinimumLevel.Debug()
16-
.CreateLogger();
12+
var builder = Host.CreateDefaultBuilder(args);
1713

18-
var builder = WebApplication.CreateBuilder(args);
19-
20-
builder.Services.AddAkka("MyActorSystem", (configurationBuilder, serviceProvider) =>
21-
{
22-
configurationBuilder
23-
.ConfigureLoggers(setup =>
24-
{
25-
// Example: This sets the minimum log level
26-
setup.LogLevel = LogLevel.DebugLevel;
27-
28-
// Example: Clear all loggers
29-
setup.ClearLoggers();
30-
31-
// Example: Add the default logger
32-
// NOTE: You can also use setup.AddLogger<DefaultLogger>();
33-
setup.AddDefaultLogger();
34-
35-
// Example: Add the ILoggerFactory logger
36-
// NOTE:
37-
// - You can also use setup.AddLogger<LoggerFactoryLogger>();
38-
// - To use a specific ILoggerFactory instance, you can use setup.AddLoggerFactory(myILoggerFactory);
39-
setup.AddLoggerFactory();
40-
41-
// Example: Adding a serilog logger
42-
//setup.AddLogger<SerilogLogger>(); // TODO: add back once upgraded to v1.5 APIs
43-
})
44-
.WithRemoting("localhost", 8110)
45-
.WithClustering(new ClusterOptions(){ Roles = new[]{ "myRole" },
46-
SeedNodes = new[]{ "akka.tcp://MyActorSystem@localhost:8110" }})
47-
.WithActors((system, registry) =>
48-
{
49-
var echo = system.ActorOf(act =>
14+
await builder
15+
.ConfigureServices(services =>
16+
{
17+
services
18+
.AddSingleton<WorkerService>()
19+
.AddHostedService<WorkerService>()
20+
.AddAkka("MyActorSystem", (configurationBuilder, serviceProvider) =>
5021
{
51-
act.ReceiveAny((o, context) =>
52-
{
53-
Logging.GetLogger(context.System, "echo").Info($"Actor received {o}");
54-
context.Sender.Tell($"{context.Self} rcv {o}");
55-
});
56-
}, "echo");
57-
registry.TryRegister<Echo>(echo); // register for DI
58-
});
59-
});
60-
61-
var app = builder.Build();
62-
63-
app.MapGet("/", async (context) =>
64-
{
65-
var echo = context.RequestServices.GetRequiredService<ActorRegistry>().Get<Echo>();
66-
var body = await echo.Ask<string>(context.TraceIdentifier, context.RequestAborted).ConfigureAwait(false);
67-
await context.Response.WriteAsync(body);
68-
});
69-
70-
app.Run();
22+
configurationBuilder
23+
.ConfigureLoggers(setup =>
24+
{
25+
// This sets the minimum log level
26+
setup.LogLevel = LogLevel.DebugLevel;
27+
28+
// Clear all loggers (remove the default console logger)
29+
setup.ClearLoggers();
30+
31+
// Add the ILoggerFactory logger
32+
// NOTE:
33+
// - You can also use setup.AddLogger<LoggerFactoryLogger>();
34+
// - To use a specific ILoggerFactory instance, you can use setup.AddLoggerFactory(myILoggerFactory);
35+
setup.AddLoggerFactory();
36+
})
37+
.WithRemoting("localhost", 8110)
38+
.WithClustering(new ClusterOptions {
39+
Roles = ["myRole"],
40+
SeedNodes = ["akka.tcp://MyActorSystem@localhost:8110"]
41+
})
42+
.WithActors((system, registry) =>
43+
{
44+
var echo = system.ActorOf(act =>
45+
{
46+
act.ReceiveAny((o, context) =>
47+
{
48+
Logging.GetLogger(context.System, "echo").Info($"Actor received {o}");
49+
context.Sender.Tell($"{context.Self} rcv {o}");
50+
});
51+
}, "echo");
52+
registry.TryRegister<Echo>(echo); // register for DI
53+
});
54+
});
55+
})
56+
.UseConsoleLifetime()
57+
.RunConsoleAsync();
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using Akka.Actor;
2+
using Microsoft.Extensions.Hosting;
3+
using Microsoft.Extensions.Logging;
4+
5+
namespace Akka.Hosting.LoggingDemo;
6+
7+
public class WorkerService: IHostedService
8+
{
9+
private readonly ILogger<WorkerService> _logger;
10+
private readonly IRequiredActor<Echo> _reqEcho;
11+
private readonly CancellationTokenSource _cancellationTokenSource;
12+
private Task? _timerTask;
13+
14+
public WorkerService(IRequiredActor<Echo> reqActor, ILogger<WorkerService> logger)
15+
{
16+
_reqEcho = reqActor;
17+
_logger = logger;
18+
_cancellationTokenSource = new CancellationTokenSource();
19+
}
20+
21+
public Task StartAsync(CancellationToken cancellationToken)
22+
{
23+
_timerTask = StartTimerTask();
24+
return Task.CompletedTask;
25+
}
26+
27+
public async Task StopAsync(CancellationToken cancellationToken)
28+
{
29+
_cancellationTokenSource.Cancel();
30+
if(_timerTask != null)
31+
await _timerTask;
32+
}
33+
34+
private async Task StartTimerTask()
35+
{
36+
var echoActor = await _reqEcho.GetAsync();
37+
var periodicTimer = new PeriodicTimer(TimeSpan.FromSeconds(2));
38+
39+
try
40+
{
41+
while (true)
42+
{
43+
if (await periodicTimer.WaitForNextTickAsync(_cancellationTokenSource.Token))
44+
{
45+
var response = await echoActor.Ask<string>(Guid.NewGuid().ToString(), _cancellationTokenSource.Token);
46+
_logger.LogInformation(response);
47+
}
48+
}
49+
}
50+
catch
51+
{
52+
// no-op
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)