LogGroup L2 construct
Define a CloudWatch Log Group.
Example
import * as logs from 'aws-cdk-lib/aws-logs';
const logGroup = new logs.LogGroup(this, 'Log Group');
const logBucket = new s3.Bucket(this, 'S3 Bucket')
new tasks.EmrContainersStartJobRun(this, 'EMR Containers Start Job Run', {
virtualCluster: tasks.VirtualClusterInput.fromVirtualClusterId('de92jdei2910fwedz'),
releaseLabel: tasks.ReleaseLabel.EMR_6_2_0,
jobDriver: {
sparkSubmitJobDriver: {
entryPoint: sfn.TaskInput.fromText('local:///usr/lib/spark/examples/src/main/python/pi.py'),
sparkSubmitParameters: '--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1',
},
},
monitoring: {
logGroup: logGroup,
logBucket: logBucket,
},
});
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
)
)
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup = new LogGroup(this, "Log Group");
Bucket logBucket = new Bucket(this, "S3 Bucket");
EmrContainersStartJobRun.Builder.create(this, "EMR Containers Start Job Run")
.virtualCluster(VirtualClusterInput.fromVirtualClusterId("de92jdei2910fwedz"))
.releaseLabel(ReleaseLabel.EMR_6_2_0)
.jobDriver(JobDriver.builder()
.sparkSubmitJobDriver(SparkSubmitJobDriver.builder()
.entryPoint(TaskInput.fromText("local:///usr/lib/spark/examples/src/main/python/pi.py"))
.sparkSubmitParameters("--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1")
.build())
.build())
.monitoring(Monitoring.builder()
.logGroup(logGroup)
.logBucket(logBucket)
.build())
.build();
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.Logs;
var logGroup = new LogGroup(this, "Log Group");
var logBucket = new Bucket(this, "S3 Bucket");
new EmrContainersStartJobRun(this, "EMR Containers Start Job Run", new EmrContainersStartJobRunProps {
VirtualCluster = VirtualClusterInput.FromVirtualClusterId("de92jdei2910fwedz"),
ReleaseLabel = ReleaseLabel.EMR_6_2_0,
JobDriver = new JobDriver {
SparkSubmitJobDriver = new SparkSubmitJobDriver {
EntryPoint = TaskInput.FromText("local:///usr/lib/spark/examples/src/main/python/pi.py"),
SparkSubmitParameters = "--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1"
}
},
Monitoring = new Monitoring {
LogGroup = logGroup,
LogBucket = logBucket
}
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import logs "github.com/aws/aws-cdk-go/awscdk"
logGroup := logs.NewLogGroup(this, jsii.String("Log Group"))
logBucket := s3.NewBucket(this, jsii.String("S3 Bucket"))
tasks.NewEmrContainersStartJobRun(this, jsii.String("EMR Containers Start Job Run"), &EmrContainersStartJobRunProps{
VirtualCluster: tasks.VirtualClusterInput_FromVirtualClusterId(jsii.String("de92jdei2910fwedz")),
ReleaseLabel: tasks.ReleaseLabel_EMR_6_2_0(),
JobDriver: &JobDriver{
SparkSubmitJobDriver: &SparkSubmitJobDriver{
EntryPoint: sfn.TaskInput_FromText(jsii.String("local:///usr/lib/spark/examples/src/main/python/pi.py")),
SparkSubmitParameters: jsii.String("--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1"),
},
},
Monitoring: &Monitoring{
LogGroup: logGroup,
LogBucket: logBucket,
},
})
Initializer
new LogGroup(scope: Construct, id: string, props?: LogGroupProps)
LogGroup(scope: Construct, id: str, props: typing.Optional[LogGroupProps] = None)
new LogGroup(Construct scope, String id, LogGroupProps props)
new LogGroup(Construct scope, string id, LogGroupProps? props = null)
NewLogGroup(Scope Construct, Id *string, Props LogGroupProps)
Construct Props
dataProtectionPolicyDataProtectionPolicydata_protection_policyDataProtectionPolicydataProtectionPolicyDataProtectionPolicyDataProtectionPolicyDataProtectionPolicyDataProtectionPolicyDataProtectionPolicy= no data protection policy#deletionProtectionEnabledbooleandeletion_protection_enabledbooldeletionProtectionEnabledBooleanDeletionProtectionEnabledboolDeletionProtectionEnabled*bool= false#When enabled, deletion protection blocks all deletion operations until it is explicitly disabled.
encryptionKeyIKeyRefencryption_keyIKeyRefencryptionKeyIKeyRefEncryptionKeyIKeyRefEncryptionKeyIKeyRef= Server-side encryption managed b…#default
Default: Server-side encryption managed by the CloudWatch Logs service
fieldIndexPoliciesFieldIndexPolicy[]field_index_policiestyping.List[FieldIndexPolicy]fieldIndexPoliciesList<FieldIndexPolicy>FieldIndexPoliciesFieldIndexPolicy[]FieldIndexPolicies*[]FieldIndexPolicy= no field index policies for this…#default
Default: no field index policies for this log group.
logGroupClassLogGroupClasslog_group_classLogGroupClasslogGroupClassLogGroupClassLogGroupClassLogGroupClassLogGroupClassLogGroupClass= LogGroupClass.STANDARD#notes
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.
DELIVERY class is used to deliver logs to a destination such as Amazon S3 or Amazon Data Firehose (for example, Lambda vended logs). A Delivery log group forwards events to a destination instead of storing them, so it does not support retention, dataProtectionPolicy, or fieldIndexPolicies; setting any of these together with LogGroupClass.DELIVERY results in a synthesis-time error.
logGroupNamestringlog_group_namestrlogGroupNameStringLogGroupNamestringLogGroupName*string= Automatically generated#removalPolicyRemovalPolicyremoval_policyRemovalPolicyremovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicy= RemovalPolicy.Retain#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.
retentionRetentionDaysretentionRetentionDaysretentionRetentionDaysRetentionRetentionDaysRetentionRetentionDays= RetentionDays.TWO_YEARS#To retain all logs, set this value to RetentionDays.INFINITE.
Properties
envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
grantsLogGroupGrantsgrantsLogGroupGrantsgrantsLogGroupGrantsGrantsLogGroupGrantsGrantsLogGroupGrantsrequired#logGroupRefLogGroupReferencelog_group_refLogGroupReferencelogGroupRefLogGroupReferenceLogGroupRefLogGroupReferenceLogGroupRefLogGroupReferencerequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#Methods
addMetricFilter(id: string, props: MetricFilterOptions): MetricFilterdef add_metric_filter(self, id: str, props: MetricFilterOptions) -> MetricFilterpublic MetricFilter addMetricFilter(String id, MetricFilterOptions props)public MetricFilter AddMetricFilter(string id, MetricFilterOptions props)func AddMetricFilter(Id *string, Props MetricFilterOptions) MetricFilter#2 parameters
Parameters
ididididId— Unique identifier for the construct in its parent.propspropspropspropsProps— Properties for creating the MetricFilter.
addStream(id: string, props?: StreamOptions): LogStreamdef add_stream(self, id: str, props: typing.Optional[StreamOptions] = None) -> LogStreampublic LogStream addStream(String id, StreamOptions props)public LogStream AddStream(string id, StreamOptions? props = null)func AddStream(Id *string, Props StreamOptions) LogStream#2 parameters
Parameters
ididididId— Unique identifier for the construct in its parent.propspropspropspropsProps— Properties for creating the LogStream.
addSubscriptionFilter(id: string, props: SubscriptionFilterOptions): SubscriptionFilterdef add_subscription_filter(self, id: str, props: SubscriptionFilterOptions) -> SubscriptionFilterpublic SubscriptionFilter addSubscriptionFilter(String id, SubscriptionFilterOptions props)public SubscriptionFilter AddSubscriptionFilter(string id, SubscriptionFilterOptions props)func AddSubscriptionFilter(Id *string, Props SubscriptionFilterOptions) SubscriptionFilter#2 parameters
Parameters
ididididId— Unique identifier for the construct in its parent.propspropspropspropsProps— Properties for creating the SubscriptionFilter.
addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResultdef add_to_resource_policy(self, statement: PolicyStatement) -> AddToResourcePolicyResultpublic AddToResourcePolicyResult addToResourcePolicy(PolicyStatement statement)public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement)func AddToResourcePolicy(Statement PolicyStatement) AddToResourcePolicyResult#notes · 1 parameter
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
statementstatementstatementstatementStatement— The policy statement to add.
addTransformer(id: string, props: TransformerOptions): Transformerdef add_transformer(self, id: str, props: TransformerOptions) -> Transformerpublic Transformer addTransformer(String id, TransformerOptions props)public Transformer AddTransformer(string id, TransformerOptions props)func AddTransformer(Id *string, Props TransformerOptions) Transformer#2 parameters
Parameters
ididididId— Unique identifier for the construct in its parent.propspropspropspropsProps— Properties for creating the Transformer.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
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).
extractMetric(jsonField: string, metricNamespace: string, metricName: string): Metricdef extract_metric(self, json_field: str, metric_namespace: str, metric_name: str) -> Metricpublic Metric extractMetric(String jsonField, String metricNamespace, String metricName)public Metric ExtractMetric(string jsonField, string metricNamespace, string metricName)func ExtractMetric(JsonField *string, MetricNamespace *string, MetricName *string) Metric#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.
3 parameters · returns
Parameters
jsonFieldjson_fieldjsonFieldjsonFieldJsonField— JSON field to extract (example: '$.myfield').metricNamespacemetric_namespacemetricNamespacemetricNamespaceMetricNamespace— Namespace to emit the metric under.metricNamemetric_namemetricNamemetricNameMetricName— Name to emit the metric under.
Returns: A Metric object representing the extracted metric
fromLogGroupArn(scope: Construct, id: string, logGroupArn: string): ILogGroup@staticmethod def from_log_group_arn(scope: Construct, id: str, log_group_arn: str) -> ILogGrouppublic static ILogGroup fromLogGroupArn(Construct scope, String id, String logGroupArn)public static ILogGroup FromLogGroupArn(Construct scope, string id, string logGroupArn)func FromLogGroupArn(Scope Construct, Id *string, LogGroupArn *string) ILogGroupstatic#fromLogGroupName(scope: Construct, id: string, logGroupName: string): ILogGroup@staticmethod def from_log_group_name(scope: Construct, id: str, log_group_name: str) -> ILogGrouppublic static ILogGroup fromLogGroupName(Construct scope, String id, String logGroupName)public static ILogGroup FromLogGroupName(Construct scope, string id, string logGroupName)func FromLogGroupName(Scope Construct, Id *string, LogGroupName *string) ILogGroupstatic#grant(grantee: IGrantable, ...actions: string[]): Grantdef grant(self, grantee: IGrantable, actions: str) -> Grantpublic Grant grant(IGrantable grantee, String actions)public Grant Grant(IGrantable grantee, string actions)func Grant(Grantee IGrantable, Actions *string) Grant#[disable-awslint:no-grants]
grantRead(grantee: IGrantable): Grantdef grant_read(self, grantee: IGrantable) -> Grantpublic Grant grantRead(IGrantable grantee)public Grant GrantRead(IGrantable grantee)func GrantRead(Grantee IGrantable) Grant#The use of this method is discouraged. Please use grants.read() instead.
[disable-awslint:no-grants]
grantWrite(grantee: IGrantable): Grantdef grant_write(self, grantee: IGrantable) -> Grantpublic Grant grantWrite(IGrantable grantee)public Grant GrantWrite(IGrantable grantee)func GrantWrite(Grantee IGrantable) Grant#The use of this method is discouraged. Please use grants.write() instead.
[disable-awslint:no-grants]
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
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
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#logGroupPhysicalName(): stringdef log_group_physical_name(self, ) -> strpublic String logGroupPhysicalName()public string LogGroupPhysicalName()func LogGroupPhysicalName() *string#returns
Returns: Physical name of log group
metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#2 parameters · returns
Parameters
metricNamemetric_namemetricNamemetricNameMetricName— - The name of the metric to create.propspropspropspropsProps— - Optional.
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. ```
metricIncomingBytes(props?: MetricOptions): Metricdef metric_incoming_bytes(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricIncomingBytes(MetricOptions props)public Metric MetricIncomingBytes(MetricOptions? props = null)func MetricIncomingBytes(Props MetricOptions) Metric#1 parameter · returns
Parameters
propspropspropspropsProps— - Optional.
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, });
metricIncomingLogEvents(props?: MetricOptions): Metricdef metric_incoming_log_events(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricIncomingLogEvents(MetricOptions props)public Metric MetricIncomingLogEvents(MetricOptions? props = null)func MetricIncomingLogEvents(Props MetricOptions) Metric#1 parameter · returns
Parameters
propspropspropspropsProps— - Optional.
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, });
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.