How Can I Write Logs Directly to AWS S3 in Nodejs?
Here is the code in which you can directly work with AWS S3 Logs.
// need to install "npm install aws-sdk" first if not exist
const AWS = require('aws-sdk')
const s3 = new AWS.S3({
// your S3 accessKeyId and your S3 secretAccessKey
accessKeyId: process.env.ACCESS_KEY_ID.trim(),
secretAccessKey: process.env.SECRET_ACCESS_KEY.trim()
})
// params for getting the log file from s3
var getParams = {
// your S3 bucket name and your S3 filename Key/path
Bucket: process.env.BUCKET.trim(),
Key: fileNameKey
};
// get file data from s3
await s3.getObject(getParams, function(err, data) {
// Handle any error and exit. if 404 then skip. it will create new below.
if (err && err.statusCode !== 404) {
return console.log(err);
}
// create content
let content = ''
// if file exist and no err then prepend the data in the new content
if (!err || (err && err.statusCode !== 404)) {
// Use the encoding necessary
let objectData = data.Body.toString('utf-8');
content += objectData
}
var date = new Date()
content += '['+ date +'] - your text for the logs';
content += "\n\n"; // will leave 2 line breaks at the last
// s3 upload file params
const params = {
Bucket: process.env.BUCKET.trim(), // your S3 bucket name
Key: fileNameKey, // your S3 filename Key/path
Body: content
}
s3.upload(params, (err2, data) => {
if (err2) {
return console.log(err2)
}
return console.log(err2);
})
return console.log(err);
});
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment