Search code examples
node.jsexpressamazon-cloudwatchlogslocalstack

localstack Aws cloudwatch logs


How to send logs to localstack cloudwatch logs using node.

i am using npm

const winston = require('winston')
const CloudWatchTransport = require('winston-aws-cloudwatch')

Solution

  • You should probably be using winston-cloudwatch instead as winston-aws-cloudwatch because it is more in use and is maintained. But as the choice is yours and if you still want to use winston-aws-cloudwatch, you can add the endpoint in awsConfig to http://localhost:4586, because by default localstack uses 4586 as port for cloudwatch.

    Example for winston-cloudwatch is given below.

    const AWS = require('aws-sdk');
    const WinstonCloudWatch = require('winston-cloudwatch');
     
    winston.add(new WinstonCloudWatch({
      awsRegion: 'us-east-1',
      logGroupName: 'your-log-group-name',
      logStreamName: 'your-log-stream-name',
      jsonMessage: true,
    }));
    
    winston.info('I am done');
    

    or

    const AWS = require('aws-sdk');
    const WinstonCloudWatch = require('winston-cloudwatch');
    
    const logger = winston.createLogger({
      transports: [
        new WinstonCloudWatch({
          logGroupName: 'log-group-name',
          logStreamName: 'log-stream-name',
          awsRegion: 'us-east-1',
          jsonMessage: true
        })
      ]
    });
    
    logger.error('I am done');
    

    The snippet may end in Invalid token error. You can use awslocal iam to create an IAM user and create an access key with the same and use it.

    You may need to install awslocal if you wanna play with localstack

    To verify if the log group has been created or not, you can try with awslocal logs describe-log-groups

    For other CLI commands, you can refer AWS CLI documetation

    For local, you can replace aws to awslocal.