Repository: awslabs/aws-embedded-metrics-node (ts)

Issue:
Calling flush would reset the namespace as well
Documentation for flush()

>flush()
Flushes the current MetricsContext to the configured sink and resets all properties, dimensions and metric values. The namespace and default dimensions will be preserved across flushes.

Namespace is set on the context and at the end of flush, context is set back to empty.

Either the documentation or the behavior of flush should be updated.

Pull request description:
fix(#15): preserve the logger context across flushes
Closes #15

Patch:
diff --git a/src/logger/MetricsLogger.ts b/src/logger/MetricsLogger.ts
index d9a86be..fe5ee84 100644
--- a/src/logger/MetricsLogger.ts
+++ b/src/logger/MetricsLogger.ts
@@ -48,7 +48,7 @@ export class MetricsLogger {
 
     // accept and reset the context
     sink.accept(this.context);
-    this.context = MetricsContext.empty();
+    this.context = this.context.createCopyWithContext();
   }
 
   /**


Test patch:
diff --git a/src/logger/__tests__/MetricsLogger.test.ts b/src/logger/__tests__/MetricsLogger.test.ts
index 0d5ecb9..984ca79 100644
--- a/src/logger/__tests__/MetricsLogger.test.ts
+++ b/src/logger/__tests__/MetricsLogger.test.ts
@@ -261,6 +261,42 @@ test('flush() delegates context configuration to the environment by calling conf
   expect(environment.configureContext).toBeCalled();
 });
 
+test('context is preserved across flush() calls', async () => {
+  // arrange
+  const expectedNamespace = 'Namespace';
+  const metricKey = 'Metric';
+  const expectedDimensionKey = 'Dim';
+  const expectedPropertyKey = 'Prop';
+  const expectedValues = 'Value';
+
+  const dimensions: Record<string, string> = {};
+  dimensions[expectedDimensionKey] = expectedValues;
+
+  logger.setNamespace(expectedNamespace);
+  logger.setProperty(expectedPropertyKey, expectedValues);
+  logger.setDimensions(dimensions);
+
+  // act
+  logger.putMetric(metricKey, 0);
+  await logger.flush();
+
+  logger.putMetric(metricKey, 1);
+  await logger.flush();
+
+  // assert
+  expect(sink.events).toHaveLength(2);
+  for (let i = 0; i < sink.events.length; i++) {
+    const evt = sink.events[i];
+    // namespace, properties, dimensions should survive flushes
+    expect(evt.namespace).toBe(expectedNamespace);
+    expect(evt.getDimensions()[0][expectedDimensionKey]).toBe(expectedValues);
+    expect(evt.properties[expectedPropertyKey]).toBe(expectedValues);
+    // metric values should not survive flushes
+    // @ts-ignore
+    expect(evt.metrics.get(metricKey).values).toStrictEqual([i]);
+  }
+});
+
 const expectDimension = (key: string, value: string) => {
   expect(sink.events).toHaveLength(1);
   const dimensionSets = sink.events[0].getDimensions();