All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.teambytes.cloudwatch.appenders.logback.CloudwatchAppender.scala Maven / Gradle / Ivy

The newest version!
package com.teambytes.cloudwatch.appenders.logback

import java.util.Date
import java.util.concurrent.atomic.AtomicReference

import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.{AppenderBase, Layout}
import com.amazonaws.services.logs.AWSLogsAsyncClient
import com.amazonaws.services.logs.model._

import scala.beans.BeanProperty
import scala.collection.JavaConverters._

trait CloudwatchAppender extends AppenderBase[ILoggingEvent] {

  protected val awsClient = new AWSLogsAsyncClient()
  @BeanProperty
  var layout: Layout[ILoggingEvent] = null
  @BeanProperty
  var logGroupName: String = null
  @BeanProperty
  var logStreamName: String = null
  private val lastSequenceToken = new AtomicReference[String](null)

  override def start(): Unit = {
    val createLogGroupRequest = new CreateLogGroupRequest(logGroupName)
    try {
      awsClient.createLogGroup(createLogGroupRequest)
    } catch {
      case e: ResourceAlreadyExistsException =>
        addInfo(s"Log group '$logGroupName' already exists")
    }

    val createLogStreamRequest = new CreateLogStreamRequest(logGroupName, logStreamName)
    try {
      awsClient.createLogStream(createLogStreamRequest)
    } catch {
      case e: ResourceAlreadyExistsException =>
        addInfo(s"Log stream '$logStreamName' in group '$logGroupName' already exists")
    }

    try {
      sendEvent("Getting the next expected sequenceToken for CloudwatchAppender")
    } catch {
      case e: InvalidSequenceTokenException =>
        lastSequenceToken.set(e.getExpectedSequenceToken)
    }

    super.start()
  }

  protected def sendEvent(message: String) = {
    val logEvents = Seq(new InputLogEvent().
      withTimestamp(new Date().getTime).
      withMessage(message))
    val putLogEventsRequest = new PutLogEventsRequest(logGroupName, logStreamName, logEvents.asJava)
    putLogEventsRequest.setSequenceToken(lastSequenceToken.get())
    val result = awsClient.putLogEvents(putLogEventsRequest)
    lastSequenceToken.set(result.getNextSequenceToken)
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy