

# Enabling conversation logs for your Lex V2 bots
<a name="enabling-logs"></a>

Use conversation logs to store user conversations with your bot. Review these logs to identify issues with your bot's interactions with users and modify your bot's behavior with these insights. This section also describes how to obfuscate slot values to protect the privacy of users.

**Topics**
+ [Logging conversations with conversation logs in Lex V2](conversation-logs.md)
+ [Obscuring slot values in conversation logs from Lex V2](monitoring-obfuscate.md)
+ [Selective conversation log capture in Lex V2](monitoring-selective-logging.md)

# Logging conversations with conversation logs in Lex V2
<a name="conversation-logs"></a>

You enable *conversation logs* to store bot interactions. You can use these logs to review the performance of your bot and to troubleshoot issues with conversations. You can log text for the [RecognizeText](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeText.html) operation. You can log both text and audio for the [RecognizeUtterance](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeUtterance.html) operation. By enabling conversation logs, you get a detailed view of conversations that users have with your bot.

For example, a session with your bot has a session ID. You can use this ID to get the transcript of the conversation including user utterances and the corresponding bot responses. You also get metadata such as intent name and slot values for an utterance.

**Note**  
You can't use conversation logs with a bot subject to the Children's Online Privacy Protection Act (COPPA).

Conversation logs are configured for an alias. Each alias can have different settings for their text and audio logs. You can enable text logs, audio logs, or both for each alias. Text logs store text input, transcripts of audio input, and associated metadata in CloudWatch Logs. Audio logs store audio input in Amazon S3. You can enable encryption of text and audio logs using AWS KMS customer managed CMKs.

To configure logging, use the console or the [CreateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateBotAlias.html) or [UpdateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateBotAlias.html) operation. After enabling conversation logs for an alias, using the [RecognizeText](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeText.html) or [RecognizeUtterance](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeUtterance.html) operation for that alias logs the text or audio utterances in the configured CloudWatch Logs log group or S3 bucket.

**Topics**
+ [IAM Policies for Conversation Logs](conversation-logs-policies.md)
+ [Configuring conversation logs for your Lex V2 bot](conversation-logs-configure.md)
+ [Viewing text logs in Amazon CloudWatch Logs from Lex V2](conversation-logs-cw.md)
+ [Accessing audio logs in Amazon S3](conversation-logs-s3.md)
+ [Monitoring conversation log status with CloudWatch metrics](conversation-logs-monitoring.md)

# IAM Policies for Conversation Logs
<a name="conversation-logs-policies"></a>

Depending on the type of logging that you select, Amazon Lex V2 requires permission to use Amazon CloudWatch Logs and Amazon Simple Storage Service (S3) buckets to store your logs. You must create AWS Identity and Access Management roles and permissions to enable Amazon Lex V2 to access these resources. 

## Creating an IAM Role and Policies for Conversation Logs
<a name="conversation-logs-role-and-policy"></a>

To enable conversation logs, you must grant write permission for CloudWatch Logs and Amazon S3. If you enable object encryption for your S3 objects, you need to grant access permission to the AWS KMS keys used to encrypt the objects. 

You can use the IAM console, the IAM API, or the AWS Command Line Interface to create the role and policies. These instructions use the AWS CLI to create the role and policies.

**Note**  
The following code is formatted for Linux and MacOS. For Windows, replace the Linux line continuation character (\$1) with a caret (^).



**To create an IAM role for conversation logs**

1. Create a document in the current directory called **LexConversationLogsAssumeRolePolicyDocument.json**, add the following code to it, and save it. This policy document adds Amazon Lex V2 as a trusted entity to the role. This allows Amazon Lex V2 to assume the role to deliver logs to the resources configured for conversation logs.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lexv2.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

------

1. In the AWS CLI, run the following command to create the IAM role for conversation logs.

   ```
   aws iam create-role \
       --role-name role-name \
       --assume-role-policy-document file://LexConversationLogsAssumeRolePolicyDocument.json
   ```

Next, create and attach a policy to the role that enables Amazon Lex V2 to write to CloudWatch Logs. 

