Skip to content

Commit

Permalink
docs(logger): extract Logger code snippets in separate files aws-powe…
Browse files Browse the repository at this point in the history
  • Loading branch information
niko-achilles committed Jan 12, 2023
1 parent 4307a7c commit b4929e0
Show file tree
Hide file tree
Showing 18 changed files with 375 additions and 374 deletions.
391 changes: 17 additions & 374 deletions docs/core/logger.md

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions docs/snippets/logger/appendKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Logger } from '@aws-lambda-powertools/logger';

// Add persistent log keys via the constructor
const logger = new Logger({
persistentLogAttributes: {
aws_account_id: '123456789012',
aws_region: 'eu-west-1',
logger: {
name: '@aws-lambda-powertools/logger',
version: '0.0.1',
},
extra_key: "some-value"
}
});

// OR add persistent log keys to an existing Logger instance with the appendKeys method:
// logger.appendKeys({
// aws_account_id: '123456789012',
// aws_region: 'eu-west-1',
// logger: {
// name: '@aws-lambda-powertools/logger',
// version: '0.0.1',
// },
// extra_key: "some-value"
// });

export const handler = async (_event: any, _context: any): Promise<unknown> => {

// If you don't want to log the "extra_key" attribute in your logs, you can remove it
logger.removeKeys(["extra_key"])

// This info log will print all extra custom attributes added above
// Extra attributes: logger object with name and version of the logger library, awsAccountId, awsRegion
logger.info('This is an INFO log');
logger.info('This is another INFO log');

return {
foo: 'bar'
};

};
7 changes: 7 additions & 0 deletions docs/snippets/logger/basicUsage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger({ serviceName: 'serverlessAirline' });

export const handler = async (_event, _context): Promise<void> => {
// ...
};
24 changes: 24 additions & 0 deletions docs/snippets/logger/bringYourOwnFormatterClass.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { MyCompanyLogFormatter } from './utils/formatters/MyCompanyLogFormatter';

const logger = new Logger({
logFormatter: new MyCompanyLogFormatter(),
logLevel: 'DEBUG',
serviceName: 'serverlessAirline',
sampleRateValue: 0.5,
persistentLogAttributes: {
awsAccountId: process.env.AWS_ACCOUNT_ID,
logger: {
name: '@aws-lambda-powertools/logger',
version: '0.0.1'
}
},
});

export const handler = async (event, context): Promise<void> => {

logger.addContext(context);

logger.info('This is an INFO log', { correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } });

};
24 changes: 24 additions & 0 deletions docs/snippets/logger/bringYourOwnFormatterHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { MyCompanyLogFormatter } from './utils/formatters/MyCompanyLogFormatter';

const logger = new Logger({
logFormatter: new MyCompanyLogFormatter(),
logLevel: 'DEBUG',
serviceName: 'serverlessAirline',
sampleRateValue: 0.5,
persistentLogAttributes: {
awsAccountId: process.env.AWS_ACCOUNT_ID,
logger: {
name: '@aws-lambda-powertools/logger',
version: '0.0.1'
}
},
});

export const handler = async (event, context): Promise<void> => {

logger.addContext(context);

logger.info('This is an INFO log', { correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } });

};
31 changes: 31 additions & 0 deletions docs/snippets/logger/clearStateDecorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { LambdaInterface } from '@aws-lambda-powertools/commons';

// Persistent attributes added outside the handler will be
// cached across invocations
const logger = new Logger({
logLevel: 'DEBUG',
persistentLogAttributes: {
foo: "bar",
biz: "baz"
}
});

class Lambda implements LambdaInterface {
// Enable the clear state flag
@logger.injectLambdaContext({ clearState: true })
public async handler(_event: any, _context: any): Promise<void> {
// Persistent attributes added inside the handler will NOT be cached
// across invocations
if (event['special_key'] === '123456'){
logger.appendKeys({
details: { special_key: '123456' }
});
}
logger.debug('This is a DEBUG log');
}

}

const myFunction = new Lambda();
export const handler = myFunction.handler.bind(myFunction); // (1)
27 changes: 27 additions & 0 deletions docs/snippets/logger/clearStateMiddy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
import middy from '@middy/core';

// Persistent attributes added outside the handler will be
// cached across invocations
const logger = new Logger({
logLevel: 'DEBUG',
persistentLogAttributes: {
foo: "bar",
biz: "baz"
}
});

const lambdaHandler = async (event: { special_key: string }, _context: any): Promise<void> => {
// Persistent attributes added inside the handler will NOT be cached
// across invocations
if (event['special_key'] === '123456') {
logger.appendKeys({
details: { special_key: event['special_key'] }
});
}
logger.debug('This is a DEBUG log');
};

// Enable the clear state flag
export const handler = middy(lambdaHandler)
.use(injectLambdaContext(logger, { clearState: true }));
21 changes: 21 additions & 0 deletions docs/snippets/logger/createChild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Logger } from '@aws-lambda-powertools/logger';

// With this logger, all the INFO logs will be printed
const logger = new Logger({
logLevel: 'INFO'
});

// With this logger, only the ERROR logs will be printed
const childLogger = logger.createChild({
logLevel: 'ERROR'
});

