Skip to content

Commit 273a2fe

Browse files
committed
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 (aws#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 aws#2469
1 parent 42a8cd3 commit 273a2fe

2 files changed

Lines changed: 143 additions & 63 deletions

File tree

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

Lines changed: 73 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,32 @@
22
using System.Collections.Generic;
33

44
namespace Microsoft.Extensions.Logging
5-
{
6-
internal class LambdaILogger : ILogger
7-
{
8-
// Private fields
9-
private readonly string _categoryName;
10-
private readonly LambdaLoggerOptions _options;
11-
12-
13-
internal IExternalScopeProvider ScopeProvider { get; set; }
14-
15-
// Constructor
16-
public LambdaILogger(string categoryName, LambdaLoggerOptions options)
17-
{
18-
_categoryName = categoryName;
19-
_options = options;
20-
}
21-
22-
// ILogger methods
23-
public IDisposable BeginScope<TState>(TState state) => ScopeProvider?.Push(state) ?? new NoOpDisposable();
24-
25-
public bool IsEnabled(LogLevel logLevel)
26-
{
27-
return (
28-
_options.Filter == null ||
29-
_options.Filter(_categoryName, logLevel));
30-
}
5+
{
6+
internal class LambdaILogger : ILogger
7+
{
8+
// Private fields
9+
private readonly string _categoryName;
10+
private readonly LambdaLoggerOptions _options;
11+
12+
13+
internal IExternalScopeProvider ScopeProvider { get; set; }
14+
15+
// Constructor
16+
public LambdaILogger(string categoryName, LambdaLoggerOptions options)
17+
{
18+
_categoryName = categoryName;
19+
_options = options;
20+
}
21+
22+
// ILogger methods
23+
public IDisposable BeginScope<TState>(TState state) => ScopeProvider?.Push(state) ?? new NoOpDisposable();
24+
25+
public bool IsEnabled(LogLevel logLevel)
26+
{
27+
return (
28+
_options.Filter == null ||
29+
_options.Filter(_categoryName, logLevel));
30+
}
3131

3232
/// <summary>
3333
/// The Log method called by the ILogger framework to log message to logger's target. In the Lambda case the formatted logging will be
@@ -39,17 +39,17 @@ public bool IsEnabled(LogLevel logLevel)
3939
/// <param name="state"></param>
4040
/// <param name="exception"></param>
4141
/// <param name="formatter"></param>
42-
/// <exception cref="ArgumentNullException"></exception>
43-
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
44-
{
45-
if (formatter == null)
46-
{
47-
throw new ArgumentNullException(nameof(formatter));
48-
}
49-
50-
if (!IsEnabled(logLevel))
51-
{
52-
return;
42+
/// <exception cref="ArgumentNullException"></exception>
43+
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
44+
{
45+
if (formatter == null)
46+
{
47+
throw new ArgumentNullException(nameof(formatter));
48+
}
49+
50+
if (!IsEnabled(logLevel))
51+
{
52+
return;
5353
}
5454

5555
var lambdaLogLevel = ConvertLogLevel(logLevel);
@@ -75,6 +75,16 @@ 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 a
82+
// "{Category}" placeholder (which the JSON formatter turns into a
83+
// queryable property) and supply the category value.
84+
messageTemplate = "[{Category}] " + messageTemplate;
85+
parameters.Insert(0, _categoryName);
86+
}
87+
7888
Amazon.Lambda.Core.LambdaLogger.Log(lambdaLogLevel, exception, messageTemplate, parameters.ToArray());
7989
}
8090
else
@@ -133,26 +143,26 @@ private static Amazon.Lambda.Core.LogLevel ConvertLogLevel(LogLevel logLevel)
133143
default:
134144
return Amazon.Lambda.Core.LogLevel.Information;
135145
}
136-
}
137-
138-
private void GetScopeInformation(List<string> logMessageComponents)
139-
{
140-
var scopeProvider = ScopeProvider;
141-
142-
if (_options.IncludeScopes && scopeProvider != null)
143-
{
144-
var initialCount = logMessageComponents.Count;
145-
146-
scopeProvider.ForEachScope((scope, list) =>
147-
{
148-
list.Add(scope.ToString());
149-
}, (logMessageComponents));
150-
151-
if (logMessageComponents.Count > initialCount)
152-
{
153-
logMessageComponents.Add("=>");
154-
}
155-
}
146+
}
147+
148+
private void GetScopeInformation(List<string> logMessageComponents)
149+
{
150+
var scopeProvider = ScopeProvider;
151+
152+
if (_options.IncludeScopes && scopeProvider != null)
153+
{
154+
var initialCount = logMessageComponents.Count;
155+
156+
scopeProvider.ForEachScope((scope, list) =>
157+
{
158+
list.Add(scope.ToString());
159+
}, (logMessageComponents));
160+
161+
if (logMessageComponents.Count > initialCount)
162+
{
163+
logMessageComponents.Add("=>");
164+
}
165+
}
156166
}
157167

158168
private bool IsLambdaJsonFormatEnabled
@@ -164,12 +174,12 @@ private bool IsLambdaJsonFormatEnabled
164174
}
165175

166176
// Private classes
167-
private class NoOpDisposable : IDisposable
168-
{
169-
public void Dispose()
170-
{
171-
}
177+
private class NoOpDisposable : IDisposable
178+
{
179+
public void Dispose()
180+
{
181+
}
172182
}
173-
183+
174184
}
175185
}

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

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,76 @@ 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 a placeholder + argument, so it becomes
602+
// a queryable JSON property instead of being dropped.
603+
Assert.Contains("{Category}", text);
604+
Assert.Contains("parameter count: 4", text);
605+
}
606+
}
607+
finally
608+
{
609+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
610+
}
611+
}
612+
613+
[Fact]
614+
public void TestJSONParameterLoggingOmitsCategoryWhenDisabled()
615+
{
616+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
617+
try
618+
{
619+
using (var writer = new StringWriter())
620+
{
621+
ConnectLoggingActionToLogger(message => writer.Write(message));
622+
623+
var configuration = new ConfigurationBuilder()
624+
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
625+
.Build();
626+
627+
var loggerOptions = new LambdaLoggerOptions(configuration);
628+
loggerOptions.IncludeCategory = false;
629+
var loggerFactory = new TestLoggerFactory()
630+
.AddLambdaLogger(loggerOptions);
631+
632+
var logger = loggerFactory.CreateLogger("JSONLogging");
633+
634+
logger.LogError(new Exception("Too Cheap"), "User {name} fail to by {product} for {price}", "Gilmour", "Guitar", 55.55);
635+
636+
var text = writer.ToString();
637+
Assert.DoesNotContain("{Category}", text);
638+
Assert.Contains("parameter count: 3", text);
639+
}
640+
}
641+
finally
642+
{
643+
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
644+
}
645+
}
646+
577647
[Fact]
578648
public void JsonLoggingWithNoOriginalFormat()
579649
{

0 commit comments

Comments
 (0)