import { config, CloudWatchLogs } from 'aws-sdk' import { OnModuleInit, Injectable } from '@nestjs/common' import { format } from 'date-fns' @Injectable() export class CloudWatchService implements OnModuleInit { private _CloudWatchLogs: CloudWatchLogs onModuleInit(): void { config.update({ region: process.env.AWS_SNS_REGION, }) this._CloudWatchLogs = new CloudWatchLogs() } async putLog(message: string, logName: string): Promise { const logGroupName = '/aws/lambda/' + logName + '-' + process.env.STAGE const logStreamName = format(new Date(), 'yyyy/MM/dd-HH-mm') try { await this._CloudWatchLogs.createLogGroup({ logGroupName }).promise() } catch (e) {} try { await this._CloudWatchLogs.createLogStream({ logGroupName, logStreamName }).promise() } catch (e) {} const sequenceToken = await this.getNextSeqToken(logGroupName, logStreamName) const params = { logEvents: [ { message, timestamp: new Date().getTime(), }, ], logGroupName, logStreamName, sequenceToken, } try { await this._CloudWatchLogs.putLogEvents(params).promise() } catch (e) {} } async getNextSeqToken(logGroupName: string, logStreamName: string): Promise { const response = await this._CloudWatchLogs .describeLogStreams({ logGroupName, logStreamNamePrefix: logStreamName }) .promise() if (response?.logStreams && response?.logStreams?.[0]?.logStreamName == logStreamName) return response.logStreams[0].uploadSequenceToken return null } }