-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsumeWorker.cs
94 lines (85 loc) · 3.21 KB
/
ConsumeWorker.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using Net6_Demo.Helpers;
using Net6_Demo.Providers;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
namespace Net6_Demo.Workers
{
public class ConsumeWorker : IWorker
{
private readonly IModel _channel;
private readonly object _printLock = new();
public ConsumeWorker(RabbitMQHelper mq)
{
_channel = mq.GetConnection();
}
/// <summary>
/// Register event to consume queue
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task DoWork(CancellationToken cancellationToken)
{
Console.WriteLine($"{GetType().Name} doing background work.");
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
PrintLog(message);
};
_channel.BasicConsume(queue: "message",
autoAck: true,
consumer: consumer);
await Task.CompletedTask;
}
/// <summary>
/// Lazy to setup a demo log viewer, so just write on console
/// </summary>
/// <param name="message"></param>
private void PrintLog(string message)
{
try
{
var log = JsonSerializer.Deserialize<LogObject>(message);
if(log == null)
{
Console.WriteLine($"{DateTime.UtcNow} Received from RabbitMq: {message}");
return;
}
lock (_printLock)
{
Console.WriteLine($"{DateTime.UtcNow:g} Received from RabbitMq:");
switch (log.LogLevel)
{
case LogLevel.Information:
Console.ForegroundColor = ConsoleColor.Green;
break;
case LogLevel.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case LogLevel.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
Console.ForegroundColor = ConsoleColor.White;
break;
}
Console.Write(log.LogLevel);
Console.ResetColor();
Console.WriteLine($" [{log.EventId}] {log.Module}");
Console.WriteLine($" LogTxt: {log.LogData}");
if (!string.IsNullOrEmpty(log.ErrorMessage))
{
Console.WriteLine($" Error Code: {log.ErrorCode}, Message:{log.ErrorMessage}");
}
}
}
catch (Exception) //ignore
{
Console.WriteLine($"{DateTime.UtcNow} Received from RabbitMq: {message}");
}
}
}
}