npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cloudwatchlogger

v1.0.4

Published

Module to log directly to AWS CloudWatchLogs in NodeJS

Downloads

7

Readme

cloudwatchlogger

NPM Version Build Status Coverage Status Dependency Status devDependency Status bitHound Score nsp status

Module to log directly to AWS CloudWatchLogs in NodeJS

cloudwatchlogger is a module that allows your Node.js app to send logs directly to AWS CloudWatchLogs.

  • Creates LogGroups and LogStream if it doesnot exist
  • Configurable batch size and retry options
  • Provides a streaming interface
  • CLI interface

Getting Started

Install the module with: npm install cloudwatchlogger --save

Install the module as a CLI tool npm install cloudwatchlogger -g

Usage

API

You can use the module by requiring and creating an instance of the logger by providing the AWS credentials and other options.

const Logger = require('cloudwatchlogger');

new Logger(OPTS).setupLogger('myGroupNameTest', 'myStreamNameTest',
        function(err, logger) {
            // logger is your actual logger instance
        }

Once you have the logger, you can call .log() function


    logger.log('Some Text'); // string
    logger.log(42); // number
    logger.log(true); // boolean
    logger.log({test:true}); // JSON

Logger OPTS

Logger OPTS allows you to pass in AWS credentials and few more options to control cloudwatchlogger behaviour.

OPTS needs to be a JSON like this:

{
    "accessKeyId": "XXXXX", // required
    "secretAccessKey": "YYYYY", // required
    "region": "us-west-2", // required
    "logLevel": "trace", // [optional] Use `Trace` if you want to see library logs
    "batchSize": 1024, // [optional] Messages are sent in batches of this size
    "batchDelay": 3000, // [optional] Delay before it sends if no messages are logged
    "maxRetries": 2 // [optional] Num of retries if posting to AWS fails
}

Full Example with Restify Server



'use strict'

const restify = require('restify');
const Logger = require('cloudwatchlogger');
let logger = null;
const server = restify.createServer({name: 'app'});
const opts = {
    "accessKeyId": "XXXXX", // required
    "secretAccessKey": "YYYYY", // required
    "region": "us-west-2", // required
    "logLevel": "trace", // [optional] Use `Trace` if you want to see library logs
    "batchSize": 1024, // [optional] Messages are sent in batches of this size
    "batchDelay": 3000, // [optional] Delay before it sends if no messages are logged
    "maxRetries": 2 // [optional] Num of retries if posting to AWS fails
};

/*
or, ask logger to read the AWS config from file json file
const opts = {
    "file":"./aws.config.json",
    "logLevel": "trace",
    "batchSize": 1024,
    "batchDelay": 3000,
    "maxRetries": 2
}
 */


server.pre( (req, res, next) => {
    req.id = 'RandomId123';
    // Example: Req object is circular with lots of other info
    // you would want to serialize it to a format that suits you
    logger.log({ method: req.method,
        url: req.url,
        id: req.id, // Example - assign and log a req id
        // later you can query in CloudWatchLogger with
        headers: req.headers,
        remoteAddress: req.connection.remoteAddress,
        remotePort: req.connection.remotePort });
    next();
});


server.get('/',  (req, res) => {
    logger.log('Some Text'); // string
    logger.log(42); // number
    logger.log(true); // boolean
    logger.log({test:true}); // JSON
    logger.log({
        statusCode: res.statusCode,
        id: req.id,
        header: res._header
    });
    res.send('hello world');
    next();
});


server.listen(3003, () => {
    // get an instance of logger and pass in the AWS CloudWatchLogs Group Name
    // and Stream Name
    // If GroupName or StreamName does not exists, library will create one for
    // you
    new Logger(opts).setupLogger('myGroupNameTest', 'myStreamNameTest',
        function(err, loggerInstance) {
            // you get back a loggerInstance when it establishes that log group
            // and log streams are valid
            logger = loggerInstance;
            console.log('Server listening on 3003 with CloudWatchLogger');
        });
});

CLI


cloudwatchlogger -h

  Usage: cloudwatchlogger [options]

  Options:

    -h, --help                               output usage information
    -V, --version                            output the version number
    -a, --accessKeyId <accessKeyId>          AWS Access Key Id
    -s, --secretAccessKey <secretAccessKey>  AWS Secret Access Key
    -r, --region <region>                    AWS Region
    -l, --logStreamName <logStreamName>      CloudWatch Log Stream Name
    -g, --logGroupName <logGroupName>        Cloud Watch Log Group Name
    -f, --file <pathToFile>                  or, Config JSON file containing AWS Credentials
    -d, --debug                              [optional] Enables debug logs for this library
    -m, --maxRetry <value>                   [optional] Max retries per log batch
    -b, --batchSize <value>                  [optional] Batch size

You can use cloudwatchlogger to stream output from one source into AWS CloudWatchLogs.

Example: The following will stream all the output from node server.js directly to AWS.

node server.js | cloudwatchlogger -f aws.config.json -g loggingGroup -l loggingStream

Contributing

Ensure that all linting and codestyle tasks are passing. Add unit tests for any new or changed functionality.

To start contributing, install the git prepush hooks:

make githooks

Before committing, lint and test your code using the included Makefile:

make prepush

If you have style errors, you can auto fix whitespace issues by running:

make codestyle-fix

License

Copyright (c) 2017 Rajat Kumar

Licensed under the MIT license.