Search code examples
amazon-ecsamazon-cloudwatchaws-cdk

Log retation setting for ECS


I want to set the ecs fargate services logretantion by CDK

This services have two containers and oneLogGroup.

var logRetention = logs.RetentionDays.ONE_DAY 

const logGroup = new logs.LogGroup(this, 'ServiceLogGroup', {
  logGroupName: ecsInfos['logGroup'],
  removalPolicy: RemovalPolicy.DESTROY,

});
const nginxContainer = taskDefinitionAdmin.addContainer("NginxContainer", {
  image: nginxImage,
  containerName:ecsInfos['containerNginx'],
  logging: ecs.LogDriver.awsLogs({
    streamPrefix: "log-nginx",
    logRetention:logRetention,
    logGroup,
  }),
});

const djangoContainer = taskDefinitionAdmin.addContainer("DjangoContainer", {
  image: djangoImage,
  containerName:ecsInfos['containerDjango'],
  logging: ecs.LogDriver.awsLogs({
    streamPrefix: "log-django",
    logRetention:logRetention,
    logGroup,
  }),
});

This code shows the error below.

Error: Cannot specify both `logGroup` and `logRetentionDays`.
    at new AwsLogDriver (/Users/whitebear/MyCode/httproot/proj_cdk/node_modules/aws-cdk-lib/aws-ecs/lib/log-drivers/aws-log-driver.js:1:1214)
    at Function.awsLogs (/Users/whitebear/MyCode/httproot/proj_cdk/node_modules/aws-cdk-lib/aws-ecs/lib/log-drivers/log-driver.js:1:624)
    at new CdkStFargateStack (/Users/whitebear/MyCode/httproot/proj_cdk/lib/cdk_st-fargate-stack.ts:81:30)
    at Object.<anonymous> (/Users/whitebear/MyCode/httproot/proj_cdk/bin/cdk_st.ts:45:17)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module.m._compile (/Users/whitebear/MyCode/httproot/proj_cdk/node_modules/ts-node/src/index.ts:1056:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/whitebear/MyCode/httproot/proj_cdk/node_modules/ts-node/src/index.ts:1059:12)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)

I guss I should set the logRetention in logs.LogGroup , however there is no logRetantion prop.

How can I solve this?


Solution

  • If you are creating the LogGroup then you need to set the retention on the log group itself:

    const logGroup = new logs.LogGroup(this, 'ServiceLogGroup', {
      logGroupName: ecsInfos['logGroup'],
      removalPolicy: RemovalPolicy.DESTROY,
      retention: logRetention 
    });
    

    When you are specifying log configuration in the task definition, you either specify an existing log group, or you specify all the other settings for a new log group that will be created for you.