Skip to content

Commit

Permalink
docs: update environment variable tables for utilities (#1153)
Browse files Browse the repository at this point in the history
* chore(docs): update environment variable table

* Correct the default value for the POWERTOOLS_METRICS_NAMESPACE env var
* Refer reader to utility page for further info on env vars

* chore(docs): add default, allowed and example values to utility docs

* Extract default and allowed values from description to their own cols
* Add allowed values, example and default columns
* Correct default value for metrics namespace

* refactor: set default service name in utility class

Previously the Metric and Tracer classes did not set a service name if
one was not provided. There was no default service name.
This commit sets a default service name in the Utility class, and
updates the Tracer, Metric and Logger classes to use it.

* test: fix Logger tests

Add missing `defaultServiceName` property to expected Logger object
Correct typo in test names

* test(tracer): remove invalid test

Remove a test that is no longer valid. As there is a default service
name, the tracer should not be enabled even if there is a service name
Update the `addServiceAnnotation` function to remove redundant check

* docs(metrics): correct default value

* test(metrics): update metric tests to account for default service dim

The `service_name` is now set by default. This means it is always
present in metric dimensions. This commit updates the tests to account
for this change

* test(tracer): add test for default service name

* test(utility): add test for new method

Add test for getDefaultServiceName method

* test(utility): fix getdefaultservicename test

* refactor: extract isvalidservicename method to utility class

This commit extracts the isValidServiceName method from the Tracer class
to the Utility class.

* test(utility): fix test description

* refactor: change utility class methods from public to protected

* test(utility): refactor tests to allow for protected methods

* docs(index): remove quotation marks from default values

* test(metrics): add comments to explain magic numbers

* doc(tracer): add explanation for definite assignment assertion operator

* test(tracer): refactor test to match project norms
  • Loading branch information
ConnorKirk authored Nov 15, 2022
1 parent 664c4da commit c37932d
Show file tree
Hide file tree
Showing 13 changed files with 128 additions and 59 deletions.
12 changes: 6 additions & 6 deletions docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ The library requires two settings. You can set them as environment variables, or

These settings will be used across all logs emitted:

| Setting | Description | Environment variable | Constructor parameter |
|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------|-----------------------|
| **Service name** | Sets the name of service of which the Lambda function is part of, that will be present across all log statements | `POWERTOOLS_SERVICE_NAME` | `serviceName` |
| **Logging level** | Sets how verbose Logger should be (INFO, by default). Supported values are: `DEBUG`, `INFO`, `WARN`, `ERROR` | `LOG_LEVEL` | `logLevel` |
| **Log incoming event** | Whether to log or not the incoming event when using the decorator or middleware. Supported values are: `true`, or `false`, disabled by default | `POWERTOOLS_LOGGER_LOG_EVENT` | `logEvent` |
| **Debug log sampling** | Probability that a Lambda invocation will print all the log items regardless of the log level setting. Supported values range from `0.0` to `1` | `POWERTOOLS_LOGGER_SAMPLE_RATE` | `sampleRateValue` |
| Setting | Description | Environment variable | Default Value | Allowed Values | Example Value | Constructor parameter |
|-------------------------|------------------------------------------------------------------------------------------------------------------|---------------------------------|---------------------|--------------------------------|--------------------|-----------------------|
| **Service name** | Sets the name of service of which the Lambda function is part of, that will be present across all log statements | `POWERTOOLS_SERVICE_NAME` | `service_undefined` | Any string | `serverlessAirline`| `serviceName` |
| **Logging level** | Sets how verbose Logger should be | `LOG_LEVEL` | `info` |`DEBUG`, `INFO`, `WARN`, `ERROR`| `ERROR` | `logLevel` |
| **Log incoming event** | Whether to log or not the incoming event when using the decorator or middleware. | `POWERTOOLS_LOGGER_LOG_EVENT` | `false` | `true`, `false` | `false` | `logEvent` |
| **Debug log sampling** | Probability that a Lambda invocation will print all the log items regardless of the log level setting. | `POWERTOOLS_LOGGER_SAMPLE_RATE` | `0` | `0.0` to `1` | `0.5` | `sampleRateValue` |

#### Example using AWS Serverless Application Model (SAM)

Expand Down
8 changes: 4 additions & 4 deletions docs/core/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ The library requires two settings. You can set them as environment variables, or

These settings will be used across all metrics emitted:

| Setting | Description | Environment variable | Constructor parameter |
|----------------------|---------------------------------------------------------------------------------|--------------------------------|-----------------------|
| **Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `serviceName` |
| **Metric namespace** | Logical container where all metrics will be placed e.g. `serverlessAirline` | `POWERTOOLS_METRICS_NAMESPACE` | `namespace` |
| Setting | Description | Environment variable | Default | Allowed Values | Example | Constructor parameter |
|----------------------|-----------------------------------------------------------------|-------------------------------|--------------------|----------------|--------------------|-----------------------|
| **Service** | Optionally, sets **service** metric dimension across all metrics| `POWERTOOLS_SERVICE_NAME` | `service_undefined`| Any string | `serverlessAirline`| `serviceName` |
| **Metric namespace** | Logical container where all metrics will be placed | `POWERTOOLS_METRICS_NAMESPACE`| `default_namespace`| Any string | `serverlessAirline`| `default_namespace` |

!!! tip
Use your application name or main service as the metric namespace to easily group all metrics
Expand Down
14 changes: 7 additions & 7 deletions docs/core/tracer.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler.

The library has three optional settings. You can set them as environment variables, or pass them in the constructor:

| Setting | Description | Environment variable | Constructor parameter |
|----------------------------|-----------------------------------------------------------------------------------------------------------------| -------------------------------------------|------------------------|
| **Service name** | Sets an annotation with the **name of the service** across all traces e.g. `serverlessAirline` | `POWERTOOLS_SERVICE_NAME` | `serviceName` |
| **Tracing enabled** | Enables or disables tracing. By default tracing is enabled when running in AWS Lambda | `POWERTOOLS_TRACE_ENABLED` | `enabled` |
| **Capture HTTPs Requests** | Defines whether HTTPs requests will be traced or not, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS` | `captureHTTPsRequests` |
| **Capture Response** | Defines whether functions responses are serialized as metadata, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_RESPONSE` | `captureResult` |
| **Capture Errors** | Defines whether functions errors are serialized as metadata, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_ERROR` | N/A |
| Setting | Description | Environment variable | Default | Allowed Values | Example | Constructor parameter |
|----------------------------|-----------------------------------------------------------------------| -------------------------------------------|--------------------|------------------|--------------------|------------------------|
| **Service name** | Sets an annotation with the **name of the service** across all traces | `POWERTOOLS_SERVICE_NAME` | `service_undefined`| Any string | `serverlessAirline`| `serviceName` |
| **Tracing enabled** | Enables or disables tracing. | `POWERTOOLS_TRACE_ENABLED` | `true `| `true` or `false`| `false` | `enabled` |
| **Capture HTTPs Requests** | Defines whether HTTPs requests will be traced or not | `POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS` | `true` | `true` or `false`| `false` | `captureHTTPsRequests` |
| **Capture Response** | Defines whether functions responses are serialized as metadata | `POWERTOOLS_TRACER_CAPTURE_RESPONSE` | `true` | `true` or `false`| `false` | `captureResult` |
| **Capture Errors** | Defines whether functions errors are serialized as metadata | `POWERTOOLS_TRACER_CAPTURE_ERROR` | `true` | `true` or `false`| `false` | N/A |

!!! note
Before your use this utility, your AWS Lambda function must have [Active Tracing enabled](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html) as well as [have permissions](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html#services-xray-permissions) to send traces to AWS X-Ray
Expand Down
6 changes: 4 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,8 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al

| Environment variable | Description | Utility | Default |
|----------------------------------------------|----------------------------------------------------------------------------------------|---------------------------|-----------------------|
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | All | `"service_undefined"` |
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | [Metrics](./core/metrics) | `None` |
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` |
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | [Metrics](./core/metrics) | `default_namespace` |
| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](./core/tracer) | `true` |
| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Captures Lambda or method return as metadata. | [Tracer](./core/tracer) | `true` |
| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Captures Lambda or method exception as metadata. | [Tracer](./core/tracer) | `true` |
Expand All @@ -296,6 +296,8 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al
| **POWERTOOLS_DEV** | Increase JSON indentation to ease debugging when running functions locally or in a non-production environment | [Logger](./core/logger) | `false` |
| **LOG_LEVEL** | Sets logging level | [Logger](./core/logger) | `INFO` |

