-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundLogger.cs
45 lines (38 loc) · 1.28 KB
/
BackgroundLogger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
public class BackgroundLogger : IHostedService, IDisposable
{
private readonly ILogger<BackgroundLogger> logger;
private Timer timer;
private int number;
public BackgroundLogger(ILogger<BackgroundLogger> logger)
{
this.logger = logger;
}
void WriteTestLogEntries(ILogger logger){
Interlocked.Increment(ref number);
using(logger.BeginScope("root-scope")){
logger.LogInformation($"Logging Number {number} with a template string");
logger.LogInformation("Logging Number {number} with an arg", number);
using(logger.BeginScope(new {Task="DemoTask", ID=42})){
logger.LogInformation("Logging String from nested scope", number);
}
}
}
public void Dispose()
{
timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
timer = new Timer(o => WriteTestLogEntries(logger), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}