LogGroup

class aws_cdk.aws_logs.LogGroup(scope, id, *, data_protection_policy=None, encryption_key=None, log_group_class=None, log_group_name=None, removal_policy=None, retention=None)

Bases: Resource

Define a CloudWatch Log Group.

ExampleMetadata:

infused

Example:

import aws_cdk.aws_logs as logs


log_group = logs.LogGroup(self, "Log Group")
log_bucket = s3.Bucket(self, "S3 Bucket")

tasks.EmrContainersStartJobRun(self, "EMR Containers Start Job Run",
    virtual_cluster=tasks.VirtualClusterInput.from_virtual_cluster_id("de92jdei2910fwedz"),
    release_label=tasks.ReleaseLabel.EMR_6_2_0,
    job_driver=tasks.JobDriver(
        spark_submit_job_driver=tasks.SparkSubmitJobDriver(
            entry_point=sfn.TaskInput.from_text("local:///usr/lib/spark/examples/src/main/python/pi.py"),
            spark_submit_parameters="--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1"
        )
    ),
    monitoring=tasks.Monitoring(
        log_group=log_group,
        log_bucket=log_bucket
    )
)
Parameters:
  • scope (Construct) –

  • id (str) –

  • data_protection_policy (Optional[DataProtectionPolicy]) – Data Protection Policy for this log group. Default: - no data protection policy

  • encryption_key (Optional[IKey]) – The KMS customer managed key to encrypt the log group with. Default: Server-side encryption managed by the CloudWatch Logs service

  • log_group_class (Optional[LogGroupClass]) – The class of the log group. Possible values are: STANDARD and INFREQUENT_ACCESS. INFREQUENT_ACCESS class provides customers a cost-effective way to consolidate logs which supports querying using Logs Insights. The logGroupClass property cannot be changed once the log group is created. Default: LogGroupClass.STANDARD

  • log_group_name (Optional[str]) – Name of the log group. Default: Automatically generated

  • removal_policy (Optional[RemovalPolicy]) – Determine the removal policy of this log group. Normally you want to retain the log group so you can diagnose issues from logs even after a deployment that no longer includes the log group. In that case, use the normal date-based retention policy to age out your logs. Default: RemovalPolicy.Retain

  • retention (Optional[RetentionDays]) – How long, in days, the log contents will be retained. To retain all logs, set this value to RetentionDays.INFINITE. Default: RetentionDays.TWO_YEARS

Methods

add_metric_filter(id, *, filter_pattern, metric_name, metric_namespace, default_value=None, dimensions=None, filter_name=None, metric_value=None, unit=None)

Create a new Metric Filter on this Log Group.

Parameters:
  • id (str) – Unique identifier for the construct in its parent.

  • filter_pattern (IFilterPattern) – Pattern to search for log events.

  • metric_name (str) – The name of the metric to emit.

  • metric_namespace (str) – The namespace of the metric to emit.

  • default_value (Union[int, float, None]) – The value to emit if the pattern does not match a particular event. Default: No metric emitted.

  • dimensions (Optional[Mapping[str, str]]) – The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions. Default: - No dimensions attached to metrics.

  • filter_name (Optional[str]) – The name of the metric filter. Default: - Cloudformation generated name.

  • metric_value (Optional[str]) – The value to emit for the metric. Can either be a literal number (typically “1”), or the name of a field in the structure to take the value from the matched event. If you are using a field value, the field value must have been matched using the pattern. If you want to specify a field from a matched JSON structure, use ‘$.fieldName’, and make sure the field is in the pattern (if only as ‘$.fieldName = *’). If you want to specify a field from a matched space-delimited structure, use ‘$fieldName’. Default: “1”

  • unit (Optional[Unit]) – The unit to assign to the metric. Default: - No unit attached to metrics.

Return type:

MetricFilter

add_stream(id, *, log_stream_name=None)

Create a new Log Stream for this Log Group.

Parameters:
  • id (str) – Unique identifier for the construct in its parent.

  • log_stream_name (Optional[str]) – The name of the log stream to create. The name must be unique within the log group. Default: Automatically generated

Return type:

LogStream

add_subscription_filter(id, *, destination, filter_pattern, distribution=None, filter_name=None)

Create a new Subscription Filter on this Log Group.

Parameters:
  • id (str) – Unique identifier for the construct in its parent.

  • destination (ILogSubscriptionDestination) – The destination to send the filtered events to. For example, a Kinesis stream or a Lambda function.

  • filter_pattern (IFilterPattern) – Log events matching this pattern will be sent to the destination.

  • distribution (Optional[Distribution]) – The method used to distribute log data to the destination. This property can only be used with KinesisDestination. Default: Distribution.BY_LOG_STREAM

  • filter_name (Optional[str]) – The name of the subscription filter. Default: Automatically generated

Return type:

SubscriptionFilter

