Skip to content

Commit b4929e0

Browse files
committed
docs(logger): extract Logger code snippets in separate files aws-powertools#1220
1 parent 4307a7c commit b4929e0

18 files changed

+375
-374
lines changed

Diff for: docs/core/logger.md

+17-374
Large diffs are not rendered by default.

Diff for: docs/snippets/logger/appendKeys.ts

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
// Add persistent log keys via the constructor
4+
const logger = new Logger({
5+
persistentLogAttributes: {
6+
aws_account_id: '123456789012',
7+
aws_region: 'eu-west-1',
8+
logger: {
9+
name: '@aws-lambda-powertools/logger',
10+
version: '0.0.1',
11+
},
12+
extra_key: "some-value"
13+
}
14+
});
15+
16+
// OR add persistent log keys to an existing Logger instance with the appendKeys method:
17+
// logger.appendKeys({
18+
// aws_account_id: '123456789012',
19+
// aws_region: 'eu-west-1',
20+
// logger: {
21+
// name: '@aws-lambda-powertools/logger',
22+
// version: '0.0.1',
23+
// },
24+
// extra_key: "some-value"
25+
// });
26+
27+
export const handler = async (_event: any, _context: any): Promise<unknown> => {
28+
29+
// If you don't want to log the "extra_key" attribute in your logs, you can remove it
30+
logger.removeKeys(["extra_key"])
31+
32+
// This info log will print all extra custom attributes added above
33+
// Extra attributes: logger object with name and version of the logger library, awsAccountId, awsRegion
34+
logger.info('This is an INFO log');
35+
logger.info('This is another INFO log');
36+
37+
return {
38+
foo: 'bar'
39+
};
40+
41+
};

Diff for: docs/snippets/logger/basicUsage.ts

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
const logger = new Logger({ serviceName: 'serverlessAirline' });
4+
5+
export const handler = async (_event, _context): Promise<void> => {
6+
// ...
7+
};

Diff for: docs/snippets/logger/bringYourOwnFormatterClass.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import { MyCompanyLogFormatter } from './utils/formatters/MyCompanyLogFormatter';
3+
4+
const logger = new Logger({
5+
logFormatter: new MyCompanyLogFormatter(),
6+
logLevel: 'DEBUG',
7+
serviceName: 'serverlessAirline',
8+
sampleRateValue: 0.5,
9+
persistentLogAttributes: {
10+
awsAccountId: process.env.AWS_ACCOUNT_ID,
11+
logger: {
12+
name: '@aws-lambda-powertools/logger',
13+
version: '0.0.1'
14+
}
15+
},
16+
});
17+
18+
export const handler = async (event, context): Promise<void> => {
19+
20+
logger.addContext(context);
21+
22+
logger.info('This is an INFO log', { correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } });
23+
24+
};

Diff for: docs/snippets/logger/bringYourOwnFormatterHandler.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import { MyCompanyLogFormatter } from './utils/formatters/MyCompanyLogFormatter';
3+
4+
const logger = new Logger({
5+
logFormatter: new MyCompanyLogFormatter(),
6+
logLevel: 'DEBUG',
7+
serviceName: 'serverlessAirline',
8+
sampleRateValue: 0.5,
9+
persistentLogAttributes: {
10+
awsAccountId: process.env.AWS_ACCOUNT_ID,
11+
logger: {
12+
name: '@aws-lambda-powertools/logger',
13+
version: '0.0.1'
14+
}
15+
},
16+
});
17+
18+
export const handler = async (event, context): Promise<void> => {
19+
20+
logger.addContext(context);
21+
22+
logger.info('This is an INFO log', { correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } });
23+
24+
};

