forked from dotnet/aspire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAspireRabbitMQLoggingTests.cs
254 lines (205 loc) · 8.96 KB
/
AspireRabbitMQLoggingTests.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using Aspire.Components.Common.Tests;
using Aspire.Hosting.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using RabbitMQ.Client;
using Testcontainers.RabbitMq;
using Xunit;
#if RABBITMQ_V6
using RabbitMQ.Client.Logging;
#else
using System.Reflection;
#endif
namespace Aspire.RabbitMQ.Client.Tests;
public class AspireRabbitMQLoggingTests
{
/// <summary>
/// Tests that the RabbitMQ client logs are forwarded to the M.E.Logging correctly in an end-to-end scenario.
///
/// The easiest way to ensure a log is written is to start the RabbitMQ container, establish the connection,
/// and then stop the container. This will cause the RabbitMQ client to log an error message.
/// </summary>
[Fact]
[RequiresDocker]
public async Task EndToEndLoggingTest()
{
await using var rabbitMqContainer = new RabbitMqBuilder()
.WithImage($"{ComponentTestConstants.AspireTestContainerRegistry}/{RabbitMQContainerImageTags.Image}:{RabbitMQContainerImageTags.Tag}")
.Build();
await rabbitMqContainer.StartAsync();
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Configuration.AddInMemoryCollection([
new KeyValuePair<string, string?>("ConnectionStrings:messaging", rabbitMqContainer.GetConnectionString())
]);
builder.AddRabbitMQClient("messaging");
var tsc = new TaskCompletionSource();
var logger = new TestLogger();
logger.LoggedMessage = () =>
{
// wait for at least 2 logs to be written
if (logger.Logs.Count >= 2)
{
tsc.SetResult();
}
};
builder.Services.AddSingleton<ILoggerProvider>(sp => new LoggerProvider(logger));
using var host = builder.Build();
using var connection = host.Services.GetRequiredService<IConnection>();
await rabbitMqContainer.StopAsync();
await rabbitMqContainer.DisposeAsync();
await tsc.Task.WaitAsync(TimeSpan.FromMinutes(1));
var logs = logger.Logs.ToArray();
Assert.True(logs.Length >= 2, "Should be at least 2 logs written.");
Assert.Contains(logs, l => l.Level == LogLevel.Information && l.Message == "Performing automatic recovery");
Assert.Contains(logs, l => l.Level == LogLevel.Error && l.Message == "Connection recovery exception.");
}
[Fact]
public void TestInfoAndWarn()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Services.AddSingleton<RabbitMQEventSourceLogForwarder>();
var logger = new TestLogger();
builder.Services.AddSingleton<ILoggerProvider>(sp => new LoggerProvider(logger));
using var host = builder.Build();
host.Services.GetRequiredService<RabbitMQEventSourceLogForwarder>().Start();
var message = "This is an informational message.";
LogInfo(message);
var logs = logger.Logs.ToArray();
Assert.Single(logs);
Assert.Equal(LogLevel.Information, logs[0].Level);
Assert.Equal(message, logs[0].Message);
var warningMessage = "This is a warning message.";
LogWarn(warningMessage);
logs = logger.Logs.ToArray();
Assert.Equal(2, logs.Length);
Assert.Equal(LogLevel.Warning, logs[1].Level);
Assert.Equal(warningMessage, logs[1].Message);
}
[Fact]
public void TestExceptionWithoutInnerException()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Services.AddSingleton<RabbitMQEventSourceLogForwarder>();
var logger = new TestLogger();
builder.Services.AddSingleton<ILoggerProvider>(sp => new LoggerProvider(logger));
using var host = builder.Build();
host.Services.GetRequiredService<RabbitMQEventSourceLogForwarder>().Start();
var exceptionMessage = "Test exception";
Exception testException;
try
{
throw new InvalidOperationException(exceptionMessage);
}
catch (Exception ex)
{
testException = ex;
}
Assert.NotNull(testException);
var logMessage = "This is an error message.";
LogError(logMessage, testException);
var logs = logger.Logs.ToArray();
Assert.Single(logs);
Assert.Equal(LogLevel.Error, logs[0].Level);
Assert.Equal(logMessage, logs[0].Message);
var errorEvent = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logs[0].State);
Assert.Equal(3, errorEvent.Count);
Assert.Equal("exception.type", errorEvent[0].Key);
Assert.Equal("System.InvalidOperationException", errorEvent[0].Value);
Assert.Equal("exception.message", errorEvent[1].Key);
Assert.Equal(exceptionMessage, errorEvent[1].Value);
Assert.Equal("exception.stacktrace", errorEvent[2].Key);
Assert.Contains("AspireRabbitMQLoggingTests.TestException", errorEvent[2].Value?.ToString());
}
[Fact]
public void TestExceptionWithInnerException()
{
var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Services.AddSingleton<RabbitMQEventSourceLogForwarder>();
var logger = new TestLogger();
builder.Services.AddSingleton<ILoggerProvider>(sp => new LoggerProvider(logger));
using var host = builder.Build();
host.Services.GetRequiredService<RabbitMQEventSourceLogForwarder>().Start();
var exceptionMessage = "Test exception";
Exception testException;
InvalidOperationException innerException = new("Inner exception");
try
{
throw new InvalidOperationException(exceptionMessage, innerException);
}
catch (Exception ex)
{
testException = ex;
}
Assert.NotNull(testException);
var logMessage = "This is an error message.";
LogError(logMessage, testException);
var logs = logger.Logs.ToArray();
Assert.Single(logs);
Assert.Equal(LogLevel.Error, logs[0].Level);
Assert.Equal(logMessage, logs[0].Message);
var errorEvent = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logs[0].State);
Assert.Equal(4, errorEvent.Count);
Assert.Equal("exception.type", errorEvent[0].Key);
Assert.Equal("System.InvalidOperationException", errorEvent[0].Value);
Assert.Equal("exception.message", errorEvent[1].Key);
Assert.Equal(exceptionMessage, errorEvent[1].Value);
Assert.Equal("exception.stacktrace", errorEvent[2].Key);
Assert.Contains("AspireRabbitMQLoggingTests.TestException", errorEvent[2].Value?.ToString());
Assert.Equal("exception.innerexception", errorEvent[3].Key);
Assert.Equal($"{innerException.GetType()}: {innerException.Message}", errorEvent[3].Value?.ToString());
}
#if !RABBITMQ_V6
private static readonly object s_log =
Type.GetType("RabbitMQ.Client.Logging.RabbitMqClientEventSource, RabbitMQ.Client")!
.GetField("Log", BindingFlags.Static | BindingFlags.Public)!
.GetValue(null)!;
#endif
private static void LogInfo(string message)
{
#if RABBITMQ_V6
RabbitMqClientEventSource.Log.Info(message);
#else
s_log.GetType().GetMethod("Info")!.Invoke(s_log, new object[] { message });
#endif
}
private static void LogWarn(string message)
{
#if RABBITMQ_V6
RabbitMqClientEventSource.Log.Warn(message);
#else
s_log.GetType().GetMethod("Warn")!.Invoke(s_log, new object[] { message });
#endif
}
private static void LogError(string message, Exception ex)
{
#if RABBITMQ_V6
RabbitMqClientEventSource.Log.Error(message, ex);
#else
s_log.GetType().GetMethod("Error", [typeof(string), typeof(Exception)])!.Invoke(s_log, new object[] { message, ex });
#endif
}
private sealed class LoggerProvider(TestLogger logger) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => logger;
public void Dispose() { }
}
private sealed class TestLogger : ILogger
{
public BlockingCollection<(LogLevel Level, string Message, object? State)> Logs { get; } = new();
public Action? LoggedMessage { get; set; }
public IDisposable? BeginScope<TState>(TState state) where TState : notnull =>
NullLogger.Instance.BeginScope(state);
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Logs.Add((logLevel, formatter(state, exception), state));
LoggedMessage?.Invoke();
}
}
}