**To create an IAM policy for logging conversation text to CloudWatch Logs**

1. Create a document in the current directory called **LexConversationLogsCloudWatchLogsPolicy.json**, add the following IAM policy to it, and save it.

1. In the AWS CLI, create the IAM policy that grants write permission to the CloudWatch Logs log group.

   ```
   aws iam create-policy \
       --policy-name cloudwatch-policy-name \
       --policy-document file://LexConversationLogsCloudWatchLogsPolicy.json
   ```

1. Attach the policy to the IAM role that you created for conversation logs.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/cloudwatch-policy-name \
       --role-name role-name
   ```

If you are logging audio to an S3 bucket, create a policy that enables Amazon Lex V2 to write to the bucket.

**To create an IAM policy for audio logging to an S3 bucket**

1. Create a document in the current directory called **LexConversationLogsS3Policy.json**, add the following policy to it, and save it.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Effect": "Allow",
             "Action": [
                 "s3:PutObject"
             ],
             "Resource": "arn:aws:s3:::bucket-name/*"
         }
     ]
   }
   ```

------

1. In the AWS CLI, create the IAM policy that grants write permission to your S3 bucket.

   ```
   aws iam create-policy \
       --policy-name s3-policy-name \
       --policy-document file://LexConversationLogsS3Policy.json
   ```

1. Attach the policy to the role that you created for conversation logs.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/s3-policy-name \
       --role-name role-name
   ```

## Granting Permission to Pass an IAM Role
<a name="conversation-logs-pass-role"></a>

When you use the console, the AWS Command Line Interface, or an AWS SDK to specify an IAM role to use for conversation logs, the user specifying the conversation logs IAM role must have permission to pass the role to Amazon Lex V2. To allow the user to pass the role to Amazon Lex V2, you must grant `PassRole` permission to the user's IAM user, role, or group. 

The following policy defines the permission to grant to the user, role, or group. You can use the `iam:AssociatedResourceArn` and `iam:PassedToService` condition keys to limit the scope of the permission. For more information, see [ Granting a User Permissions to Pass a Role to an AWS Service ](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html) and [ IAM and AWS STS Condition Context Keys ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role-name",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "lexv2.amazonaws.com"
                },
                "StringLike": {
                    "iam:AssociatedResourceARN": "arn:aws:lex:region:123456789012:bot:bot-name:bot-alias"
                }
            }
        }
    ]
}
```

------

# Configuring conversation logs for your Lex V2 bot
<a name="conversation-logs-configure"></a>

You enable and disable conversation logs using the console or the `conversationLogSettings` field of the `CreateBotAlias` or `UpdateBotAlias` operation. You can turn on or turn off audio logs, text logs, or both. Logging starts on new bot sessions. Changes to log settings aren't reflected for active sessions.

To store text logs, use an Amazon CloudWatch Logs log group in your AWS account. You can use any valid log group. The log group must be in the same region as the Amazon Lex V2 bot. For more information about creating a CloudWatch Logs log group, see [ Working with Log Groups and Log Streams ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html) in the *Amazon CloudWatch Logs User Guide*.

To store audio logs, use an Amazon S3 bucket in your AWS account. You can use any valid S3 bucket. The bucket must be in the same region as the Amazon Lex V2 bot. For more information about creating an S3 bucket, see [Creating a bucket](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html) in the *Amazon Simple Storage Service Getting Started Guide*.

When you manage conversation logs using the console, the console updates your service role so that it has access to the log group and S3 bucket.