Diff for: docs/snippets/logger/clearStateDecorator.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import { LambdaInterface } from '@aws-lambda-powertools/commons';
3+
4+
// Persistent attributes added outside the handler will be
5+
// cached across invocations
6+
const logger = new Logger({
7+
logLevel: 'DEBUG',
8+
persistentLogAttributes: {
9+
foo: "bar",
10+
biz: "baz"
11+
}
12+
});
13+
14+
class Lambda implements LambdaInterface {
15+
// Enable the clear state flag
16+
@logger.injectLambdaContext({ clearState: true })
17+
public async handler(_event: any, _context: any): Promise<void> {
18+
// Persistent attributes added inside the handler will NOT be cached
19+
// across invocations
20+
if (event['special_key'] === '123456'){
21+
logger.appendKeys({
22+
details: { special_key: '123456' }
23+
});
24+
}
25+
logger.debug('This is a DEBUG log');
26+
}
27+
28+
}
29+
30+
const myFunction = new Lambda();
31+
export const handler = myFunction.handler.bind(myFunction); // (1)

Diff for: docs/snippets/logger/clearStateMiddy.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
2+
import middy from '@middy/core';
3+
4+
// Persistent attributes added outside the handler will be
5+
// cached across invocations
6+
const logger = new Logger({
7+
logLevel: 'DEBUG',
8+
persistentLogAttributes: {
9+
foo: "bar",
10+
biz: "baz"
11+
}
12+
});
13+
14+
const lambdaHandler = async (event: { special_key: string }, _context: any): Promise<void> => {
15+
// Persistent attributes added inside the handler will NOT be cached
16+
// across invocations
17+
if (event['special_key'] === '123456') {
18+
logger.appendKeys({
19+
details: { special_key: event['special_key'] }
20+
});
21+
}
22+
logger.debug('This is a DEBUG log');
23+
};
24+
25+
// Enable the clear state flag
26+
export const handler = middy(lambdaHandler)
27+
.use(injectLambdaContext(logger, { clearState: true }));

Diff for: docs/snippets/logger/createChild.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
// With this logger, all the INFO logs will be printed
4+
const logger = new Logger({
5+
logLevel: 'INFO'
6+
});
7+
8+
// With this logger, only the ERROR logs will be printed
9+
const childLogger = logger.createChild({
10+
logLevel: 'ERROR'
11+
});
12+
13+
export const handler = async (_event: any, _context: any): Promise<void> => {
14+
15+
logger.info('This is an INFO log, from the parent logger');
16+
logger.error('This is an ERROR log, from the parent logger');
17+
18+
childLogger.info('This is an INFO log, from the child logger');
19+
childLogger.error('This is an ERROR log, from the child logger');
20+
21+
};

Diff for: docs/snippets/logger/decorator.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import { LambdaInterface } from '@aws-lambda-powertools/commons';
3+
4+
const logger = new Logger();
5+
6+
class Lambda implements LambdaInterface {
7+
// Decorate your handler class method
8+
@logger.injectLambdaContext()
9+
public async handler(_event: any, _context: any): Promise<void> {
10+
logger.info('This is an INFO log with some context');
11+
}
12+
13+
}
14+
15+
const myFunction = new Lambda();
16+
export const handler = myFunction.handler.bind(myFunction); // (1)

Diff for: docs/snippets/logger/eventDecorator.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import { LambdaInterface } from '@aws-lambda-powertools/commons';
3+
4+
const logger = new Logger();
5+
6+
class Lambda implements LambdaInterface {
7+
// Set the log event flag to true
8+
@logger.injectLambdaContext({ logEvent: true })
9+
public async handler(_event: any, _context: any): Promise<void> {
10+
logger.info('This is an INFO log with some context');
11+
}
12+
13+
}
14+
15+
const myFunction = new Lambda();
16+
export const handler = myFunction.handler.bind(myFunction); // (1)

Diff for: docs/snippets/logger/eventMiddy.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
2+
import middy from '@middy/core';
3+
4+
const logger = new Logger();
5+
6+
const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
7+
logger.info('This is an INFO log with some context');
8+
};
9+
10+
export const handler = middy(lambdaHandler)
11+
.use(injectLambdaContext(logger, { logEvent: true }));

