Skip to content

Commit d02ae25

Browse files
committed
feat(metrics): add support for disabling metrics via environment variable
1 parent 97dc991 commit d02ae25

File tree

6 files changed

+83
-15
lines changed

6 files changed

+83
-15
lines changed

docs/core/metrics-v2.md

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

5353
**`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.
5454

55-
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:
55+
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:
5656

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

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

70-
### Full list of environment variables
71-
72-
| Environment variable | Description | Default |
73-
| ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- |
74-
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | `"service_undefined"` |
75-
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | `None` |
76-
7774
### Metrics object
7875

7976
#### 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: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,11 @@ internal static IMetrics Instance
100100
/// </summary>
101101
private string _functionName;
102102

103+
/// <summary>
104+
/// Gets a value indicating whether metrics are disabled.
105+
/// </summary>
106+
private bool _disabled;
107+
103108
/// <summary>
104109
/// Initializes a new instance of the <see cref="Metrics" /> class.
105110
/// </summary>
@@ -156,6 +161,7 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
156161
_context = new MetricsContext();
157162
_raiseOnEmptyMetrics = raiseOnEmptyMetrics;
158163
_captureColdStartEnabled = captureColdStartEnabled;
164+
_disabled = _powertoolsConfigurations.MetricsDisabled;
159165

160166
Instance = this;
161167
_powertoolsConfigurations.SetExecutionEnvironment(this);
@@ -167,7 +173,7 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
167173
/// <inheritdoc />
168174
void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolution resolution)
169175
{
170-
if (Instance != null)
176+
if (Instance != null && !_disabled)
171177
{
172178
if (string.IsNullOrWhiteSpace(key))
173179
throw new ArgumentNullException(
@@ -261,6 +267,9 @@ void IMetrics.SetDefaultDimensions(Dictionary<string, string> defaultDimensions)
261267
/// <inheritdoc />
262268
void IMetrics.Flush(bool metricsOverflow)
263269
{
270+
if(_disabled)
271+
return;
272+
264273
if (_context.GetMetrics().Count == 0
265274
&& _raiseOnEmptyMetrics)
266275
throw new SchemaValidationException(true);
@@ -329,6 +338,9 @@ private Dictionary<string, string> GetDefaultDimensions()
329338
void IMetrics.PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace,
330339
string service, Dictionary<string, string> defaultDimensions, MetricResolution resolution)
331340
{
341+
if(_disabled)
342+
return;
343+
332344
if (string.IsNullOrWhiteSpace(name))
333345
throw new ArgumentNullException(nameof(name),
334346
"'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.");

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;
@@ -141,6 +142,51 @@ public void Before_When_RaiseOnEmptyMetricsNotSet_Should_Configure_Null()
141142
Assert.False(metrics.Options.RaiseOnEmptyMetrics);
142143
}
143144

145+
[Fact]
146+
public void When_MetricsDisabled_Should_Not_AddMetric()
147+
{
148+
// Arrange
149+
var conf = Substitute.For<IPowertoolsConfigurations>();
150+
conf.MetricsDisabled.Returns(true);
151+
152+
IMetrics metrics = new Metrics(conf);
153+
var stringWriter = new StringWriter();
154+
Console.SetOut(stringWriter);
155+
156+
// Act
157+
metrics.AddMetric("test", 1.0);
158+
metrics.Flush();
159+
160+
// Assert
161+
Assert.Empty(stringWriter.ToString());
162+
163+
// Cleanup
164+
stringWriter.Dispose();
165+
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
166+
}
167+
168+
[Fact]
169+
public void When_MetricsDisabled_Should_Not_PushSingleMetric()
170+
{
171+
// Arrange
172+
var conf = Substitute.For<IPowertoolsConfigurations>();
173+
conf.MetricsDisabled.Returns(true);
174+
175+
IMetrics metrics = new Metrics(conf);
176+
var stringWriter = new StringWriter();
177+
Console.SetOut(stringWriter);
178+
179+
// Act
180+
metrics.PushSingleMetric("test", 1.0, MetricUnit.Count);
181+
182+
// Assert
183+
Assert.Empty(stringWriter.ToString());
184+
185+
// Cleanup
186+
stringWriter.Dispose();
187+
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
188+
}
189+
144190
// Helper method for the tests
145191
internal void TestMethod(ILambdaContext context)
146192
{

0 commit comments

Comments
 (0)