-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
log-group.ts
643 lines (559 loc) · 16.8 KB
/
log-group.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import { Construct } from 'constructs';
import { DataProtectionPolicy } from './data-protection-policy';
import { LogStream } from './log-stream';
import { CfnLogGroup } from './logs.generated';
import { MetricFilter } from './metric-filter';
import { FilterPattern, IFilterPattern } from './pattern';
import { ResourcePolicy } from './policy';
import { ILogSubscriptionDestination, SubscriptionFilter } from './subscription-filter';
import * as cloudwatch from '../../aws-cloudwatch';
import * as iam from '../../aws-iam';
import * as kms from '../../aws-kms';
import { Annotations, Arn, ArnFormat, RemovalPolicy, Resource, Stack, Token } from '../../core';
export interface ILogGroup extends iam.IResourceWithPolicy {
/**
* The ARN of this log group, with ':*' appended
*
* @attribute
*/
readonly logGroupArn: string;
/**
* The name of this log group
* @attribute
*/
readonly logGroupName: string;
/**
* Create a new Log Stream for this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the LogStream
*/
addStream(id: string, props?: StreamOptions): LogStream;
/**
* Create a new Subscription Filter on this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the SubscriptionFilter
*/
addSubscriptionFilter(id: string, props: SubscriptionFilterOptions): SubscriptionFilter;
/**
* Create a new Metric Filter on this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the MetricFilter
*/
addMetricFilter(id: string, props: MetricFilterOptions): MetricFilter;
/**
* 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.
*
* @param jsonField JSON field to extract (example: '$.myfield')
* @param metricNamespace Namespace to emit the metric under
* @param metricName Name to emit the metric under
* @returns A Metric object representing the extracted metric
*/
extractMetric(jsonField: string, metricNamespace: string, metricName: string): cloudwatch.Metric;
/**
* Give permissions to write to create and write to streams in this log group
*/
grantWrite(grantee: iam.IGrantable): iam.Grant;
/**
* Give permissions to read from this log group and streams
*/
grantRead(grantee: iam.IGrantable): iam.Grant;
/**
* Give the indicated permissions on this log group and all streams
*/
grant(grantee: iam.IGrantable, ...actions: string[]): iam.Grant;
/**
* Public method to get the physical name of this log group
*/
logGroupPhysicalName(): string;
}
/**
* An CloudWatch Log Group
*/
abstract class LogGroupBase extends Resource implements ILogGroup {
/**
* The ARN of this log group, with ':*' appended
*/
public abstract readonly logGroupArn: string;
/**
* The name of this log group
*/
public abstract readonly logGroupName: string;
private policy?: ResourcePolicy;
/**
* Create a new Log Stream for this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the LogStream
*/
public addStream(id: string, props: StreamOptions = {}): LogStream {
return new LogStream(this, id, {
logGroup: this,
...props,
});
}
/**
* Create a new Subscription Filter on this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the SubscriptionFilter
*/
public addSubscriptionFilter(id: string, props: SubscriptionFilterOptions): SubscriptionFilter {
return new SubscriptionFilter(this, id, {
logGroup: this,
...props,
});
}
/**
* Create a new Metric Filter on this Log Group
*
* @param id Unique identifier for the construct in its parent
* @param props Properties for creating the MetricFilter
*/
public addMetricFilter(id: string, props: MetricFilterOptions): MetricFilter {
return new MetricFilter(this, id, {
logGroup: this,
...props,
});
}
/**
* 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.
*
* @param jsonField JSON field to extract (example: '$.myfield')
* @param metricNamespace Namespace to emit the metric under
* @param metricName Name to emit the metric under
* @returns A Metric object representing the extracted metric
*/
public extractMetric(jsonField: string, metricNamespace: string, metricName: string) {
new MetricFilter(this, `${metricNamespace}_${metricName}`, {
logGroup: this,
metricNamespace,
metricName,
filterPattern: FilterPattern.exists(jsonField),
metricValue: jsonField,
});
return new cloudwatch.Metric({ metricName, namespace: metricNamespace }).attachTo(this);
}
/**
* Give permissions to create and write to streams in this log group
*/
public grantWrite(grantee: iam.IGrantable) {
return this.grant(grantee, 'logs:CreateLogStream', 'logs:PutLogEvents');
}
/**
* Give permissions to read and filter events from this log group
*/
public grantRead(grantee: iam.IGrantable) {
return this.grant(grantee,
'logs:FilterLogEvents',
'logs:GetLogEvents',
'logs:GetLogGroupFields',
'logs:DescribeLogGroups',
'logs:DescribeLogStreams',
);
}
/**
* Give the indicated permissions on this log group and all streams
*/
public grant(grantee: iam.IGrantable, ...actions: string[]) {
return iam.Grant.addToPrincipalOrResource({
grantee,
actions,
// A LogGroup ARN out of CloudFormation already includes a ':*' at the end to include the log streams under the group.
// See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html#w2ab1c21c10c63c43c11
resourceArns: [this.logGroupArn],
resource: this,
});
}
/**
* Public method to get the physical name of this log group
* @returns Physical name of log group
*/
public logGroupPhysicalName(): string {
return this.physicalName;
}
/**
* 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.
*
* @param statement The policy statement to add
*/
public addToResourcePolicy(statement: iam.PolicyStatement): iam.AddToResourcePolicyResult {
if (!this.policy) {
this.policy = new ResourcePolicy(this, 'Policy');
}
this.policy.document.addStatements(statement.copy({
principals: statement.principals.map(p => this.convertArnPrincipalToAccountId(p)),
}));
return { statementAdded: true, policyDependable: this.policy };
}
private convertArnPrincipalToAccountId(principal: iam.IPrincipal) {
if (principal.principalAccount) {
// we use ArnPrincipal here because the constructor inserts the argument
// into the template without mutating it, which means that there is no
// ARN created by this call.
return new iam.ArnPrincipal(principal.principalAccount);
}
if (principal instanceof iam.ArnPrincipal && principal.arn !== '*') {
const parsedArn = Arn.split(principal.arn, ArnFormat.SLASH_RESOURCE_NAME);
if (parsedArn.account) {
return new iam.ArnPrincipal(parsedArn.account);
}
}
return principal;
}
}
/**
* How long, in days, the log contents will be retained.
*/
export enum RetentionDays {
/**
* 1 day
*/
ONE_DAY = 1,
/**
* 3 days
*/
THREE_DAYS = 3,
/**
* 5 days
*/
FIVE_DAYS = 5,
/**
* 1 week
*/
ONE_WEEK = 7,
/**
* 2 weeks
*/
TWO_WEEKS = 14,
/**
* 1 month
*/
ONE_MONTH = 30,
/**
* 2 months
*/
TWO_MONTHS = 60,
/**
* 3 months
*/
THREE_MONTHS = 90,
/**
* 4 months
*/
FOUR_MONTHS = 120,
/**
* 5 months
*/
FIVE_MONTHS = 150,
/**
* 6 months
*/
SIX_MONTHS = 180,
/**
* 1 year
*/
ONE_YEAR = 365,
/**
* 13 months
*/
THIRTEEN_MONTHS = 400,
/**
* 18 months
*/
EIGHTEEN_MONTHS = 545,
/**
* 2 years
*/
TWO_YEARS = 731,
/**
* 3 years
*/
THREE_YEARS = 1096,
/**
* 5 years
*/
FIVE_YEARS = 1827,
/**
* 6 years
*/
SIX_YEARS = 2192,
/**
* 7 years
*/
SEVEN_YEARS = 2557,
/**
* 8 years
*/
EIGHT_YEARS = 2922,
/**
* 9 years
*/
NINE_YEARS = 3288,
/**
* 10 years
*/
TEN_YEARS = 3653,
/**
* Retain logs forever
*/
INFINITE = 9999,
}
/**
* Class of Log Group.
*/
export enum LogGroupClass {
/**
* Default class of logs services
*/
STANDARD = 'STANDARD',
/**
* Class for reduced logs services
*/
INFREQUENT_ACCESS = 'INFREQUENT_ACCESS',
}
/**
* Properties for a LogGroup
*/
export interface LogGroupProps {
/**
* The KMS customer managed key to encrypt the log group with.
*
* @default Server-side encrpytion managed by the CloudWatch Logs service
*/
readonly encryptionKey?: kms.IKey;
/**
* Name of the log group.
*
* @default Automatically generated
*/
readonly logGroupName?: string;
/**
* Data Protection Policy for this log group.
*
* @default - no data protection policy
*/
readonly dataProtectionPolicy?: DataProtectionPolicy;
/**
* How long, in days, the log contents will be retained.
*
* To retain all logs, set this value to RetentionDays.INFINITE.
*
* @default RetentionDays.TWO_YEARS
*/
readonly retention?: RetentionDays;
/**
* 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
*/
readonly logGroupClass?: LogGroupClass;
/**
* 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
*/
readonly removalPolicy?: RemovalPolicy;
}
/**
* Define a CloudWatch Log Group
*/
export class LogGroup extends LogGroupBase {
/**
* Import an existing LogGroup given its ARN
*/
public static fromLogGroupArn(scope: Construct, id: string, logGroupArn: string): ILogGroup {
const baseLogGroupArn = logGroupArn.replace(/:\*$/, '');
class Import extends LogGroupBase {
public readonly logGroupArn = `${baseLogGroupArn}:*`;
public readonly logGroupName = Stack.of(scope).splitArn(baseLogGroupArn, ArnFormat.COLON_RESOURCE_NAME).resourceName!;
}
return new Import(scope, id, {
environmentFromArn: baseLogGroupArn,
});
}
/**
* Import an existing LogGroup given its name
*/
public static fromLogGroupName(scope: Construct, id: string, logGroupName: string): ILogGroup {
const baseLogGroupName = logGroupName.replace(/:\*$/, '');
class Import extends LogGroupBase {
public readonly logGroupName = baseLogGroupName;
public readonly logGroupArn = Stack.of(scope).formatArn({
service: 'logs',
resource: 'log-group',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: baseLogGroupName + ':*',
});
}
return new Import(scope, id);
}
/**
* The ARN of this log group
*/
public readonly logGroupArn: string;
/**
* The name of this log group
*/
public readonly logGroupName: string;
constructor(scope: Construct, id: string, props: LogGroupProps = {}) {
super(scope, id, {
physicalName: props.logGroupName,
});
let retentionInDays = props.retention;
if (retentionInDays === undefined) { retentionInDays = RetentionDays.TWO_YEARS; }
if (retentionInDays === Infinity || retentionInDays === RetentionDays.INFINITE) { retentionInDays = undefined; }
if (retentionInDays !== undefined && !Token.isUnresolved(retentionInDays) && retentionInDays <= 0) {
throw new Error(`retentionInDays must be positive, got ${retentionInDays}`);
}
let logGroupClass = props.logGroupClass;
const stack = Stack.of(scope);
const logGroupClassUnsupportedRegions = [
'cn-north-1', // BJS
'cn-northwest-1', // ZHY
'us-iso-west-1', // APA
'us-iso-east-1', // DCA
'us-isob-east-1', // LCK
'us-gov-west-1', // PDT
'us-gov-east-1', // OSU
];
if (logGroupClass !== undefined && !Token.isUnresolved(stack.region) && logGroupClassUnsupportedRegions.includes(stack.region)) {
Annotations.of(this).addWarningV2('@aws-cdk/aws-logs:propertyNotSupported', `The LogGroupClass property is not supported in the following regions: ${logGroupClassUnsupportedRegions}`);
}
const resource = new CfnLogGroup(this, 'Resource', {
kmsKeyId: props.encryptionKey?.keyArn,
logGroupClass,
logGroupName: this.physicalName,
retentionInDays,
dataProtectionPolicy: props.dataProtectionPolicy?._bind(this),
});
resource.applyRemovalPolicy(props.removalPolicy);
this.logGroupArn = this.getResourceArnAttribute(resource.attrArn, {
service: 'logs',
resource: 'log-group',
resourceName: this.physicalName,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
});
this.logGroupName = this.getResourceNameAttribute(resource.ref);
}
}
/**
* Properties for a new LogStream created from a LogGroup
*/
export interface StreamOptions {
/**
* The name of the log stream to create.
*
* The name must be unique within the log group.
*
* @default Automatically generated
*/
readonly logStreamName?: string;
}
/**
* Properties for a new SubscriptionFilter created from a LogGroup
*/
export interface SubscriptionFilterOptions {
/**
* The destination to send the filtered events to.
*
* For example, a Kinesis stream or a Lambda function.
*/
readonly destination: ILogSubscriptionDestination;
/**
* Log events matching this pattern will be sent to the destination.
*/
readonly filterPattern: IFilterPattern;
/**
* The name of the subscription filter.
*
* @default Automatically generated
*/
readonly filterName?: string;
}
/**
* Properties for a MetricFilter created from a LogGroup
*/
export interface MetricFilterOptions {
/**
* Pattern to search for log events.
*/
readonly filterPattern: IFilterPattern;
/**
* The namespace of the metric to emit.
*/
readonly metricNamespace: string;
/**
* The name of the metric to emit.
*/
readonly metricName: string;
/**
* 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"
*/
readonly metricValue?: string;
/**
* The value to emit if the pattern does not match a particular event.
*
* @default No metric emitted.
*/
readonly defaultValue?: number;
/**
* The fields to use as dimensions for the metric. One metric filter can include as many as three dimensions.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html#cfn-logs-metricfilter-metrictransformation-dimensions
* @default - No dimensions attached to metrics.
*/
readonly dimensions?: Record<string, string>;
/**
* The unit to assign to the metric.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html#cfn-logs-metricfilter-metrictransformation-unit
* @default - No unit attached to metrics.
*/
readonly unit?: cloudwatch.Unit;
/**
* The name of the metric filter.
*
* @default - Cloudformation generated name.
*/
readonly filterName?: string;
}