export const handler = async (_event: any, _context: any): Promise<void> => {

logger.info('This is an INFO log, from the parent logger');
logger.error('This is an ERROR log, from the parent logger');

childLogger.info('This is an INFO log, from the child logger');
childLogger.error('This is an ERROR log, from the child logger');

};
16 changes: 16 additions & 0 deletions docs/snippets/logger/decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { LambdaInterface } from '@aws-lambda-powertools/commons';

const logger = new Logger();

class Lambda implements LambdaInterface {
// Decorate your handler class method
@logger.injectLambdaContext()
public async handler(_event: any, _context: any): Promise<void> {
logger.info('This is an INFO log with some context');
}

}

const myFunction = new Lambda();
export const handler = myFunction.handler.bind(myFunction); // (1)
16 changes: 16 additions & 0 deletions docs/snippets/logger/eventDecorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { LambdaInterface } from '@aws-lambda-powertools/commons';

const logger = new Logger();

class Lambda implements LambdaInterface {
// Set the log event flag to true
@logger.injectLambdaContext({ logEvent: true })
public async handler(_event: any, _context: any): Promise<void> {
logger.info('This is an INFO log with some context');
}

}

const myFunction = new Lambda();
export const handler = myFunction.handler.bind(myFunction); // (1)
11 changes: 11 additions & 0 deletions docs/snippets/logger/eventMiddy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
import middy from '@middy/core';

const logger = new Logger();

const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
logger.info('This is an INFO log with some context');
};

export const handler = middy(lambdaHandler)
.use(injectLambdaContext(logger, { logEvent: true }));
38 changes: 38 additions & 0 deletions docs/snippets/logger/extraData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger();

export const handler = async (event: any, _context: any): Promise<unknown> => {

const myImportantVariable = {
foo: 'bar'
};

// Log additional data in single log items

// As second parameter
logger.info('This is a log with an extra variable', { data: myImportantVariable });

// You can also pass multiple parameters containing arbitrary objects
logger.info('This is a log with 3 extra objects',
{ data: myImportantVariable },
{ correlationIds: { myCustomCorrelationId: 'foo-bar-baz' } },
{ lambdaEvent: event }
);

// Simply pass a string for logging additional data
logger.info('This is a log with additional string value', 'string value');

// Directly passing an object containing both the message and the additional info
const logObject = {
message: 'This is a log message',
additionalValue: 42
};

logger.info(logObject);

return {
foo: 'bar'
};

};
21 changes: 21 additions & 0 deletions docs/snippets/logger/logError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger();

export const handler = async (_event: any, _context: any): Promise<void> => {

try {
throw new Error('Unexpected error #1');
} catch (error) {
// Log information about the error using the default "error" key
logger.error('This is the first error', error as Error);
}

try {
throw new Error('Unexpected error #2');
} catch (error) {
// Log information about the error using a custom "myCustomErrorKey" key
logger.error('This is the second error', { myCustomErrorKey: error as Error } );
}

};
24 changes: 24 additions & 0 deletions docs/snippets/logger/logSampling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Logger } from '@aws-lambda-powertools/logger';

// Notice the log level set to 'ERROR'
const logger = new Logger({
logLevel: 'ERROR',
sampleRateValue: 0.5
});

export const handler = async (_event: any, _context: any): Promise<void> => {

// This log item (equal to log level 'ERROR') will be printed to standard output
// in all Lambda invocations
logger.error('This is an ERROR log');

// These log items (below the log level 'ERROR') have ~50% chance
// of being printed in a Lambda invocation
logger.debug('This is a DEBUG log that has 50% chance of being printed');
logger.info('This is an INFO log that has 50% chance of being printed');
logger.warn('This is a WARN log that has 50% chance of being printed');

// Optional: refresh sample rate calculation on runtime
// logger.refreshSampleRateCalculation();

};
11 changes: 11 additions & 0 deletions docs/snippets/logger/manual.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger();

export const handler = async (_event, context): Promise<void> => {

logger.addContext(context);

logger.info('This is an INFO log with some context');

};
11 changes: 11 additions & 0 deletions docs/snippets/logger/middy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
import middy from '@middy/core';

const logger = new Logger();

const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
logger.info('This is an INFO log with some context');
};

export const handler = middy(lambdaHandler)
.use(injectLambdaContext(logger));
10 changes: 10 additions & 0 deletions docs/snippets/logger/sam.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Logger } from '@aws-lambda-powertools/logger';

// Logger parameters fetched from the environment variables (see template.yaml tab)
const logger = new Logger();

// You can also pass the parameters in the constructor
// const logger = new Logger({
// logLevel: 'WARN',
// serviceName: 'serverlessAirline'
// });
25 changes: 25 additions & 0 deletions docs/snippets/logger/unitTesting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const dummyContext = {
callbackWaitsForEmptyEventLoop: true,
functionVersion: '$LATEST',
functionName: 'foo-bar-function',
memoryLimitInMB: '128',
logGroupName: '/aws/lambda/foo-bar-function',
logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456',
invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function',
awsRequestId: 'c6af9ac6-7b61-11e6-9a41-93e812345678',
getRemainingTimeInMillis: () => 1234,
done: () => console.log('Done!'),
fail: () => console.log('Failed!'),
succeed: () => console.log('Succeeded!'),
};

describe('MyUnitTest', () => {

test('Lambda invoked successfully', async () => {

const testEvent = { test: 'test' };
await handler(testEvent, dummyContext);

});

});

0 comments on commit b4929e0

Please sign in to comment.