If you are not using the console, you must provide an IAM role with policies that enable Amazon Lex V2 to write to the configured log group or bucket. If you create a service-linked role using the AWS Command Line Interface, you must add a custom suffix to the role using the `custom-suffix` option as in the following example. For more information, see [Creating an IAM Role and Policies for Conversation Logs](conversation-logs-policies.md#conversation-logs-role-and-policy).

```
aws iam create-service-linked-role \
    --aws-service-name lexv2.amazon.aws.com \
    --custom-suffix suffix
```

The IAM role that you use to enable conversation logs must have the `iam:PassRole` permission. The following policy should be attached to the role:

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role"
        }
    ]
}
```

------

## Enabling conversation logs
<a name="conversation-logs-enable"></a>

**To turn on logs using the console**

1. Open the Amazon Lex V2 console [https://console.aws.amazon.com/lexv2](https://console.aws.amazon.com/lexv2).

1. From the list, choose a bot.

1. From the left menu, choose **Aliases**.

1. In the list of aliases, choose the alias for which you want to configure conversation logs.

1. In the **Conversation logs** section, choose **Manage conversation logs**. 

1. For text logs, choose **Enable** then enter the Amazon CloudWatch Logs log group name.

1. For audio logs, choose **Enable** then enter the S3 bucket information.

1. Optional. To encrypt audio logs, choose the AWS KMS key to use for encryption.

1. Choose **Save** to start logging conversations. If necessary, Amazon Lex V2 will update your service role with permissions to access the CloudWatch Logs log group and selected S3 bucket.

## Disabling conversation logs in Lex V2
<a name="conversation-logs-disable"></a>

**To turn off logs using the console**

1. Open the Amazon Lex V2 console [https://console.aws.amazon.com/lexv2](https://console.aws.amazon.com/lexv2).

1. From the list, choose a bot.

1. From the left menu, choose **Aliases**.

1. In the list of aliases, choose the alias for which you want to configure conversation logs.

1. In the **Conversation logs** section, choose **Manage conversation logs**.

1. Disable text logging, audio logging, or both to turn off logging.

1. Choose **Save** to stop logging conversations.

# Viewing text logs in Amazon CloudWatch Logs from Lex V2
<a name="conversation-logs-cw"></a>

Amazon Lex V2 stores text logs for your conversations in Amazon CloudWatch Logs. To view the logs, use the CloudWatch Logs console or API. For more information, see [ Search Log Data Using Filter Patterns](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html) and [CloudWatch Logs Insights Query Syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html) in the *Amazon CloudWatch Logs User Guide*.

**To view logs using the Amazon Lex V2 console**

1. Open the Amazon Lex V2 console [https://console.aws.amazon.com/lexv2](https://console.aws.amazon.com/lexv2).

1. From the list, choose a bot.

1. From the left menu, choose **Analytics** and then choose **CloudWatch metrics**.

1. View metrics for your bot on the **CloudWatch metrics** page.

You can also use the CloudWatch console or API to view your log entries. To find the log entries, navigate to the log group that you configured for the alias. You can find the log stream prefix for your logs in the Amazon Lex V2 console or by using the [DescribeBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DescribeBotAlias.html) operation. 

Log entries for a user utterance are found in multiple log streams. An utterance in the conversation has an entry in one of the log streams with the specified prefix. An entry in the log stream contains the following information:

message-version  
The message schema version.

bot  
Details about the bot that the customer is interacting with.

messages  
The response that the bot sent back to the user.

utteranceContext  
Information about processing this utterance.  
+ `runtimeHints`—runtime context used to transcribe and interpret the user's input. For more information, see [Improving recognition of slot values with runtime hints in the conversation](using-hints.md).
+ `slotElicitationStyle`—Slot elicitation style used to interpret user input. For more information, see [Capturing slot values with spelling styles during the conversation](spelling-styles.md).

sessionState  
The current state of the conversation between the user and the bot. For more information, see [Understanding Amazon Lex V2 bot conversations](managing-conversations.md).

interpretations  
A list of intents that Amazon Lex V2 determined could satisfy the user's utterance. [Using confidence scores to improve conversation accuracy](confidence-scores.md).

interpretationSource  
Indicates whether a slot is resolved by Amazon Lex V2 or Amazon Bedrock. Values: Lex \$1 Bedrock

sessionId  
The identifier of the user session that is having the conversation.

inputTranscript  
A transcription of the input from the user.  
+ For text input, this is the text that the user typed. For DTMF input, this is the key that the user input.
+ For speech input, this is the text to which Amazon Lex V2 converts the user utterance in order to invoke an intent or fill a slot.

rawInputTranscript  
The raw transcript of the user input before any text processing is applied. Note: Text processing is only for en-US and en-GB locales.

transcriptions  
A list of potential transcriptions of the user's input. For more information, see [Using voice transcription confidence scores to improve conversations with your Lex V2 bot](using-transcript-confidence-scores.md). 

rawTranscription  
Using voice transcription confidence scores. For more information, see [Using voice transcription confidence scores to improve conversations with your Lex V2 bot](using-transcript-confidence-scores.md). 

missedUtterance  
Indicates whether Amazon Lex V2 was able to recognize the user's utterance.

requestId  
Amazon Lex V2 generated request ID for the user input.

timestamp  
The timestamp of the user's input.

developerOverride  
Indicates whether the conversation flow was updated using a dialog code hook. For more information on using a dialog code hook, see [Integrating an AWS Lambda function into your Amazon Lex V2 bot](lambda.md).

inputMode  
Indicates the type of input. Can be audio, DTMF, or text.

requestAttributes  
The request attributes used when processing the user's input.

audioProperties  
If audio conversation logs are enabled and the user input was in audio format, includes the total duration of the audio input, the duration of voice and the duration of silence in the audio. It also includes a link to the audio file.

bargeIn  
Indicates whether the user input interrupted the previous bot response.

responseReason  
The reason a response was generated. Can be one of:  
+ `UtteranceResponse` – response to user input
+ `StartTimeout` – server generated response when the user didn't provide input
+ `StillWaitingResponse` – server generated response when the user requests the bot wait
+ `FulfillmentInitiated` – server generated response that fulfillment is about to be initiated
+ `FulfillmentStartedResponse` – server generated response that fulfillment has begun
+ `FulfillmentUpdateResponse` – periodic server generated response while fulfillment is in progress
+ `FulfillmentCompletedResponse` – server generated response when fulfillment is complete.

operationName  
The API used to interact with the bot. Can be one of `PutSession`, `RecognizeText`, `RecognizeUtterance`, or `StartConversation`.

```
{
    "message-version": "2.0",
    "bot": {
        "id": "string",
        "name": "string",
        "aliasId": "string",
        "aliasName": "string",
        "localeId": "string",
        "version": "string"
    },
    "messages": [
        {
            "contentType": "PlainText | SSML | CustomPayload | ImageResponseCard",
            "content": "string",
            "imageResponseCard": {
                "title": "string",
                "subtitle": "string",
                "imageUrl": "string",
                "buttonsList": [
                    {
                        "text": "string",
                        "value": "string"
                    }
                ]
            }
        }
    ],
    "utteranceContext": {
        "activeRuntimeHints": {
            "slotHints": {
                "string": {
                    "string": {
                        "runtimeHintValues": [
                            {
                                "phrase": "string"
                            },
                            {
                                "phrase": "string"
                            }
                        ]
                    }
                }
            }
        },
        "slotElicitationStyle": "string"
    },
    "sessionState": {
        "dialogAction": {
            "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot",
            "slotToElicit": "string"
        },
        "intent": {
            "name": "string",
            "slots": {
                "string": { 
                    "value": { 
                       "interpretedValue": "string",
                       "originalValue": "string",
                       "resolvedValues": [ "string" ]
                    }
                 },  
                "string": {
                    "shape": "List",
                    "value": {
                        "originalValue": "string",
                        "interpretedValue": "string",
                        "resolvedValues": [ "string" ]
                    },
                    "values": [
                        {
                            "shape": "Scalar",
                            "value": {
                                "originalValue": "string",
                                "interpretedValue": "string",
                                "resolvedValues": [ "string" ]
                            }
                        },
                        {
                            "shape": "Scalar",
                            "value": {
                                "originalValue": "string",
                                "interpretedValue": "string",
                                "resolvedValues": [ "string" ]
                            }
                        }
                    ]
                }
            },
            "kendraResponse": {
                // Only present when intent is KendraSearchIntent. For details, see 
                // https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax
                },
            "state": "InProgress | ReadyForFulfillment | Fulfilled | Failed",
            "confirmationState": "Confirmed | Denied | None"
        },
        "originatingRequestId": "string",
        "sessionAttributes": {
            "string": "string"
        },
        "runtimeHints": {
            "slotHints": {
                "string": {
                    "string": {
                        "runtimeHintValues": [
                            {
                                "phrase": "string"
                            },
                            {
                                "phrase": "string"
                            }
                        ]
                    }
                }
            }
        }
    },
   "dialogEventLogs": [
        {
	  // only for conditional
     "conditionalEvaluationResult":[
      // all the branches until true

     {
     "conditionalBranchName": "string",
     "expressionString": "string",
     "evaluatedExpression": "string",
     "evaluationResult": "true | false"
     }
    ],
  "dialogCodeHookInvocationLabel": "string",
  "response": "string",
  "nextStep": {
        "dialogAction": {
            "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot",
            "slotToElicit": "string"
        },
	      "intent": {
                          "name": "string",
           "slots": {
               }
        }
       }
    ]
    "interpretations": [
        {
            "interpretationSource": "Bedrock | Lex",
            "nluConfidence": "string",
            "intent": {
                "name": "string",
                "slots": {
                    "string": {
                        "value": {
                            "originalValue": "string",
                            "interpretedValue": "string",
                            "resolvedValues": [ "string" ]
                        }
                    },
                    "string": {
                        "shape": "List",
                        "value": {
                            "interpretedValue": "string",
                            "originalValue": "string",
                            "resolvedValues": [ "string" ]
                        },
                        "values": [
                            {
                                "shape": "Scalar",
                                "value": {
                                    "interpretedValue": "string",
                                    "originalValue": "string",
                                    "resolvedValues": [ "string" ]
                                }
                            },
                            {
                                "shape": "Scalar",
                                "value": {
                                    "interpretedValue": "string",
                                    "originalValue": "string",
                                    "resolvedValues": [ "string" ]
                                }

                            }
                        ]
                    }
                },
                "kendraResponse": {
                    // Only present when intent is KendraSearchIntent. For details, see 
                    // https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax
                    },
                "state": "InProgress | ReadyForFulfillment | Fulfilled | Failed",
                "confirmationState": "Confirmed | Denied | None"
                },
            "sentimentResponse": {
                "sentiment": "string",
                "sentimentScore": {
                    "positive": "string",
                    "negative": "string",
                    "neutral": "string",
                    "mixed": "string"
                }
            }
        }
    ],
    "sessionId": "string",
    "inputTranscript": "string",
    "rawInputTranscript": "string",
    "transcriptions": [
        {
            "transcription": "string",
            "rawTranscription": "string",
            "transcriptionConfidence": "number",
            },
            "resolvedContext": {
                "intent": "string"
            },
            "resolvedSlots": {
                "string": {
                    "name": "slotName",
                    "shape": "List",
                    "value": { 
                        "originalValue": "string",
                        "resolvedValues": [
                            "string"
                        ]
                    }
                }
            }
        }
    ],
    "missedUtterance": "bool",
    "requestId": "string",
    "timestamp": "string",
    "developerOverride": "bool",
    "inputMode": "DTMF | Speech | Text",
    "requestAttributes": {
        "string": "string"
    },
    "audioProperties": {
        "contentType": "string",
        "s3Path": "string",
        "duration": {
            "total": "integer",
            "voice": "integer",
            "silence": "integer"
        }
    },
    "bargeIn": "string",
    "responseReason": "string",
    "operationName": "string"
}
```

The contents of the log entry depend on the result of a transaction and the configuration of the bot and request.
+ The `intent`, `slots`, and `slotToElicit` fields don't appear in an entry if the `missedUtterance` field is `true`.
+ The `s3PathForAudio` field doesn't appear if audio logs are disabled or if the `inputDialogMode`field is `Text`.
+ The `responseCard` field only appears when you have defined a response card for the bot.
+ The `requestAttributes` map only appears if you have specified request attributes in the request.
+ The `kendraResponse` field is only present when the `AMAZON.KendraSearchIntent` makes a request to search an Amazon Kendra index.
+ The `developerOverride` field is true when an alternative intent was specified in the bot's Lambda function.
+ The `sessionAttributes` map only appears if you have specified session attributes in the request.
+ The `sentimentResponse` map only appears if you configure the bot to return sentiment values.

**Note**  
The input format may change without a corresponding change in the `messageVersion`. Your code should not throw an error if new fields are present.

# Accessing audio logs in Amazon S3
<a name="conversation-logs-s3"></a>

Amazon Lex V2 stores audio logs for your conversations in an S3 bucket. 

You can use the Amazon S3 console or API to access audio logs. You can see the S3 object key prefix of the audio files in the Amazon Lex V2 console, or in the `conversationLogSettings` field in the `DescribeBotAlias` operation response.

# Monitoring conversation log status with CloudWatch metrics
<a name="conversation-logs-monitoring"></a>

Use Amazon CloudWatch to monitor delivery metrics of your conversation logs. You can set alarms on metrics so that you are aware of issues with logging if they should occur.

Amazon Lex V2 provides four metrics in the `AWS/Lex` namespace for conversation logs:
+ `ConversationLogsAudioDeliverySuccess`
+ `ConversationLogsAudioDeliveryFailure`
+ `ConversationLogsTextDeliverySuccess`
+ `ConversationLogsTextDeliveryFailure`

The success metrics show that Amazon Lex V2 has successfully written your audio or text logs to their destinations. 

The failure metrics show that Amazon Lex V2 couldn't deliver audio or text logs to the specified destination. Typically, this is a configuration error. When your failure metrics are above zero, check the following:
+ Make sure that Amazon Lex V2 is a trusted entity for the IAM role.
+ For text logging, make sure that the CloudWatch Logs log group exists. For audio logging, make sure that the S3 bucket exists.
+ Make sure that the IAM role that Amazon Lex V2 uses to access the CloudWatch Logs log group or S3 bucket has write permission for the log group or bucket.
+ Make sure that the S3 bucket exists in the same region as the Amazon Lex V2 bot and belongs to your account.

# Obscuring slot values in conversation logs from Lex V2
<a name="monitoring-obfuscate"></a>

Amazon Lex V2 enables you to obfuscate, or hide, the contents of slots so that the content is not visible. To protect sensitive data captured as slot values, you can enable slot obfuscation to mask those values for logging.

When you choose to obfuscate slot values, Amazon Lex V2 replaces the value of the slot with the name of the slot in conversation logs. For a slot called `full_name`, the value of the slot would be obfuscated as follows:

```
Before:
    My name is John Stiles
