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

feature - Improve logging #378

Merged
merged 2 commits into from
Jan 15, 2024
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 2.3.0 (15.01.2024)
- Do not add the full content of `context.bindingData` to `customDimensions` for app insights logging anymore as it contains i.e. the request body.
+ Add `AppInsightForHttpTrigger.finalizeWithConfig` which allows you to configure when the request and response body should be logged and allows you to use a body sanitizer to remove sensitive data.

## 2.2.2 (03.11.2023)
+ Added the `context` as a parameter for the `errorResponseHandler` function to enhance error handling capabilities.

Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ export default middleware(functionHandler, [], [postFunction]);

### Logging and Tracing with appInsights

To enhance the logging and tracing with appInsights you can wrap your function with the appInsightWrapper. Currently, this will log the query-parameter
and binding-context of request into the customProperties, which will make your logs more searchable.
To enhance the logging and tracing with appInsights you can wrap your function with the appInsightWrapper.
Currently, this will add request parameters and workflow data into the customProperties, which will make your logs more searchable.

Use the `AppInsightForHttpTrigger` for your http-functions:
```typescript
Expand All @@ -172,6 +172,10 @@ export default middleware([AppInsightForHttpTrigger.setup], handler, [AppInsight

and the `AppInsightForNonHttpTrigger` for functions with different kinds of trigger (e.g. `activityTrigger` or `timerTrigger`).

Per default the request and response bodies of http requests are only logged if the request fails. You can customize this
behavior by using `AppInsightForHttpTrigger.finalizeWithConfig(...)` instead of `AppInsightForHttpTrigger.finalizeAppInsight`.
There you can also provide a function to sanitize the request and response bodies to prevent logging of sensitive data.

## Support and Contact

If you encounter any issues or have questions about using this middleware, please file an issue in this repository or contact the maintainers at <[email protected]> or <[email protected]>.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@senacor/azure-function-middleware",
"version": "2.2.2",
"version": "2.3.0",
"description": "Middleware for azure functions to handle authentication, authorization, error handling and logging",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
76 changes: 55 additions & 21 deletions src/appInsights/appInsightsWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { TelemetryClient } from 'applicationinsights';

import { consoleLogger, createAppInsightsLogger } from './Logger';

type LogBehavior = 'always' | 'on_error' | 'on_success' | 'never';
type LogDataSanitizer = (data: unknown) => unknown;
const noOpLogDataSanitizer: LogDataSanitizer = (data) => data;

const telemetryClients: { [key: string]: TelemetryClient } = {};

const isDisabled =
Expand Down Expand Up @@ -36,31 +40,63 @@ if (!isDisabled) {
console.log('Started appInsights');
}

const setupAppInsight = async (context: Context): Promise<void> => {
if (isDisabled) {
context.log = consoleLogger;
return;
}

const setupTelemetryClient = (context: Context, additionalProperties: object) => {
context.log('Setting up AppInsights');

const telemetryClient = new TelemetryClient();
telemetryClient.setAutoPopulateAzureProperties(true);
telemetryClients[context.invocationId] = telemetryClient;
context.log = createAppInsightsLogger(telemetryClient);

// excluding headers because it contains sensible data
const { headers, ...includedProperties } = context.bindingData;
const { invocationId, sys } = context.bindingData;

telemetryClient.commonProperties = {
...includedProperties,
invocationId,
sys,
...additionalProperties,
...appInsights.defaultClient.commonProperties,
};

context.log('Set up AppInsights');
};

const finalizeAppInsightForHttpTrigger = async (context: Context, req: HttpRequest): Promise<void> => {
const setupAppInsightForHttpTrigger = async (context: Context): Promise<void> => {
if (isDisabled) {
context.log = consoleLogger;
return;
}

setupTelemetryClient(context, { params: context.req?.params });
};

const setupAppInsightForNonHttpTrigger = async (context: Context): Promise<void> => {
if (isDisabled) {
context.log = consoleLogger;
return;
}

setupTelemetryClient(context, { workflowData: context.bindingData.workflowData });
};

const shouldLog = (logBehavior: LogBehavior, isError: boolean) => {
switch (logBehavior) {
case 'always':
return true;
case 'on_error':
return isError;
case 'on_success':
return !isError;
case 'never':
return false;
}
};

const finalizeAppInsightForHttpTrigger = async (
context: Context,
req: HttpRequest,
logBodyBehavior: LogBehavior = 'on_error',
bodySanitizer: LogDataSanitizer = noOpLogDataSanitizer,
): Promise<void> => {
if (isDisabled) {
return;
}
Expand All @@ -84,10 +120,9 @@ const finalizeAppInsightForHttpTrigger = async (context: Context, req: HttpReque
context.log.warn("context.res is empty and properly shouldn't be");
}

const properties: { [key: string]: unknown } = {};

if (context?.res?.status >= 400) {
properties.body = context.req?.body ?? 'NO_REQ_BODY';
if (shouldLog(logBodyBehavior, context?.res?.status >= 400)) {
context.log('Request body:', context.req?.body ? bodySanitizer(context.req?.body) : 'NO_REQ_BODY');
context.log('Response body:', context.res?.body ? bodySanitizer(context.res?.body) : 'NO_RES_BODY');
}

telemetryClient.trackRequest({
Expand All @@ -98,7 +133,6 @@ const finalizeAppInsightForHttpTrigger = async (context: Context, req: HttpReque
url: req.url,
duration: 0,
id: correlationContext?.operation?.id ?? 'UNDEFINED',
properties,
});

telemetryClient.flush();
Expand All @@ -123,8 +157,6 @@ const finalizeAppInsightForNonHttpTrigger = async (context: Context): Promise<vo
...telemetryClient.commonProperties,
};

const properties: { [key: string]: unknown } = {};

telemetryClient.trackRequest({
name: context.executionContext.functionName,
resultCode: 0,
Expand All @@ -133,21 +165,23 @@ const finalizeAppInsightForNonHttpTrigger = async (context: Context): Promise<vo
url: '',
duration: 0,
id: correlationContext?.operation?.id ?? 'UNDEFINED',
properties,
});

telemetryClient.flush();
delete telemetryClients[context.invocationId];
};

const AppInsightForHttpTrigger = {
setup: setupAppInsight,
setup: setupAppInsightForHttpTrigger,
finalizeAppInsight: finalizeAppInsightForHttpTrigger,
finalizeWithConfig:
(logBodyBehavior: LogBehavior, bodySanitizer: LogDataSanitizer) => (context: Context, req: HttpRequest) =>
finalizeAppInsightForHttpTrigger(context, req, logBodyBehavior, bodySanitizer),
};

const AppInsightForNoNHttpTrigger = {
setup: setupAppInsight,
setup: setupAppInsightForNonHttpTrigger,
finalizeAppInsight: finalizeAppInsightForNonHttpTrigger,
};

export { AppInsightForHttpTrigger, AppInsightForNoNHttpTrigger };
export { AppInsightForHttpTrigger, AppInsightForNoNHttpTrigger, LogBehavior, LogDataSanitizer };
Loading