Name:
interface
Value:
Extend your Amplify Gen 2 app with AWS Blocks — self-contained backend capabilities you compose into your existing backend.

CloudWatch client

AmplifyCloudWatchClient is a standalone client for sending application logs to Amazon CloudWatch Logs. It provides:

  • Local persistence for offline support
  • Automatic batching and interval-based flushing (default: every 60 seconds)
  • Integration with Amplify logging as a log sink
  • Per-namespace and per-user log level constraints
  • Enable/disable toggle that silently drops new logs while preserving cached ones

This is an experimental API. These public APIs are subject to change and are not meant for production code.

You must opt in by annotating your usage with @OptIn(ExperimentalAmplifyApi::class).

This is a standalone client, separate from the Amplify Logging category plugin. It communicates directly with the CloudWatch Logs API.

Before using this client, ensure your backend is configured with the required log group and IAM permissions. See Set up CloudWatch Logs.

Getting started

Installation

Add the dependency to your module's build.gradle.kts:

dependencies {
implementation("com.amplifyframework:aws-cloudwatch:ANDROID_VERSION")
}

Initialize the client

The logGroupName is required. It must match a CloudWatch log group your app has permission to write to.

import com.amplifyframework.cloudwatch.AmplifyCloudWatchClient
import com.amplifyframework.cloudwatch.AmplifyCloudWatchClientOptions
val cloudWatch = AmplifyCloudWatchClient(
context = applicationContext,
region = "us-east-1",
credentialsProvider = credentialsProvider,
options = AmplifyCloudWatchClientOptions {
logGroupName = "/app/my-android-app"
}
)

Configuration options

You can customize the client behavior through the options object:

OptionDefaultDescription
logGroupName(required)The CloudWatch log group logs are sent to.
localStoreMaxSizeInMB5Maximum size of the local log cache in MB.
flushStrategyFlushStrategy.Interval() (60s)Automatic flush interval. Use FlushStrategy.None for manual-only flushing.
loggingConstraintsLoggingConstraints()Per-namespace and per-user log level rules.
configureClientnullEscape hatch to customize the underlying AWS SDK CloudWatchLogsClient.
import com.amplifyframework.cloudwatch.AmplifyCloudWatchClientOptions
import com.amplifyframework.cloudwatch.FlushStrategy
import com.amplifyframework.cloudwatch.LoggingConstraints
import com.amplifyframework.logging.LogLevel
import kotlin.time.Duration.Companion.seconds
val options = AmplifyCloudWatchClientOptions {
logGroupName = "/app/my-android-app"
localStoreMaxSizeInMB = 10
flushStrategy = FlushStrategy.Interval(30.seconds)
loggingConstraints = LoggingConstraints(defaultLogLevel = LogLevel.Verbose)
configureClient {
retryStrategy { maxAttempts = 10 }
}
}

To disable automatic flushing:

options = AmplifyCloudWatchClientOptions {
logGroupName = "/app/my-android-app"
flushStrategy = FlushStrategy.None
}

Usage

Register as a logging sink

The client implements AmplifyFoundation's LogSink interface. Register it once to capture every message logged through Amplify logging:

import com.amplifyframework.logging.AmplifyLogging
AmplifyLogging.addSink(cloudWatch)

Emit a message directly

You can also send a log message to the client without going through Amplify logging:

import com.amplifyframework.logging.LogLevel
import com.amplifyframework.logging.LogMessage
cloudWatch.emit(LogMessage(LogLevel.Error, "MyNamespace", "Something went wrong", null))

Messages emitted while the client is disabled are silently dropped.

Flush logs

The client automatically flushes cached logs at the configured interval (default: 60 seconds). You can also trigger a manual flush:

when (val result = cloudWatch.flushLogs()) {
is Result.Success -> println("Flushed: ${result.data.flushed}")
is Result.Failure -> println("Flush error: ${result.error}")
}

Manual flushes work even when the client is disabled, allowing you to drain cached logs without re-enabling collection.

Enable and disable

You can toggle log collection and automatic flushing at runtime. When disabled, new logs are silently dropped but already-cached logs remain in storage.

cloudWatch.disable()
// Logs are dropped, auto-flush paused
cloudWatch.enable()
// Collection and auto-flush resume

Set the user identifier

Associate cached and future logs with a user identifier, for example after sign-in.

Pass null to clear it on sign-out.

cloudWatch.setUserIdentifier("user-123")

Set logging constraints

Update the log level rules at runtime, for example after fetching remote configuration:

import com.amplifyframework.cloudwatch.LoggingConstraints
import com.amplifyframework.logging.LogLevel
cloudWatch.setLoggingConstraints(
LoggingConstraints(
defaultLogLevel = LogLevel.Warn,
namespaceLogLevel = mapOf("Storage" to LogLevel.Debug)
)
)

Observe events

The client surfaces write and flush failures through an events stream so you can react to persistent problems:

import com.amplifyframework.cloudwatch.LoggingEvent
import kotlinx.coroutines.flow.collect
cloudWatch.events.collect { event ->
when (event) {
is LoggingEvent.WriteLogFailure -> { /* handle write failure */ }
is LoggingEvent.FlushLogFailure -> { /* handle flush failure */ }
}
}

Advanced

Escape hatch

Access the underlying AWS SDK CloudWatchLogsClient for operations not covered by this client's API:

val sdkClient = cloudWatch.getCloudWatchLogsClient()
// Use sdkClient for direct CloudWatch Logs API calls

Error handling

Operations surface errors through a sealed error hierarchy:

Error typeDescription
AmplifyCloudWatchStorageExceptionLocal storage error (file I/O, log rotation).
AmplifyCloudWatchServiceExceptionA CloudWatch Logs API call failed.
AmplifyCloudWatchConfigurationExceptionThe client was misconfigured.
AmplifyCloudWatchUnknownExceptionUnexpected or uncategorized error.

flushLogs() returns Result<FlushData, AmplifyCloudWatchException>:

when (val result = cloudWatch.flushLogs()) {
is Result.Success -> { /* success */ }
is Result.Failure -> when (result.error) {
is AmplifyCloudWatchStorageException -> { /* storage error */ }
is AmplifyCloudWatchServiceException -> { /* service error */ }
is AmplifyCloudWatchConfigurationException -> { /* misconfiguration */ }
is AmplifyCloudWatchUnknownException -> { /* unexpected error */ }
}
}

CloudWatch Logs service limits

The client batches logs to stay within the CloudWatch Logs PutLogEvents limits:

LimitValue
Max batch size1 MB
Max events per batch10,000
Max single event size256 KB