Skip to content
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

chore: Metrics disabled environment variable #786

Merged
merged 3 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions docs/core/metrics-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,16 @@ Visit the AWS documentation for a complete explanation for [Amazon CloudWatch co

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

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:
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:

Setting | Description | Environment variable | Constructor parameter
------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------
**Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service`
**Metric namespace** | Logical container where all metrics will be placed e.g. `MyCompanyEcommerce` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace`
Setting | Description | Environment variable | Decorator parameter
-------------------------------|---------------------------------------------------------------------------------| ------------------------------------------------- |-----------------------
**Metric namespace** | Logical container where all metrics will be placed e.g. `MyCompanyEcommerce` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace`
**Service** | Optionally, sets **Service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service`
**Disable Powertools Metrics** | Optionally, disables all Powertools metrics |`POWERTOOLS_METRICS_DISABLED` | N/A |

???+ info
`POWERTOOLS_METRICS_DISABLED` will not disable default metrics created by AWS services.

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

### Full list of environment variables

| Environment variable | Description | Default |
| ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- |
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | `"service_undefined"` |
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | `None` |

### Metrics object

#### Attribute
Expand Down
5 changes: 5 additions & 0 deletions libraries/src/AWS.Lambda.Powertools.Common/Core/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,9 @@ internal static class Constants
/// Constant for POWERTOOLS_BATCH_THROW_ON_FULL_BATCH_FAILURE environment variable
/// </summary>
internal const string BatchThrowOnFullBatchFailureEnv = "POWERTOOLS_BATCH_THROW_ON_FULL_BATCH_FAILURE";

/// <summary>
/// Constant for POWERTOOLS_METRICS_DISABLED environment variable
/// </summary>
internal const string PowertoolsMetricsDisabledEnv = "POWERTOOLS_METRICS_DISABLED";
}
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,16 @@ public interface IPowertoolsConfigurations
/// Gets the maximum degree of parallelism to apply during batch processing.
/// </summary>
/// <value>Defaults to 1 (no parallelism). Specify -1 to automatically use the value of <see cref="System.Environment.ProcessorCount">ProcessorCount</see>.</value>
int BatchProcessingMaxDegreeOfParallelism { get; }
int BatchProcessingMaxDegreeOfParallelism { get; }

/// <summary>
/// Gets a value indicating whether Batch processing will throw an exception on full batch failure.
/// </summary>
/// <value>Defaults to true</value>
bool BatchThrowOnFullBatchFailureEnabled { get; }

/// <summary>
/// Gets a value indicating whether Metrics are disabled.
/// </summary>
bool MetricsDisabled { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,7 @@ public void SetExecutionEnvironment<T>(T type)

/// <inheritdoc />
public bool BatchThrowOnFullBatchFailureEnabled => GetEnvironmentVariableOrDefault(Constants.BatchThrowOnFullBatchFailureEnv, true);

/// <inheritdoc />
public bool MetricsDisabled => GetEnvironmentVariableOrDefault(Constants.PowertoolsMetricsDisabledEnv, false);
}
16 changes: 16 additions & 0 deletions libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ public static IMetrics Instance
/// </summary>
private readonly IConsoleWrapper _consoleWrapper;

/// <summary>
/// Gets a value indicating whether metrics are disabled.
/// </summary>
private bool _disabled;

/// <summary>
/// Initializes a new instance of the <see cref="Metrics" /> class.
/// </summary>
Expand Down Expand Up @@ -170,6 +175,8 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
_captureColdStartEnabled = captureColdStartEnabled;
_options = options;

_disabled = _powertoolsConfigurations.MetricsDisabled;

Instance = this;
_powertoolsConfigurations.SetExecutionEnvironment(this);

Expand All @@ -180,6 +187,9 @@ internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string name
/// <inheritdoc />
void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolution resolution)
{
if(_disabled)
return;

if (Instance != null)
{
if (string.IsNullOrWhiteSpace(key))
Expand Down Expand Up @@ -274,6 +284,9 @@ void IMetrics.SetDefaultDimensions(Dictionary<string, string> defaultDimensions)
/// <inheritdoc />
void IMetrics.Flush(bool metricsOverflow)
{
if(_disabled)
return;

if (_context.GetMetrics().Count == 0
&& _raiseOnEmptyMetrics)
throw new SchemaValidationException(true);
Expand Down Expand Up @@ -342,6 +355,9 @@ private Dictionary<string, string> GetDefaultDimensions()
void IMetrics.PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace,
string service, Dictionary<string, string> dimensions, MetricResolution resolution)
{
if(_disabled)
return;

if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name),
"'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public void Error_Should_Write_To_Error_Console()

// Act
consoleWrapper.Error("error message");
writer.Flush();

// Assert
Assert.Equal($"error message{Environment.NewLine}", writer.ToString());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using Amazon.Lambda.Core;
using Amazon.Lambda.TestUtilities;
using AWS.Lambda.Powertools.Common;
Expand Down Expand Up @@ -62,6 +63,51 @@ public void Before_When_RaiseOnEmptyMetricsNotSet_Should_Configure_Null()
Assert.False(metrics.Options.RaiseOnEmptyMetrics);
}

[Fact]
public void When_MetricsDisabled_Should_Not_AddMetric()
{
// Arrange
var conf = Substitute.For<IPowertoolsConfigurations>();
conf.MetricsDisabled.Returns(true);

IMetrics metrics = new Metrics(conf);
var stringWriter = new StringWriter();
Console.SetOut(stringWriter);

// Act
metrics.AddMetric("test", 1.0);
metrics.Flush();

// Assert
Assert.Empty(stringWriter.ToString());

// Cleanup
stringWriter.Dispose();
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
}

[Fact]
public void When_MetricsDisabled_Should_Not_PushSingleMetric()
{
// Arrange
var conf = Substitute.For<IPowertoolsConfigurations>();
conf.MetricsDisabled.Returns(true);

IMetrics metrics = new Metrics(conf);
var stringWriter = new StringWriter();
Console.SetOut(stringWriter);

// Act
metrics.PushSingleMetric("test", 1.0, MetricUnit.Count);

// Assert
Assert.Empty(stringWriter.ToString());

// Cleanup
stringWriter.Dispose();
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
}

// Helper method for the tests
internal void TestMethod(ILambdaContext context)
{
Expand Down
Loading