Each Utility page provides information on example values and allowed values

## Tenets

These are our core principles to guide our decision making.
Expand Down
15 changes: 14 additions & 1 deletion packages/commons/src/Utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@
* ```
*/
export class Utility {

private coldStart: boolean = true;
private readonly defaultServiceName: string = 'service_undefined';

public getColdStart(): boolean {
if (this.coldStart) {
Expand All @@ -73,4 +73,17 @@ export class Utility {
return this.getColdStart();
}

protected getDefaultServiceName(): string {
return this.defaultServiceName;
}

/**
* Validate that the service name provided is valid.
* Used internally during initialization.
*
* @param serviceName - Service name to validate
*/
protected isValidServiceName(serviceName?: string): boolean {
return typeof serviceName === 'string' && serviceName.trim().length > 0;
}
}
45 changes: 45 additions & 0 deletions packages/commons/tests/unit/Utility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@ describe('Class: Utility', () => {
jest.resetModules();
});

describe('Method: getDefaultServiceName', ()=> {
test('it should return the default service name', ()=> {
class PowerTool extends Utility {
public constructor() {
super();
}

public dummyMethod(): string {
return this.getDefaultServiceName();
}
}

const powertool = new PowerTool();
const result = powertool.dummyMethod();
expect(result).toBe('service_undefined');
});
});

describe('Method: getColdStart', () => {

test('when called multiple times on the parent class, it returns true the first time, then false afterwards', () => {
Expand Down Expand Up @@ -142,4 +160,31 @@ describe('Class: Utility', () => {

});

describe('Method: isValidServiceName', () => {
class PowerTool extends Utility {
public constructor() {
super();
}

public dummyMethod(name:string): boolean {
return this.isValidServiceName(name);
}
}
test('it should allow valid strings', ()=> {
const powertool = new PowerTool();
const goodName = 'serverlessAirline';

const result = powertool.dummyMethod(goodName);

expect(result).toBe(true);
});

test('it should not allow empty strings', ()=> {
const tooShort = '';
const powertool = new PowerTool();
const result = powertool.dummyMethod(tooShort);

expect(result).toBe(false);
});
});
});
4 changes: 1 addition & 3 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,6 @@ class Logger extends Utility implements ClassThatLogs {

private static readonly defaultLogLevel: LogLevel = 'INFO';

private static readonly defaultServiceName: string = 'service_undefined';

// envVarsService is always initialized in the constructor in setOptions()
private envVarsService!: EnvironmentVariablesService;

Expand Down Expand Up @@ -803,7 +801,7 @@ class Logger extends Utility implements ClassThatLogs {
this.getEnvVarsService().getCurrentEnvironment(),
sampleRateValue: this.getSampleRateValue(),
serviceName:
serviceName || this.getCustomConfigService()?.getServiceName() || this.getEnvVarsService().getServiceName() || Logger.defaultServiceName,
serviceName || this.getCustomConfigService()?.getServiceName() || this.getEnvVarsService().getServiceName() || this.getDefaultServiceName(),
},
persistentLogAttributes,
);
Expand Down
5 changes: 5 additions & 0 deletions packages/logger/tests/unit/Logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ describe('Class: Logger', () => {
console: expect.any(Console),
coldStart: false, // This is now false because the `coldStart` attribute has been already accessed once by the `addContext` method
customConfigService: undefined,
defaultServiceName: 'service_undefined',
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
Expand Down Expand Up @@ -1265,6 +1266,7 @@ describe('Class: Logger', () => {
console: expect.any(Console),
coldStart: true,
customConfigService: undefined,
defaultServiceName: 'service_undefined',
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
Expand All @@ -1290,6 +1292,7 @@ describe('Class: Logger', () => {
console: expect.any(Console),
coldStart: true,
customConfigService: undefined,
defaultServiceName: 'service_undefined',
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
Expand Down Expand Up @@ -1317,6 +1320,7 @@ describe('Class: Logger', () => {
console: expect.any(Console),
coldStart: true,
customConfigService: undefined,
defaultServiceName: 'service_undefined',
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
Expand All @@ -1342,6 +1346,7 @@ describe('Class: Logger', () => {
console: expect.any(Console),
coldStart: true,
customConfigService: undefined,
defaultServiceName: 'service_undefined',
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
Expand Down
Loading

0 comments on commit c37932d

Please sign in to comment.