-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathConsoleWrapper.cs
More file actions
217 lines (192 loc) · 6.41 KB
/
Copy pathConsoleWrapper.cs
File metadata and controls
217 lines (192 loc) · 6.41 KB
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
using System;
using System.IO;
namespace AWS.Lambda.Powertools.Common;
/// <inheritdoc />
public class ConsoleWrapper : IConsoleWrapper
{
private static bool _override;
private static TextWriter _testOutputStream;
private static bool _inTestMode = false;
private static StreamWriter _stdoutWriter;
private static StreamWriter _stderrWriter;
private static readonly object _lock = new object();
/// <inheritdoc />
public void WriteLine(string message)
{
if (_inTestMode && _testOutputStream != null)
{
_testOutputStream.WriteLine(message);
}
else
{
EnsureConsoleOutput();
Console.WriteLine(message);
}
}
/// <inheritdoc />
public void Debug(string message)
{
if (_inTestMode && _testOutputStream != null)
{
_testOutputStream.WriteLine(message);
}
else
{
EnsureConsoleOutput();
System.Diagnostics.Debug.WriteLine(message);
}
}
/// <inheritdoc />
public void Error(string message)
{
if (_inTestMode && _testOutputStream != null)
{
_testOutputStream.WriteLine(message);
}
else
{
EnsureStderrOutput();
Console.Error.WriteLine(message);
}
}
/// <summary>
/// Set the ConsoleWrapper to use a different TextWriter
/// This is useful for unit tests where you want to capture the output
/// </summary>
public static void SetOut(TextWriter consoleOut)
{
_testOutputStream = consoleOut;
_inTestMode = true;
_override = true;
Console.SetOut(consoleOut);
}
private static void EnsureConsoleOutput()
{
// Check if we need to override console output for Lambda environment
if (ShouldOverrideConsole())
{
OverrideLambdaLogger();
}
}
private static void EnsureStderrOutput()
{
EnsureStderrOutput(() => Console.OpenStandardError());
}
internal static void EnsureStderrOutput(Func<Stream> standardErrorOpener)
{
if (_inTestMode) return;
var isLambda = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME"));
if (!isLambda) return;
lock (_lock)
{
if (_stderrWriter != null) return;
try
{
_stderrWriter = new StreamWriter(standardErrorOpener())
{
AutoFlush = true
};
Console.SetError(_stderrWriter);
}
catch (Exception)
{
// Degraded functionality is better than crash
}
}
}
private static bool ShouldOverrideConsole()
{
// Don't override if we're in test mode
if (_inTestMode) return false;
// Always override in Lambda environment to prevent Lambda's log wrapping
var isLambda = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME"));
return isLambda && (!_override || HasLambdaReInterceptedConsole());
}
internal static bool HasLambdaReInterceptedConsole()
{
return HasLambdaReInterceptedConsole(() => Console.Out);
}
internal static bool HasLambdaReInterceptedConsole(Func<TextWriter> consoleOutAccessor)
{
// Lambda might re-intercept console between init and handler execution.
// We need to detect when Lambda replaces our writer with its own,
// but NOT trigger on the SyncTextWriter wrapper that Console.SetOut
// always applies around our StreamWriter — that's still ours.
try
{
var currentOut = consoleOutAccessor();
var typeName = currentOut.GetType().FullName ?? "";
// If it explicitly contains "Lambda", Lambda has re-intercepted
if (typeName.Contains("Lambda"))
return true;
// If we have a cached writer, check if Console.Out still wraps it.
// Console.SetOut wraps in SyncTextWriter, so seeing SyncTextWriter
// does NOT mean Lambda re-intercepted — it's our own writer wrapped.
// Only if _stdoutWriter is null (never set) do we need to override.
lock (_lock)
{
return _stdoutWriter == null;
}
}
catch
{
return true; // Assume re-interception if we can't determine
}
}
internal static void OverrideLambdaLogger()
{
OverrideLambdaLogger(() => Console.OpenStandardOutput());
}
internal static void OverrideLambdaLogger(Func<Stream> standardOutputOpener)
{
lock (_lock)
{
try
{
// Reuse existing writer if we already have one — avoids FD leak
if (_stdoutWriter != null)
{
// Re-set Console.Out in case Lambda replaced it
Console.SetOut(_stdoutWriter);
_override = true;
return;
}
// First time: create a single long-lived writer for stdout
_stdoutWriter = new StreamWriter(standardOutputOpener())
{
AutoFlush = true
};
Console.SetOut(_stdoutWriter);
_override = true;
}
catch (Exception)
{
// Log the failure but don't throw - degraded functionality is better than crash
_override = false;
}
}
}
internal static void WriteLine(string logLevel, string message)
{
Console.WriteLine($"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ss.fffZ}\t{logLevel}\t{message}");
}
/// <summary>
/// Reset the ConsoleWrapper to its original state
/// </summary>
public static void ResetForTest()
{
_override = false;
_inTestMode = false;
_testOutputStream = null;
_stdoutWriter = null;
_stderrWriter = null;
}
/// <summary>
/// Clear the output reset flag
/// </summary>
public static void ClearOutputResetFlag()
{
// This method is kept for backward compatibility but no longer needed
// since we removed the _outputResetPerformed flag
}
}