This repository has been archived by the owner on Jun 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 1b65b06
Showing
7 changed files
with
255 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# package directories | ||
node_modules | ||
yarn.lock | ||
|
||
# Serverless directories | ||
.serverless | ||
.webpack | ||
.env | ||
.docker |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.travis.yml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
language: node_js | ||
node_js: | ||
- 4.3.2 | ||
deploy: | ||
provider: npm | ||
email: [email protected] | ||
api_key: | ||
secure: "Tydq86AobfioyAkHMKBJ0XL8UgSXVPZXAdcD63O7tfdkeSMIOrhOWyi2w9/HAw3d4xQTz7x684OYolu3lc1DA6YAYMDYkeecTzzeOHm6mga3nDHrcMwdO0JkyIBCsjdSRo16o71Dxp6+/4t0nbzVCeo25bXrh2YV0Gc7/YstDL7LZ2s8/98mJCle7IixKq5wMdrwDnxr4g7D7WcwN9n7wUJUF7TvrKZv5MqdPKxqgZr6Nt99WsrLWfSaNW+lv6m1DPauX2xWyOqhQz6CeJrgnyg5aRi7HMOoGRGSMwPCosfEcYBq61Pn3ZXc4sD7gfeUzDcSJCFSiT31GSiMF7EsSPc8ZFp4WhlV0G11OfinnyQ947GIKRKORpEjg/SL8Qbep2Ax79j/6XX6eODqE0Q7Qgmc8ICWjv56B/JQpjekqPrU9wXxwxkkrHBMGNdouqthisbRMTQlAvNSg02c8xtNl0GuQKCqSXzVzgokATU14EYepcw0ESyDu0rraa5o5PqUUWF+5TffvuVf6UVZbWvaX8oqAlZlyXKdAARFx0n9bapi/JXhs4uTzlK8+ELGyLblEhWk7T2Ee0hJITtuyZ/m5K/O8h6jTKgcW3NCvvrW/dkPhMdhEgwfA/5XY1HDSwZoVPFJV/gza3gsoxpWuTm3OXo151/syO/7h7cVeTVb5GQ=" | ||
on: | ||
tags: true | ||
repo: keboola/serverless-papertrail-logging | ||
branch: master |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
The MIT License (MIT) | ||
Copyright (c) 2017 Keboola | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"name": "serverless-papertrail-logging", | ||
"version": "1.0.0", | ||
"description": "Serverless Plugin for log delivery from CloudWatch Logs to Papertrail using a lambda function with log groups subscription", | ||
"main": "src/index.js", | ||
"repository": "https://github.com/keboola/serverless-papertrail-logging", | ||
"author": "Jakub Matejka <[email protected]>", | ||
"license": "MIT", | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"dependencies": { | ||
"lodash": "^4.17.4", | ||
"winston": "^2.4.0", | ||
"winston-papertrail": "^1.0.5", | ||
"zlib": "^1.0.5" | ||
}, | ||
"peerDependencies": { | ||
"serverless": "^1.24.1" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
'use strict'; | ||
|
||
const _ = require('lodash'); | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
|
||
class PapertrailLogging { | ||
constructor(serverless) { | ||
this.serverless = serverless; | ||
this.service = serverless.service; | ||
|
||
this.provider = this.serverless.getProvider('aws'); | ||
|
||
this.hooks = { | ||
'before:deploy:createDeploymentArtifacts': this.beforeDeployCreateDeploymentArtifacts.bind(this), | ||
'deploy:compileEvents': this.deployCompileEvents.bind(this), | ||
'after:deploy:deploy': this.afterDeployDeploy.bind(this), | ||
}; | ||
} | ||
|
||
static getFunctionName() { | ||
return 'papertrailLogger'; | ||
} | ||
|
||
static getFunctionFilename() { | ||
return 'papertrail-logger-function'; | ||
} | ||
|
||
getEnvFilePath() { | ||
return path.join(this.serverless.config.servicePath, LogSubscription.getFunctionFilename()); | ||
} | ||
|
||
beforeDeployCreateDeploymentArtifacts() { | ||
this.serverless.cli.log('Creating temporary logger function...'); | ||
let functionPath = this.getEnvFilePath(); | ||
|
||
if (!fs.existsSync(functionPath)) { | ||
fs.mkdirSync(functionPath); | ||
} | ||
|
||
_.merge( | ||
this.service.provider.compiledCloudFormationTemplate.Resources, | ||
{ | ||
PapertrailLoggerLogGroup: { | ||
Type: "AWS::Logs::LogGroup", | ||
Properties: { | ||
LogGroupName: `/aws/lambda/${this.service.service}-${this.service.provider.stage}-${LogSubscription.getFunctionName()}` | ||
} | ||
} | ||
} | ||
); | ||
|
||
let templatePath = path.resolve(__dirname, './logger.handler.js'); | ||
let templateFile = fs.readFileSync(templatePath, 'utf-8'); | ||
|
||
let handlerFunction = templateFile | ||
.replace('%papertrailPort%', this.service.custom.papertrail.port) | ||
.replace('%papertrailHostname%', this.service.service) | ||
.replace('%papertrailProgram%', this.service.provider.stage); | ||
fs.writeFileSync(path.join(functionPath, 'handler.js'), handlerFunction); | ||
this.service.functions[LogSubscription.getFunctionName()] = { | ||
handler: `${LogSubscription.getFunctionFilename()}/handler.handler`, | ||
name: `${this.service.service}-${this.service.provider.stage}-${LogSubscription.getFunctionName()}`, | ||
tags: _.has(this.service.provider, 'stackTags') ? this.service.provider.stackTags : {}, | ||
events: [] | ||
}; | ||
} | ||
|
||
deployCompileEvents() { | ||
this.serverless.cli.log('Creating log subscriptions...'); | ||
|
||
const loggerLogicalId = this.provider.naming.getLambdaLogicalId(LogSubscription.getFunctionName()); | ||
|
||
_.each(this.service.provider.compiledCloudFormationTemplate.Resources, (item, key) => { | ||
if (_.has(item, 'Type') && item.Type === 'AWS::Logs::LogGroup') { | ||
this.service.provider.compiledCloudFormationTemplate.Resources[key].Properties.RetentionInDays = 30; | ||
} | ||
}); | ||
|
||
_.merge( | ||
this.service.provider.compiledCloudFormationTemplate.Resources, | ||
{ | ||
LambdaPermissionForSubscription: { | ||
Type: 'AWS::Lambda::Permission', | ||
Properties: { | ||
FunctionName: { 'Fn::GetAtt': [loggerLogicalId, 'Arn'] }, | ||
Action: 'lambda:InvokeFunction', | ||
Principal: { 'Fn::Sub': 'logs.${AWS::Region}.amazonaws.com' }, | ||
SourceArn: { 'Fn::Sub': 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*' }, | ||
}, | ||
DependsOn: [loggerLogicalId] | ||
} | ||
} | ||
); | ||
|
||
const functions = this.service.getAllFunctions(); | ||
functions.forEach((functionName) => { | ||
if (functionName !== LogSubscription.getFunctionName()) { | ||
const functionData = this.service.getFunction(functionName); | ||
const normalizedFunctionName = this.provider.naming.getNormalizedFunctionName(functionName); | ||
_.merge( | ||
this.service.provider.compiledCloudFormationTemplate.Resources, | ||
{ | ||
[`${normalizedFunctionName}SubscriptionFilter`]: { | ||
Type: 'AWS::Logs::SubscriptionFilter', | ||
Properties: { | ||
DestinationArn: { 'Fn::GetAtt': [loggerLogicalId, "Arn"] }, | ||
FilterPattern: '', | ||
LogGroupName: `/aws/lambda/${functionData.name}`, | ||
}, | ||
DependsOn: ['LambdaPermissionForSubscription'] | ||
} | ||
} | ||
); | ||
} | ||
}); | ||
} | ||
|
||
afterDeployDeploy() { | ||
this.serverless.cli.log('Removing temporary logger function'); | ||
let functionPath = this.getEnvFilePath(); | ||
|
||
try { | ||
if (fs.existsSync(functionPath)) { | ||
if (fs.existsSync(path.join(functionPath, 'handler.js'))) { | ||
fs.unlinkSync(path.join(functionPath, 'handler.js')); | ||
} | ||
fs.rmdirSync(functionPath); | ||
} | ||
} catch (err) { | ||
throw new Error(err); | ||
} | ||
} | ||
} | ||
|
||
module.exports = PapertrailLogging; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
'use strict'; | ||
|
||
const _ = require('lodash'); | ||
const papertrail = require('winston-papertrail').Papertrail; | ||
const winston = require('winston'); | ||
const zlib = require('zlib'); | ||
|
||
exports.handler = function (event, context, callback) { | ||
const logger = new (winston.Logger)({ | ||
transports: [], | ||
}); | ||
logger.add(papertrail, { | ||
host: 'logs.papertrailapp.com', | ||
port: '%papertrailPort%', | ||
hostname: '%papertrailHostname%', | ||
program: '%papertrailProgram%', | ||
flushOnClose: true, | ||
includeMetaInMessage: false, | ||
handleExceptions: true, | ||
humanReadableUnhandledException: false, | ||
logFormat: (level, message) => { | ||
const consoleLog = message.split('\t'); | ||
if (consoleLog.length === 3) { | ||
try { | ||
const logData = JSON.parse(consoleLog[2]); | ||
if (_.has(logData.event, 'body') && _.isString(logData.event.body)) { | ||
logData.event.body = JSON.parse(logData.event.body); | ||
} | ||
return JSON.stringify(logData); | ||
} catch (e) { | ||
return JSON.stringify({ requestId: consoleLog[1], log: consoleLog[2] }); | ||
} | ||
} | ||
|
||
try { | ||
const logData = JSON.parse(message); | ||
if (!_.has(logData, 'statusCode')) { | ||
logData.statusCode = 500; | ||
} | ||
return JSON.stringify(logData); | ||
} catch (e) { | ||
return message; | ||
} | ||
}, | ||
}); | ||
|
||
const payload = new Buffer(event.awslogs.data, 'base64'); | ||
zlib.gunzip(payload, (err, result) => { | ||
if (err) { | ||
return callback(err); | ||
} | ||
|
||
const logData = JSON.parse(result.toString('utf8')); | ||
if (logData.messageType === 'CONTROL_MESSAGE') { | ||
return callback(); | ||
} | ||
|
||
logData.logEvents.forEach((line) => { | ||
if (line.message && !_.startsWith(line.message, 'START RequestId') && !_.startsWith(line.message, 'END RequestId') | ||
&& !_.startsWith(line.message, 'REPORT RequestId')) { | ||
logger.info(line.message); | ||
} | ||
}); | ||
|
||
logger.close(); | ||
return callback(); | ||
}); | ||
}; |