add_to_resource_policy(statement)

Adds a statement to the resource policy associated with this log group.

A resource policy will be automatically created upon the first call to addToResourcePolicy.

Any ARN Principals inside of the statement will be converted into AWS Account ID strings because CloudWatch Logs Resource Policies do not accept ARN principals.

Parameters:

statement (PolicyStatement) – The policy statement to add.

Return type:

AddToResourcePolicyResult

apply_removal_policy(policy)

Apply the given removal policy to this resource.

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you’ve removed it from the CDK application or because you’ve made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

Parameters:

policy (RemovalPolicy) –

Return type:

None

extract_metric(json_field, metric_namespace, metric_name)

Extract a metric from structured log events in the LogGroup.

Creates a MetricFilter on this LogGroup that will extract the value of the indicated JSON field in all records where it occurs.

The metric will be available in CloudWatch Metrics under the indicated namespace and name.

Parameters:
  • json_field (str) – JSON field to extract (example: ‘$.myfield’).

  • metric_namespace (str) – Namespace to emit the metric under.

  • metric_name (str) – Name to emit the metric under.

Return type:

Metric

Returns:

A Metric object representing the extracted metric

grant(grantee, *actions)

Give the indicated permissions on this log group and all streams.

Parameters:
Return type:

Grant

grant_read(grantee)

Give permissions to read and filter events from this log group.

Parameters:

grantee (IGrantable) –

Return type:

Grant

grant_write(grantee)

Give permissions to create and write to streams in this log group.

Parameters:

grantee (IGrantable) –

Return type:

Grant

log_group_physical_name()

Public method to get the physical name of this log group.

Return type:

str

Returns:

Physical name of log group

metric(metric_name, *, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

Creates a CloudWatch metric for this log group.

Parameters:
  • metric_name (str) –

    • The name of the metric to create.

  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) – Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Return type:

Metric

Returns:

A CloudWatch Metric object representing the specified metric for this log group.

This method creates a CloudWatch Metric object with predefined settings for the log group. It sets the namespace to ‘AWS/Logs’ and the statistic to ‘Sum’ by default.

The created metric is automatically associated with this log group using the attachTo method.

Common metric names for log groups include:

  • ‘IncomingBytes’: The volume of log data in bytes ingested into the log group.

  • ‘IncomingLogEvents’: The number of log events ingested into the log group.

Example:

metric_incoming_bytes(*, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

Creates a CloudWatch metric for the volume of incoming log data in bytes to this log group.

Parameters:
  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) –

    Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Return type:

Metric

Returns:

A CloudWatch Metric object representing the IncomingBytes metric.

This method allows you to monitor the volume of data being ingested into the log group. It’s useful for understanding the size of your logs, which can impact storage costs and help in identifying unexpectedly large log entries.

Example usage:

const logGroup = new logs.LogGroup(this, ‘MyLogGroup’); logGroup.metricIncomingBytes().createAlarm(stack, ‘IncomingBytesPerInstanceAlarm’, { threshold: 1, evaluationPeriods: 1, });

metric_incoming_log_events(*, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

Creates a CloudWatch metric for the number of incoming log events to this log group.

Parameters:
  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) –

    Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Return type:

Metric

Returns:

A CloudWatch Metric object representing the IncomingLogEvents metric.

This method allows you to monitor the rate at which log events are being ingested into the log group. It’s useful for understanding the volume of logging activity and can help in capacity planning or detecting unusual spikes in logging.

Example usage:

const logGroup = new logs.LogGroup(this, ‘MyLogGroup’); logGroup.metricIncomingLogEvents().createAlarm(stack, ‘IncomingEventsPerInstanceAlarm’, { threshold: 1, evaluationPeriods: 1, });

to_string()

Returns a string representation of this construct.

Return type:

str

Attributes

env

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.

log_group_arn

The ARN of this log group.

log_group_name

The name of this log group.

node

The tree node.

stack

The stack in which this resource is defined.

Static Methods

classmethod from_log_group_arn(scope, id, log_group_arn)

Import an existing LogGroup given its ARN.

Parameters:
  • scope (Construct) –

  • id (str) –

  • log_group_arn (str) –

Return type:

ILogGroup

classmethod from_log_group_name(scope, id, log_group_name)

Import an existing LogGroup given its name.

Parameters:
  • scope (Construct) –

  • id (str) –

  • log_group_name (str) –

Return type:

ILogGroup

classmethod is_construct(x)

Checks if x is a construct.

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters:

x (Any) – Any object.

Return type:

bool

Returns:

true if x is an object created from a class which extends Construct.

classmethod is_owned_resource(construct)

Returns true if the construct was created by CDK, and false otherwise.

Parameters:

construct (IConstruct) –

Return type:

bool

classmethod is_resource(construct)

Check whether the given construct is a Resource.

Parameters:

construct (IConstruct) –

Return type:

bool