Skip to content

Commit 08efcb2

Browse files
authored
Merge pull request #786 from hjgraca/feature/metrics-disabled
chore: Metrics disabled environment variable
2 parents d5593b3 + f2e94df commit 08efcb2

File tree

7 files changed

+87
-14
lines changed

7 files changed

+87
-14
lines changed

docs/core/metrics-v2.md

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,16 @@ Visit the AWS documentation for a complete explanation for [Amazon CloudWatch co
5858

5959
**`Metrics`** is implemented as a Singleton to keep track of your aggregate metrics in memory and make them accessible anywhere in your code. To guarantee that metrics are flushed properly the **`MetricsAttribute`** must be added on the lambda handler.
6060

61-
Metrics has two global settings that will be used across all metrics emitted. Use your application or main service as the metric namespace to easily group all metrics:
61+
Metrics has three global settings that will be used across all metrics emitted. Use your application or main service as the metric namespace to easily group all metrics:
6262

63-
Setting | Description | Environment variable | Constructor parameter
64-
------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------
65-
**Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service`
66-
**Metric namespace** | Logical container where all metrics will be placed e.g. `MyCompanyEcommerce` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace`
63+
Setting | Description | Environment variable | Decorator parameter
64+
-------------------------------|---------------------------------------------------------------------------------| ------------------------------------------------- |-----------------------
65+
**Metric namespace** | Logical container where all metrics will be placed e.g. `MyCompanyEcommerce` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace`
66+
**Service** | Optionally, sets **Service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service`
67+
**Disable Powertools Metrics** | Optionally, disables all Powertools metrics |`POWERTOOLS_METRICS_DISABLED` | N/A |
68+
69+
???+ info
70+
`POWERTOOLS_METRICS_DISABLED` will not disable default metrics created by AWS services.
6771

6872
!!! info "Autocomplete Metric Units"
6973
All parameters in **`Metrics Attribute`** are optional. Following rules apply:
@@ -73,13 +77,6 @@ Setting | Description | Environment variable | Constructor parameter
7377
- **CaptureColdStart:** **`false`** by default.
7478
- **RaiseOnEmptyMetrics:** **`false`** by default.
7579

76-
### Full list of environment variables
77-
78-
| Environment variable | Description | Default |
79-
| ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- |
80-
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | `"service_undefined"` |
81-
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | `None` |
82-
8380
### Metrics object
8481

8582
#### Attribute

libraries/src/AWS.Lambda.Powertools.Common/Core/Constants.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,9 @@ internal static class Constants
130130
/// Constant for POWERTOOLS_BATCH_THROW_ON_FULL_BATCH_FAILURE environment variable
131131
/// </summary>
132132
internal const string BatchThrowOnFullBatchFailureEnv = "POWERTOOLS_BATCH_THROW_ON_FULL_BATCH_FAILURE";
133+
134+
/// <summary>
135+
/// Constant for POWERTOOLS_METRICS_DISABLED environment variable
136+
/// </summary>
137+
internal const string PowertoolsMetricsDisabledEnv = "POWERTOOLS_METRICS_DISABLED";
133138
}

libraries/src/AWS.Lambda.Powertools.Common/Core/IPowertoolsConfigurations.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,16 @@ public interface IPowertoolsConfigurations
155155
/// Gets the maximum degree of parallelism to apply during batch processing.
156156
/// </summary>
157157
/// <value>Defaults to 1 (no parallelism). Specify -1 to automatically use the value of <see cref="System.Environment.ProcessorCount">ProcessorCount</see>.</value>
158-
int BatchProcessingMaxDegreeOfParallelism { get; }
159-
158+
int BatchProcessingMaxDegreeOfParallelism { get; }
159+
160160
/// <summary>
161161
/// Gets a value indicating whether Batch processing will throw an exception on full batch failure.
162162
/// </summary>
163163
/// <value>Defaults to true</value>
164164
bool BatchThrowOnFullBatchFailureEnabled { get; }
165+
166+
/// <summary>
167+
/// Gets a value indicating whether Metrics are disabled.
168+
/// </summary>
169+
bool MetricsDisabled { get; }
165170
}

libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsConfigurations.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,4 +219,7 @@ public void SetExecutionEnvironment<T>(T type)
219219

