-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathmetrics.md
393 lines (301 loc) · 13.6 KB
/
metrics.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
---
title: Metrics
description: Core utility
---
Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
These metrics can be visualized through [Amazon CloudWatch Console](https://console.aws.amazon.com/cloudwatch/).
**Key features**
* Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob).
* Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc).
* Metrics are created asynchronously by the CloudWatch service, no custom stacks needed.
* Context manager to create a one off metric with a different dimension.
## Terminologies
If you're new to Amazon CloudWatch, there are two terminologies you must be aware of before using this utility:
* **Namespace**. It's the highest level container that will group multiple metrics from multiple services for a given application, for example `ServerlessEcommerce`.
* **Dimensions**. Metrics metadata in key-value format. They help you slice and dice metrics visualization, for example `ColdStart` metric by Payment `service`.
<figure>
<img src="../../media/metrics_terminology.png" />
<figcaption>Metric terminology, visually explained</figcaption>
</figure>
## Install
Depending on your version of Java (either Java 1.8 or 11+), the configuration slightly changes.
=== "Maven Java 11+"
```xml hl_lines="3-7 16 18 24-27"
<dependencies>
...
<dependency>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-metrics</artifactId>
<version>{{ powertools.version }}</version>
</dependency>
...
</dependencies>
...
<!-- configure the aspectj-maven-plugin to compile-time weave (CTW) the aws-lambda-powertools-java aspects into your project -->
<build>
<plugins>
...
<plugin>
<groupId>dev.aspectj</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.13.1</version>
<configuration>
<source>11</source> <!-- or higher -->
<target>11</target> <!-- or higher -->
<complianceLevel>11</complianceLevel> <!-- or higher -->
<aspectLibraries>
<aspectLibrary>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-metrics</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
```
=== "Maven Java 1.8"
```xml hl_lines="3-7 16 18 24-27"
<dependencies>
...
<dependency>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-metrics</artifactId>
<version>{{ powertools.version }}</version>
</dependency>
...
</dependencies>
...
<!-- configure the aspectj-maven-plugin to compile-time weave (CTW) the aws-lambda-powertools-java aspects into your project -->
<build>
<plugins>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.14.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<complianceLevel>1.8</complianceLevel>
<aspectLibraries>
<aspectLibrary>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-metrics</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
```
=== "Gradle Java 11+"
```groovy hl_lines="3 11"
plugins {
id 'java'
id 'io.freefair.aspectj.post-compile-weaving' version '8.1.0'
}
repositories {
mavenCentral()
}
dependencies {
aspect 'software.amazon.lambda:powertools-metrics:{{ powertools.version }}'
}
sourceCompatibility = 11
targetCompatibility = 11
```
=== "Gradle Java 1.8"
```groovy hl_lines="3 11"
plugins {
id 'java'
id 'io.freefair.aspectj.post-compile-weaving' version '6.6.3'
}
repositories {
mavenCentral()
}
dependencies {
aspect 'software.amazon.lambda:powertools-metrics:{{ powertools.version }}'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
```
## Getting started
Metric has two global settings that will be used across all metrics emitted:
Setting | Description | Environment variable | Constructor parameter
------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------
**Metric namespace** | Logical container where all metrics will be placed e.g. `ServerlessAirline` | `POWERTOOLS_METRICS_NAMESPACE` | `namespace`
**Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `service`
!!! tip "Use your application or main service as the metric namespace to easily group all metrics"
=== "template.yaml"
```yaml hl_lines="9 10"
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
...
Runtime: java8
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: payment
POWERTOOLS_METRICS_NAMESPACE: ServerlessAirline
```
=== "MetricsEnabledHandler.java"
```java hl_lines="8"
import software.amazon.lambda.powertools.metrics.Metrics;
public class MetricsEnabledHandler implements RequestHandler<Object, Object> {
MetricsLogger metricsLogger = MetricsUtils.metricsLogger();
@Override
@Metrics(namespace = "ExampleApplication", service = "booking")
public Object handleRequest(Object input, Context context) {
...
}
}
```
You can initialize Metrics anywhere in your code as many times as you need - It'll keep track of your aggregate metrics in memory.
## Creating metrics
You can create metrics using `putMetric`, and manually create dimensions for all your aggregate metrics using `putDimensions`.
=== "MetricsEnabledHandler.java"
```java hl_lines="11 12"
import software.amazon.lambda.powertools.metrics.Metrics;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
public class MetricsEnabledHandler implements RequestHandler<Object, Object> {
MetricsLogger metricsLogger = MetricsUtils.metricsLogger();
@Override
@Metrics(namespace = "ExampleApplication", service = "booking")
public Object handleRequest(Object input, Context context) {
metricsLogger.putDimensions(DimensionSet.of("environment", "prod"));
metricsLogger.putMetric("SuccessfulBooking", 1, Unit.COUNT);
...
}
}
```
!!! tip "The `Unit` enum facilitate finding a supported metric unit by CloudWatch."
!!! note "Metrics overflow"
CloudWatch EMF supports a max of 100 metrics. Metrics utility will flush all metrics when adding the 100th metric while subsequent metrics will be aggregated into a new EMF object, for your convenience.
### Flushing metrics
The `@Metrics` annotation **validates**, **serializes**, and **flushes** all your metrics. During metrics validation,
if no metrics are provided no exception will be raised. If metrics are provided, and any of the following criteria are
not met, `ValidationException` exception will be raised.
!!! tip "Metric validation"
* Maximum of 9 dimensions
If you want to ensure that at least one metric is emitted, you can pass `raiseOnEmptyMetrics = true` to the **@Metrics** annotation:
=== "MetricsRaiseOnEmpty.java"
```java hl_lines="6"
import software.amazon.lambda.powertools.metrics.Metrics;
public class MetricsRaiseOnEmpty implements RequestHandler<Object, Object> {
@Override
@Metrics(raiseOnEmptyMetrics = true)
public Object handleRequest(Object input, Context context) {
...
}
}
```
## Capturing cold start metric
You can capture cold start metrics automatically with `@Metrics` via the `captureColdStart` variable.
=== "MetricsColdStart.java"
```java hl_lines="6"
import software.amazon.lambda.powertools.metrics.Metrics;
public class MetricsColdStart implements RequestHandler<Object, Object> {
@Override
@Metrics(captureColdStart = true)
public Object handleRequest(Object input, Context context) {
...
}
}
```
If it's a cold start invocation, this feature will:
* Create a separate EMF blob solely containing a metric named `ColdStart`
* Add `FunctionName` and `Service` dimensions
This has the advantage of keeping cold start metric separate from your application metrics.
## Advanced
## Adding metadata
You can use `putMetadata` for advanced use cases, where you want to metadata as part of the serialized metrics object.
!!! info
**This will not be available during metrics visualization, use `dimensions` for this purpose.**
=== "App.java"
```java hl_lines="8 9"
import software.amazon.lambda.powertools.metrics.Metrics;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;
public class App implements RequestHandler<Object, Object> {
@Override
@Metrics(namespace = "ServerlessAirline", service = "payment")
public Object handleRequest(Object input, Context context) {
metricsLogger().putMetric("CustomMetric1", 1, Unit.COUNT);
metricsLogger().putMetadata("booking_id", "1234567890");
...
}
}
```
This will be available in CloudWatch Logs to ease operations on high cardinal data.
## Overriding default dimension set
By default, all metrics emitted via module captures `Service` as one of the default dimension. This is either specified via
`POWERTOOLS_SERVICE_NAME` environment variable or via `service` attribute on `Metrics` annotation. If you wish to override the default
Dimension, it can be done via `#!java MetricsUtils.defaultDimensions()`.
=== "App.java"
```java hl_lines="8 9 10"
import software.amazon.lambda.powertools.metrics.Metrics;
import static software.amazon.lambda.powertools.metrics.MetricsUtils;
public class App implements RequestHandler<Object, Object> {
MetricsLogger metricsLogger = MetricsUtils.metricsLogger();
static {
MetricsUtils.defaultDimensions(DimensionSet.of("CustomDimension", "booking"));
}
@Override
@Metrics(namespace = "ExampleApplication", service = "booking")
public Object handleRequest(Object input, Context context) {
...
MetricsUtils.withSingleMetric("Metric2", 1, Unit.COUNT, log -> {});
}
}
```
## Creating a metric with a different dimension
CloudWatch EMF uses the same dimensions across all your metrics. Use `withSingleMetric` if you have a metric that should have different dimensions.
!!! info
Generally, this would be an edge case since you [pay for unique metric](https://aws.amazon.com/cloudwatch/pricing/). Keep the following formula in mind:
**unique metric = (metric_name + dimension_name + dimension_value)**
=== "App.java"
```java hl_lines="7 8 9"
import static software.amazon.lambda.powertools.metrics.MetricsUtils.withSingleMetric;
public class App implements RequestHandler<Object, Object> {
@Override
public Object handleRequest(Object input, Context context) {
withSingleMetric("CustomMetrics2", 1, Unit.COUNT, "Another", (metric) -> {
metric.setDimensions(DimensionSet.of("AnotherService", "CustomService"));
});
}
}
```
## Creating metrics with different configurations
Use `withMetricsLogger` if you have one or more metrics that should have different configurations e.g. dimensions or namespace.
=== "App.java"
```java hl_lines="7 8 9 10 11 12 13"
import static software.amazon.lambda.powertools.metrics.MetricsUtils.withMetricsLogger;
public class App implements RequestHandler<Object, Object> {
@Override
public Object handleRequest(Object input, Context context) {
withMetricsLogger(logger -> {
// override default dimensions
logger.setDimensions(DimensionSet.of("AnotherService", "CustomService"));
// add metrics
logger.putMetric("CustomMetrics1", 1, Unit.COUNT);
logger.putMetric("CustomMetrics2", 5, Unit.COUNT);
});
}
}
```