Diff for: docs/snippets/logger/extraData.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
const logger = new Logger();
4+
5+
export const handler = async (event: any, _context: any): Promise<unknown> => {
6+
7+
const myImportantVariable = {
8+
foo: 'bar'
9+
};
10+
11+
// Log additional data in single log items
12+
13+
// As second parameter
14+
logger.info('This is a log with an extra variable', { data: myImportantVariable });
15+
16+
// You can also pass multiple parameters containing arbitrary objects
17+
logger.info('This is a log with 3 extra objects',
18+
{ data: myImportantVariable },
19+
{ correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } },
20+
{ lambdaEvent: event }
21+
);
22+
23+
// Simply pass a string for logging additional data
24+
logger.info('This is a log with additional string value', 'string value');
25+
26+
// Directly passing an object containing both the message and the additional info
27+
const logObject = {
28+
message: 'This is a log message',
29+
additionalValue: 42
30+
};
31+
32+
logger.info(logObject);
33+
34+
return {
35+
foo: 'bar'
36+
};
37+
38+
};

Diff for: docs/snippets/logger/logError.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
const logger = new Logger();
4+
5+
export const handler = async (_event: any, _context: any): Promise<void> => {
6+
7+
try {
8+
throw new Error('Unexpected error #1');
9+
} catch (error) {
10+
// Log information about the error using the default "error" key
11+
logger.error('This is the first error', error as Error);
12+
}
13+
14+
try {
15+
throw new Error('Unexpected error #2');
16+
} catch (error) {
17+
// Log information about the error using a custom "myCustomErrorKey" key
18+
logger.error('This is the second error', { myCustomErrorKey: error as Error } );
19+
}
20+
21+
};

Diff for: docs/snippets/logger/logSampling.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
// Notice the log level set to 'ERROR'
4+
const logger = new Logger({
5+
logLevel: 'ERROR',
6+
sampleRateValue: 0.5
7+
});
8+
9+
export const handler = async (_event: any, _context: any): Promise<void> => {
10+
11+
// This log item (equal to log level 'ERROR') will be printed to standard output
12+
// in all Lambda invocations
13+
logger.error('This is an ERROR log');
14+
15+
// These log items (below the log level 'ERROR') have ~50% chance
16+
// of being printed in a Lambda invocation
17+
logger.debug('This is a DEBUG log that has 50% chance of being printed');
18+
logger.info('This is an INFO log that has 50% chance of being printed');
19+
logger.warn('This is a WARN log that has 50% chance of being printed');
20+
21+
// Optional: refresh sample rate calculation on runtime
22+
// logger.refreshSampleRateCalculation();
23+
24+
};

Diff for: docs/snippets/logger/manual.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
const logger = new Logger();
4+
5+
export const handler = async (_event, context): Promise<void> => {
6+
7+
logger.addContext(context);
8+
9+
logger.info('This is an INFO log with some context');
10+
11+
};

Diff for: docs/snippets/logger/middy.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
2+
import middy from '@middy/core';
3+
4+
const logger = new Logger();
5+
6+
const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
7+
logger.info('This is an INFO log with some context');
8+
};
9+
10+
export const handler = middy(lambdaHandler)
11+
.use(injectLambdaContext(logger));

Diff for: docs/snippets/logger/sam.ts

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
3+
// Logger parameters fetched from the environment variables (see template.yaml tab)
4+
const logger = new Logger();
5+
6+
// You can also pass the parameters in the constructor
7+
// const logger = new Logger({
8+
// logLevel: 'WARN',
9+
// serviceName: 'serverlessAirline'
10+
// });

Diff for: docs/snippets/logger/unitTesting.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const dummyContext = {
2+
callbackWaitsForEmptyEventLoop: true,
3+
functionVersion: '$LATEST',
4+
functionName: 'foo-bar-function',
5+
memoryLimitInMB: '128',
6+
logGroupName: '/aws/lambda/foo-bar-function',
7+
logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456',
8+
invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function',
9+
awsRequestId: 'c6af9ac6-7b61-11e6-9a41-93e812345678',
10+
getRemainingTimeInMillis: () => 1234,
11+
done: () => console.log('Done!'),
12+
fail: () => console.log('Failed!'),
13+
succeed: () => console.log('Succeeded!'),
14+
};
15+
16+
describe('MyUnitTest', () => {
17+
18+
test('Lambda invoked successfully', async () => {
19+
20+
const testEvent = { test: 'test' };
21+
await handler(testEvent, dummyContext);
22+
23+
});
24+
25+
});

0 commit comments

Comments
 (0)