After:
    My name is {full_name}
```

If an utterance contains bracket characters (\$1\$1) Amazon Lex V2 escapes the bracket characters with two back slashes (\$1\$1). For example, the text `{John Stiles}` is obfuscated as follows:

```
Before:
    My name is {John Stiles}
After:
    My name is \\{{full_name}\\}
```

Slot values are obfuscated in conversation logs. The slot values are still available in the response from the `RecognizeText` and `RecognizeUtterance` operations, and the slot values are available to your validation and fulfillment Lambda functions. If you are using slot values in your prompts or responses, those slot values are not obfuscated in conversation logs.

In the first turn of a conversation, Amazon Lex V2 obfuscates slot values if it recognizes a slot and slot value in the utterance. If no slot value is recognized, Amazon Lex V2 does not obfuscate the utterance.

On the second and later turns, Amazon Lex V2 knows the slot to elicit and if the slot value should be obfuscated. If Amazon Lex V2 recognizes the slot value, the value is obfuscated. If Amazon Lex V2 does not recognize a value, the entire utterance is obfuscated. Any slot values in missed utterances won't be obfuscated.

Amazon Lex V2 also doesn't obfuscate slot values that you store in request or session attributes. If you are storing slot values that should be obfuscated as an attribute, you must encrypt or otherwise obfuscate the value.

Amazon Lex V2 doesn't obfuscate the slot value in audio. It does obfuscate the slot value in the audio transcription.

You can choose which slots to obfuscate by using the console or by using the Amazon Lex V2 API. In the console, choose **Slot obfuscation** in the settings for a slot. If you are using the API, set the `obfuscationSetting` field of the slot to `DEFAULT_OBFUSCATION` when you call the [CreateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateSlot.html) or [UpdateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateSlot.html) operation.

# Selective conversation log capture in Lex V2
<a name="monitoring-selective-logging"></a>

The selective conversation log capture allows the user to select how conversation logs are captured with text and audio data from the live conversations.

To enable and capture the output of the selective conversation log capture feature, you must activate the feature in the Amazon Lex V2 console, and enable the required session attributes in the API settings to capture the selected output from the logs.

You can select the following options for the selective conversation log capture:
+ text only
+ audio only
+ text and audio

You can capture specific parts of the conversation, and choose if audio, text, or both are captured for the conversation log. 

**Note**  
Selective conversation log capture works for Amazon Lex V2 only.

**Topics**
+ [Manage selective conversation log capture](manage-selective-logging.md)
+ [Example of selective conversation log capture](example-selective-logging.md)

# Manage selective conversation log capture
<a name="manage-selective-logging"></a>

Using the Lex console, you can enable the selective conversation log capture settings and choose which slots you want to enable selective conversation log capture capture for.

**Activate selective conversation log capture in the Amazon Lex V2 console:**

1. Sign in to the AWS Management Console and open the Amazon Lex V2 console at [https://console.aws.amazon.com/lexv2/home](https://console.aws.amazon.com/lexv2/home).

1. Select **Bots** from the left side panels and choose the bot you want to enable the selective conversation log capture. Use an existing bot or create a new one.

1. Choose **Aliases** for your selected bot under the **Deployment** section on the left side panel.

1. Choose your bot’s Alias, then select **Manage conversation logs**.

1. In the **Manage conversation logs** panel, for **Text logs**, choose whether text logs are enabled or disable by selecting the radio button. If you choose **Enabled** for text logs, then you will need to enter a **Log group name** or choose an existing log group name from the drop down menu. Select the check box for **Selectively log utterances** if you are selectively logging text files.
**Note**  
Enable text and/or audio logs by selecting the **Selectively log utterances** check box in the **conversation logs settings** (text and/or audio) in build time **BotAlias** settings. You must configure the CloudWatch log group and Amazon S3 bucket to select this option.

1. In the **Audio logs** section, choose whether audio logs are enabled or disable by selecting the radio button. If you choose **Enabled** for audio logs, you need to specify the Amazon S3 bucket location and (optional) the KMS key for encrypting your audio data. Select the check box for **Selectively log utterances** if you are selectively logging audio files.  
![\[The panels for managing conversation logs.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/logging/selective-manage-logs.png)

1. Select **Save** in the bottom right corner of the panel to save your selective conversation log capture settings.

**Activate selective conversation log capture in the Amazon Lex V2 console:**

1. Go to **Intents** and select the **Intent name**, **Initial Response**, **Advanced Settings**, **Set Values**, **Session Attributes**.

1. Set the following attributes to based on the intents and slots for which you want to enable selective conversation log capture: 
   + `x-amz-lex:enable-audio-logging:intent:slot = "true"`
   + `x-amz-lex:enable-text-logging:intent:slot = "true"`  
![\[The panels for adding selective session attributes.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/logging/selective-session-attributes.png)
**Note**  
Set `x-amz-lex:enable-audio-logging:intent:slot = "true"` to capture utterances that contain only a specific slot in the conversation. The action to log an utterance depends on the assessment of *intent *:*slot* within the utterance, in comparison to the session attribute expressions, and the corresponding flag value. To log an utterance, at least one expression in the session attribute must allow it, with the enable logging flag set to `true`. The value of *intent* and *slot* can be `"*"` as well. If the slot and/or intent value is `"*"`, it means that any slot and/or intent value of `"*"` will match with it. Similar to `x-amz-lex:enable-audio-logging`, a new session attribute called `x-amz-lex:enable-text-logging` will be used to control text logs.

1. Select **Update options** and build the bot to include the updated settings.

**Note**  
Your IAM role must have access permission to allow you to write data to the Amazon S3 bucket and to use a KMS key to encrypt the data. Lex will update your IAM role with Lex permissions to access CloudWatch Logs log group and the selected Amazon S3 bucket.

**Guidelines for using selective conversation log capture:**

You can only enable selective conversation log capture for text and/or audio logs, when you have enabled text and/or audio logs in the **Conversation log settings**. By enabling selective conversation log capture for text and/or audio logs, you disable logging for all intents and slots in the conversation. To generate text and/or audio logs for particular intents and slots, you must set text or/and audio selective conversation log capture session attributes for those intents and slots to "true". 
+ If selective conversation log capture is enabled, and no session attributes with the prefix x-amz-lex:enable-audio-logging are present, logging will be disabled by default for all the utterances. This scenario is also true regarding x-amz-lex:enable-text-logging.
+ Utterance logs will be stored exclusively for the segments of text and/or audio conversation if at least one expression in the session attribute allows it.
+ The configurations for selective conversation log capture of text and/or audio, as defined in session attributes, will be effective only when selective conversation log capture for text and/or audio is enabled in Conversation Log Settings within bot alias; otherwise, session attributes will be disregarded.
+ When selective conversation log capture is enabled, any slot values in SessionState, Interpretations, and Transcriptions for which logging is not enabled using session attributes will be obfuscated in the generated text log.
+ The decision to produce audio and/or text logs is evaluated by matching the slot elicited by the bot with the selective conversation log capture session attributes, except for the intent elicitation turn where user can provide slot values along with intent elicitation. In an intent elicitation turn, the slots filled in current turn are matched against the selective conversation log capture session attributes. 
+ The slots that are considered filled are derived from the session state at the end of the turn. Therefore, any alterations made by the Dialog Codehook Lambda to the slots in session state will influence the behavior of selective conversation log capture. 
+ In an intent elicitation turn, if multiple slot values are given by the user, the text and/or audio log will only get generated if the text/audio session attributes allow logging for all the slots filled in this turn. 
+ The recommended operational approach is to set the selective conversation log capture session attribute at the beginning of the session and to refrain from modifying it during the session.
+ If any slots contain sensitive data, you should always enable slot obfuscation.

# Example of selective conversation log capture
<a name="example-selective-logging"></a>

Here is an example of a business use case for selective conversation log capture.

**Use case:**

A fintech company utilizes an Amazon Lex V2 bot to support their IVR system, which allows users to make bill payments. In order to meet compliance and auditing requirements, they must retain audio recordings of user-provided authorization consent. However, enabling general audio logs is not feasible as it would make them non-compliant, because it is not possible to obfuscate sensitive slots like CardNumber, CVV, and other information in the audio logs. Instead, they can enable selective conversation log capture for audio logs and set session attribute to only produce audio logs for utterance that has authorization consent.

**BotAlias Settings:**
+ Text Logs Enabled : true 
+ Text Logs Selective Logging Enabled : false
+ Audio Logs Enabled : true 
+ Audio Logs Selective Logging Enabled : true 

**Session Attributes:**

`x-amz-lex:enable-audio-logging:PayBill:AuthorizationConsent = "true"`

**Sample Conversation:**
+ User (Audio Input): "I want to pay my bill with bill number 35XU68."
+ Bot: "What is the due amount in dollars?"
+ User (Audio Input): "235."
+ Bot: "What is your credit card number?"
+ User (Audio Input): "9239829722200348."
+ Bot: "You're paying 235 dollars using your credit card number ending with 0348. Please say 'I authorize to pay 235 dollars.'"
+ User (Audio Input): "I authorize to pay 235 dollars."
+ Bot: "Your bill has been paid."

**Conversation Logs output: **

In this situation, text logs will be produced for all turns. However, audio logs will only be recorded for the particular turn when the **AuthorizationConsent** slot within the **PayBill** intent was elicited, and no audio logs will be produced for any other turn.