220220
/// <inheritdoc />
221221
public bool BatchThrowOnFullBatchFailureEnabled => GetEnvironmentVariableOrDefault(Constants.BatchThrowOnFullBatchFailureEnv, true);
222+
223+
/// <inheritdoc />
224+
public bool MetricsDisabled => GetEnvironmentVariableOrDefault(Constants.PowertoolsMetricsDisabledEnv, false);
222225
}

libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,11 @@ public static IMetrics Instance
109109
/// </summary>
110110
private readonly IConsoleWrapper _consoleWrapper;
111111

112+
/// <summary>
113+
/// Gets a value indicating whether metrics are disabled.
114+
/// </summary>
115+
private bool _disabled;
116+
112117
/// <summary>
113118
/// Initializes a new instance of the <see cref="Metrics" /> class.
114119
/// </summary>
@@ -170,6 +175,8 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
170175
_captureColdStartEnabled = captureColdStartEnabled;
171176
_options = options;
172177

178+
_disabled = _powertoolsConfigurations.MetricsDisabled;
179+
173180
Instance = this;
174181
_powertoolsConfigurations.SetExecutionEnvironment(this);
175182

@@ -180,6 +187,9 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
180187
/// <inheritdoc />
181188
void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolution resolution)
182189
{
190+
if(_disabled)
191+
return;
192+
183193
if (Instance != null)
184194
{
185195
if (string.IsNullOrWhiteSpace(key))
@@ -274,6 +284,9 @@ void IMetrics.SetDefaultDimensions(Dictionary<string, string> defaultDimensions)
274284
/// <inheritdoc />
275285
void IMetrics.Flush(bool metricsOverflow)
276286
{
287+
if(_disabled)
288+
return;
289+
277290
if (_context.GetMetrics().Count == 0
278291
&& _raiseOnEmptyMetrics)
279292
throw new SchemaValidationException(true);
@@ -342,6 +355,9 @@ private Dictionary<string, string> GetDefaultDimensions()
342355
void IMetrics.PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace,
343356
string service, Dictionary<string, string> dimensions, MetricResolution resolution)
344357
{
358+
if(_disabled)
359+
return;
360+
345361
if (string.IsNullOrWhiteSpace(name))
346362
throw new ArgumentNullException(nameof(name),
347363
"'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.");

libraries/tests/AWS.Lambda.Powertools.Common.Tests/ConsoleWrapperTests.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public void Error_Should_Write_To_Error_Console()
3131

3232
// Act
3333
consoleWrapper.Error("error message");
34+
writer.Flush();
3435

3536
// Assert
3637
Assert.Equal($"error message{Environment.NewLine}", writer.ToString());

libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.IO;
34
using Amazon.Lambda.Core;
45
using Amazon.Lambda.TestUtilities;
56
using AWS.Lambda.Powertools.Common;
@@ -62,6 +63,51 @@ public void Before_When_RaiseOnEmptyMetricsNotSet_Should_Configure_Null()
6263
Assert.False(metrics.Options.RaiseOnEmptyMetrics);
6364
}
6465

66+
[Fact]
67+
public void When_MetricsDisabled_Should_Not_AddMetric()
68+
{
69+
// Arrange
70+
var conf = Substitute.For<IPowertoolsConfigurations>();
71+
conf.MetricsDisabled.Returns(true);
72+
73+
IMetrics metrics = new Metrics(conf);
74+
var stringWriter = new StringWriter();
75+
Console.SetOut(stringWriter);
76+
77+
// Act
78+
metrics.AddMetric("test", 1.0);
79+
metrics.Flush();
80+
81+
// Assert
82+
Assert.Empty(stringWriter.ToString());
83+
84+
// Cleanup
85+
stringWriter.Dispose();
86+
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
87+
}
88+
89+
[Fact]
90+
public void When_MetricsDisabled_Should_Not_PushSingleMetric()
91+
{
92+
// Arrange
93+
var conf = Substitute.For<IPowertoolsConfigurations>();
94+
conf.MetricsDisabled.Returns(true);
95+
96+
IMetrics metrics = new Metrics(conf);
97+
var stringWriter = new StringWriter();
98+
Console.SetOut(stringWriter);
99+
100+
// Act
101+
metrics.PushSingleMetric("test", 1.0, MetricUnit.Count);
102+
103+
// Assert
104+
Assert.Empty(stringWriter.ToString());
105+
106+
// Cleanup
107+
stringWriter.Dispose();
108+
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
109+
}
110+
65111
// Helper method for the tests
66112
internal void TestMethod(ILambdaContext context)
67113
{

0 commit comments

Comments
 (0)