Skip to content

Commit d3a4930

Browse files
authored
Honor IncludeCategory in the JSON log format (#2474)
* Honor IncludeCategory in the JSON log format In text format the ILogger category is written on every line when LambdaLoggerOptions.IncludeCategory is true (the default), but the JSON branch of LambdaILogger.Log never emitted the category, so migrating a function from text to JSON logging silently lost it with no way to opt back in (#2469). When IncludeCategory is set, prepend a {Category} placeholder to the message template and supply the category value, so it surfaces as a queryable property in the JSON record instead of being dropped. Text format is unchanged, and JSON output is unchanged when IncludeCategory is false. Fixes #2469 * chore: add change file for logging category fix * fix: prepend category as plain text, not a template placeholder Copilot's review on this PR caught a real issue: prepending a {Category} placeholder to honor IncludeCategory in JSON mode makes the formatter's positional-argument detection treat the whole template as named, which can shift how a caller's own {0}/{1} placeholders line up with their values. Prepend the category as literal text instead, same as the text format already does. Updated the two category tests and added one covering a positional template to confirm it stays untouched. All 17 tests pass locally on net8.0 and net10.0. * chore: restore the original line endings in LambdaILogger.cs The first commit normalized the whole file to CRLF where upstream has mixed endings, so the diff read 74 changed lines when only 11 lines actually change. Content is unchanged: git diff -w against the previous commit is empty.
1 parent e41f33f commit d3a4930

3 files changed

Lines changed: 135 additions & 0 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"Projects": [
3+
{
4+
"Name": "Amazon.Lambda.Logging.AspNetCore",
5+
"Type": "Patch",
6+
"ChangelogMessages": [
7+
"Fixed the JSON log formatter ignoring IncludeCategory"
8+
]
9+
}
10+
]
11+
}

‎Libraries/src/Amazon.Lambda.Logging.AspNetCore/LambdaILogger.cs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,17 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
7575
messageTemplate = formatter.Invoke(state, exception);
7676
}
7777

78+
if (_options.IncludeCategory)
79+
{
80+
// Unlike the text format, the JSON format otherwise drops the
81+
// category entirely, so IncludeCategory has no effect. Prepend the
82+
// category as literal text rather than a "{Category}" placeholder:
83+
// a placeholder would be picked up by the formatter's positional
84+
// argument detection and shift how the template's own {0}/{name}
85+
// placeholders get matched to the caller's arguments.
86+
messageTemplate = $"[{_categoryName}] " + messageTemplate;
87+
}
88+
7889
Amazon.Lambda.Core.LambdaLogger.Log(lambdaLogLevel, exception, messageTemplate, parameters.ToArray());
7990
}
8091
else

‎Libraries/test/Amazon.Lambda.Logging.AspNetCore.Tests/LoggingTests.cs‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,119 @@ public void TestJSONParameterLogging()
574574

575575
}
576576

577+
[Fact]
578+
public void TestJSONParameterLoggingIncludesCategoryWhenEnabled()
579+
{
580+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
581+
try
582+
{
583+
using (var writer = new StringWriter())
584+
{
585+
ConnectLoggingActionToLogger(message => writer.Write(message));
586+
587+
var configuration = new ConfigurationBuilder()
588+
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
589+
.Build();
590+
591+
var loggerOptions = new LambdaLoggerOptions(configuration);
592+
loggerOptions.IncludeCategory = true;
593+
var loggerFactory = new TestLoggerFactory()
594+
.AddLambdaLogger(loggerOptions);
595+
596+
var logger = loggerFactory.CreateLogger("JSONLogging");
597+
598+
logger.LogError(new Exception("Too Cheap"), "User {name} fail to by {product} for {price}", "Gilmour", "Guitar", 55.55);
599+
600+
var text = writer.ToString();
601+
// Category is prepended as literal text, not a template placeholder,
602+
// so the caller's own {name}/{product}/{price} arguments are untouched.
603+
Assert.Contains("[JSONLogging]", text);
604+
Assert.DoesNotContain("{Category}", text);
605+
Assert.Contains("parameter count: 3", text);
606+
}
607+
}
608+
finally
609+
{
610+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
611+
}
612+
}
613+
614+
[Fact]
615+
public void TestJSONParameterLoggingOmitsCategoryWhenDisabled()
616+
{
617+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
618+
try
619+
{
620+
using (var writer = new StringWriter())
621+
{
622+
ConnectLoggingActionToLogger(message => writer.Write(message));
623+
624+
var configuration = new ConfigurationBuilder()
625+
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
626+
.Build();
627+
628+
var loggerOptions = new LambdaLoggerOptions(configuration);
629+
loggerOptions.IncludeCategory = false;
630+
var loggerFactory = new TestLoggerFactory()
631+
.AddLambdaLogger(loggerOptions);
632+
633+
var logger = loggerFactory.CreateLogger("JSONLogging");
634+
635+
logger.LogError(new Exception("Too Cheap"), "User {name} fail to by {product} for {price}", "Gilmour", "Guitar", 55.55);
636+
637+
var text = writer.ToString();
638+
Assert.DoesNotContain("[JSONLogging]", text);
639+
Assert.DoesNotContain("{Category}", text);
640+
Assert.Contains("parameter count: 3", text);
641+
}
642+
}
643+
finally
644+
{
645+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
646+
}
647+
}
648+
649+
[Fact]
650+
public void TestJSONParameterLoggingWithCategoryLeavesPositionalTemplateIntact()
651+
{
652+
// Prepending category as a "{Category}" template placeholder (the earlier approach)
653+
// would mix a named property into an otherwise all-numeric template, which the JSON
654+
// formatter's positional-argument detection relies on being all-numeric. Prepending
655+
// it as literal text instead means the caller's own "{0}"/"{1}" placeholders, and the
656+
// argument array they line up with, are passed through completely untouched.
657+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
658+
try
659+
{
660+
using (var writer = new StringWriter())
661+
{
662+
ConnectLoggingActionToLogger(message => writer.Write(message));
663+
664+
var configuration = new ConfigurationBuilder()
665+
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
666+
.Build();
667+
668+
var loggerOptions = new LambdaLoggerOptions(configuration);
669+
loggerOptions.IncludeCategory = true;
670+
var loggerFactory = new TestLoggerFactory()
671+
.AddLambdaLogger(loggerOptions);
672+
673+
var logger = loggerFactory.CreateLogger("JSONLogging");
674+
675+
logger.LogInformation("{0} scored {1}", "Alice", 42);
676+
677+
var text = writer.ToString();
678+
Assert.Contains("[JSONLogging]", text);
679+
Assert.Contains("{0} scored {1}", text);
680+
Assert.DoesNotContain("{Category}", text);
681+
Assert.Contains("parameter count: 2", text);
682+
}
683+
}
684+
finally
685+
{
686+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
687+
}
688+
}
689+
577690
[Fact]
578691
public void JsonLoggingWithNoOriginalFormat()
579692
{

0 commit comments

Comments
 (0)