amazon-web-servicesamazon-cloudwatchaws-sdk-js

How to set log level when using AWS JavaScript SDK v3 @aws-sdk/client-cloudwatch-logs?


This is how I log to AWS CloudWatch logs:

import {CloudWatchLogsClient, PutLogEventsCommand} from '@aws-sdk/client-cloudwatch-logs'

const cloudWatchLogsClient = new CloudWatchLogsClient({region: REGION})
const logToCloudWatch = async (message) => {
    await cloudWatchLogsClient.send(new PutLogEventsCommand({
        logEvents: [{
            timestamp: Date.now(),
            message: message
        }],
        logGroupName: 'my_group',
        logStreamName: 'my_stream'
    }))
}

await logToCloudWatch('INFO: App started with env: ' + JSON.stringify(process.env, null, 2))

try {
    dosomething()
} catch (err) {
    await logToCloudWatch('ERROR: ' + err))
}

As you can see, I'm just prefixing messages with log levels which is quite ugly. Does @aws-sdk/client-cloudwatch-logs support log levels? How do I use them?


Solution

  • if you look at a library such as winston-cloudwatch you can see that setting log level is not possible

    all they do in that library is combine a log level string with your message

    var messageFormatter = options.messageFormatter ? options.messageFormatter : function(log) {
        return [ log.level, log.message ].join(' - ')
      };