-
Notifications
You must be signed in to change notification settings - Fork 499
Add replay-aware logger to Amazon.Lambda.DurableExecution #2371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GarrettBeatty
wants to merge
1
commit into
GarrettBeatty/stack/3
Choose a base branch
from
GarrettBeatty/stack/4
base: GarrettBeatty/stack/3
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
161 changes: 161 additions & 0 deletions
161
Libraries/src/Amazon.Lambda.DurableExecution/Internal/LambdaCoreLogger.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| using System.Collections.Generic; | ||
| using System.Text; | ||
| using Microsoft.Extensions.Logging; | ||
| using CoreLambdaLogger = Amazon.Lambda.Core.LambdaLogger; | ||
|
|
||
| namespace Amazon.Lambda.DurableExecution.Internal; | ||
|
|
||
| /// <summary> | ||
| /// Default <see cref="ILogger"/> for <see cref="DurableContext"/>. Routes log | ||
| /// records through <see cref="CoreLambdaLogger"/> so they flow into the same | ||
| /// pipeline used by the rest of the AWS Lambda for .NET runtime — the runtime | ||
| /// host installs a redirector that produces structured JSON when | ||
| /// <c>AWS_LAMBDA_LOG_FORMAT=JSON</c> and honors <c>AWS_LAMBDA_LOG_LEVEL</c>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// In-package adapter to avoid forcing a dependency on | ||
| /// <c>Amazon.Lambda.Logging.AspNetCore</c>; users who want a richer experience | ||
| /// (Serilog, Powertools, etc.) can swap their own logger via | ||
| /// <see cref="IDurableContext.ConfigureLogger"/>. | ||
| /// | ||
| /// When <c>state</c> is the standard <c>FormattedLogValues</c> produced by | ||
| /// <see cref="LoggerExtensions"/>, the original template and named arguments | ||
| /// are forwarded so the runtime's JSON formatter surfaces named placeholders | ||
| /// (<c>{OrderId}</c>) as top-level structured attributes. Mirrors the pattern | ||
| /// in <c>Amazon.Lambda.Logging.AspNetCore.LambdaILogger</c>. | ||
| /// | ||
| /// <see cref="BeginScope"/> maintains an <see cref="AsyncLocal{T}"/> chain of | ||
| /// scope state. Scopes whose state is a key/value collection have each entry | ||
| /// appended to the outgoing template/args, so structured scope metadata | ||
| /// (<c>durableExecutionArn</c>, <c>operationId</c>, etc.) shows up as | ||
| /// top-level JSON fields without callers having to swap in a third-party | ||
| /// logger. Inner scopes win on key collision; explicit message arguments | ||
| /// always win over scope keys. | ||
| /// </remarks> | ||
| internal sealed class LambdaCoreLogger : ILogger | ||
| { | ||
| private const string OriginalFormatKey = "{OriginalFormat}"; | ||
|
|
||
| private static readonly AsyncLocal<Scope?> CurrentScope = new(); | ||
|
|
||
| public IDisposable BeginScope<TState>(TState state) where TState : notnull | ||
| { | ||
| var scope = new Scope(state, CurrentScope.Value); | ||
| CurrentScope.Value = scope; | ||
| return scope; | ||
| } | ||
|
|
||
| // Level filtering is performed by the runtime layer (AWS_LAMBDA_LOG_LEVEL). | ||
| public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; | ||
|
GarrettBeatty marked this conversation as resolved.
|
||
|
|
||
| public void Log<TState>( | ||
| LogLevel logLevel, | ||
| EventId eventId, | ||
| TState state, | ||
| Exception? exception, | ||
| Func<TState, Exception?, string> formatter) | ||
| { | ||
| if (!IsEnabled(logLevel)) return; | ||
|
|
||
| string? messageTemplate = null; | ||
| var parameters = new List<object>(); | ||
| HashSet<string>? claimedKeys = null; | ||
|
|
||
| if (state is IEnumerable<KeyValuePair<string, object?>> structure) | ||
| { | ||
| foreach (var property in structure) | ||
| { | ||
| if (property is { Key: OriginalFormatKey, Value: string value }) | ||
| { | ||
| messageTemplate = value; | ||
| } | ||
| else | ||
| { | ||
| parameters.Add(property.Value!); | ||
| claimedKeys ??= new HashSet<string>(StringComparer.Ordinal); | ||
| claimedKeys.Add(property.Key); | ||
| } | ||
| } | ||
|
|
||
| // No {OriginalFormat} → not a real FormattedLogValues; ignore the args | ||
| // we collected and fall back to the formatter below. | ||
| if (messageTemplate == null) | ||
| { | ||
| parameters.Clear(); | ||
| claimedKeys = null; | ||
| } | ||
| } | ||
|
|
||
| messageTemplate ??= formatter(state, exception); | ||
|
|
||
| AppendScopeAttributes(ref messageTemplate, parameters, ref claimedKeys); | ||
|
|
||
| var levelName = logLevel.ToString(); | ||
| var args = parameters.Count == 0 ? Array.Empty<object>() : parameters.ToArray(); | ||
| if (exception != null) | ||
| { | ||
| CoreLambdaLogger.Log(levelName, exception, messageTemplate, args); | ||
| } | ||
| else | ||
| { | ||
| CoreLambdaLogger.Log(levelName, messageTemplate, args); | ||
| } | ||
| } | ||
|
|
||
| private static void AppendScopeAttributes( | ||
| ref string messageTemplate, | ||
| List<object> parameters, | ||
| ref HashSet<string>? claimedKeys) | ||
| { | ||
| var current = CurrentScope.Value; | ||
| if (current == null) return; | ||
|
|
||
| StringBuilder? sb = null; | ||
|
|
||
| // Walk innermost → outermost so the first key seen for a given name wins | ||
| // (mirrors how Microsoft.Extensions.Logging structured providers resolve | ||
| // overlapping scope keys: the closest scope dominates). | ||
| for (var s = current; s != null; s = s.Parent) | ||
| { | ||
| if (s.State is not IEnumerable<KeyValuePair<string, object?>> kvps) continue; | ||
| foreach (var kvp in kvps) | ||
| { | ||
| // Skip {OriginalFormat} (some scope-state factories emit one). | ||
| if (kvp.Key == OriginalFormatKey) continue; | ||
|
|
||
| claimedKeys ??= new HashSet<string>(StringComparer.Ordinal); | ||
| if (!claimedKeys.Add(kvp.Key)) continue; | ||
|
|
||
| sb ??= new StringBuilder(messageTemplate); | ||
| sb.Append(' ').Append('{').Append(kvp.Key).Append('}'); | ||
| parameters.Add(kvp.Value!); | ||
| } | ||
| } | ||
|
|
||
| if (sb != null) messageTemplate = sb.ToString(); | ||
| } | ||
|
|
||
| private sealed class Scope : IDisposable | ||
| { | ||
| public object State { get; } | ||
| public Scope? Parent { get; } | ||
| private bool _disposed; | ||
|
|
||
| public Scope(object state, Scope? parent) | ||
| { | ||
| State = state; | ||
| Parent = parent; | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| if (_disposed) return; | ||
| _disposed = true; | ||
|
|
||
| // Restore the parent. Out-of-order disposal would desync the chain, | ||
| // but that violates the using-statement contract that callers rely | ||
| // on; we don't try to defend against it. | ||
| CurrentScope.Value = Parent; | ||
| } | ||
| } | ||
| } | ||
57 changes: 57 additions & 0 deletions
57
Libraries/src/Amazon.Lambda.DurableExecution/Internal/ReplayAwareLogger.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Amazon.Lambda.DurableExecution.Internal; | ||
|
|
||
| /// <summary> | ||
| /// <see cref="ILogger"/> decorator that suppresses messages while the workflow | ||
| /// is replaying prior operations. Reads <see cref="ExecutionState.IsReplaying"/> | ||
| /// on every call so it correctly transitions to passthrough the moment the | ||
| /// state's per-operation tracker decides we've caught up to fresh execution. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Mirrors the suppression behavior of the Python and Java durable execution | ||
| /// SDKs: replay <see cref="Log{TState}"/> calls return without invoking the | ||
| /// inner logger. <see cref="BeginScope{TState}"/> always delegates so scopes | ||
| /// stay balanced — suppression only applies at log emission. | ||
| /// </remarks> | ||
| internal sealed class ReplayAwareLogger : ILogger | ||
| { | ||
| private readonly ILogger _inner; | ||
| private readonly ExecutionState _state; | ||
| private readonly bool _modeAware; | ||
|
|
||
| public ReplayAwareLogger(ILogger inner, ExecutionState state, bool modeAware) | ||
| { | ||
| _inner = inner; | ||
| _state = state; | ||
| _modeAware = modeAware; | ||
| } | ||
|
|
||
| /// <summary>The wrapped logger; exposed so <c>ConfigureLogger</c> can rewrap without losing it.</summary> | ||
| public ILogger Inner => _inner; | ||
|
|
||
| /// <summary>Whether replay suppression is active.</summary> | ||
| public bool ModeAware => _modeAware; | ||
|
|
||
| public IDisposable? BeginScope<TState>(TState state) where TState : notnull | ||
| => _inner.BeginScope(state); | ||
|
|
||
| public bool IsEnabled(LogLevel logLevel) | ||
| { | ||
| if (ShouldSuppress()) return false; | ||
| return _inner.IsEnabled(logLevel); | ||
| } | ||
|
|
||
| public void Log<TState>( | ||
| LogLevel logLevel, | ||
| EventId eventId, | ||
| TState state, | ||
| Exception? exception, | ||
| Func<TState, Exception?, string> formatter) | ||
| { | ||
| if (ShouldSuppress()) return; | ||
| _inner.Log(logLevel, eventId, state, exception, formatter); | ||
| } | ||
|
|
||
| private bool ShouldSuppress() => _modeAware && _state.IsReplaying; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
Libraries/src/Amazon.Lambda.DurableExecution/LoggerConfig.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Amazon.Lambda.DurableExecution; | ||
|
|
||
| /// <summary> | ||
| /// Configuration for <see cref="IDurableContext.ConfigureLogger"/>. Lets users | ||
| /// swap the underlying <see cref="ILogger"/> (e.g. Serilog, AWS Lambda Powertools) | ||
| /// or disable replay-aware filtering for debugging. | ||
| /// </summary> | ||
| public sealed class LoggerConfig | ||
| { | ||
| /// <summary> | ||
| /// Optional <see cref="ILogger"/> to use instead of the SDK default. When | ||
| /// null, the durable context keeps its existing inner logger. | ||
| /// </summary> | ||
| public ILogger? CustomLogger { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// When true (default), messages are suppressed while the workflow is | ||
| /// re-deriving prior operations from checkpointed state. Set to false to | ||
| /// see every log line on every replay (useful for local debugging). | ||
| /// </summary> | ||
| public bool ModeAware { get; init; } = true; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.