

# Working with logs in AWS SAM
<a name="serverless-sam-cli-logging"></a>

To simplify troubleshooting, the AWS SAM CLI has a command called `sam logs`. This command lets you fetch logs generated by your Lambda function from the command line.

**Note**  
The `sam logs` command works for all AWS Lambda functions, not just the ones you deploy using AWS SAM.

## Fetching logs by CloudFormation stack
<a name="serverless-logging-cfn"></a>

When your function is a part of an CloudFormation stack, you can fetch logs by using the function's logical ID:

```
sam logs -n HelloWorldFunction --stack-name mystack
```

## Fetching logs by Lambda function name
<a name="serverless-logging-function"></a>

Or, you can fetch logs by using the function's name:

```
sam logs -n mystack-HelloWorldFunction-1FJ8PD
```

## Tailing logs
<a name="serverless-logging-tail"></a>

Add the `--tail` option to wait for new logs and see them as they arrive. This is helpful during deployment or when you're troubleshooting a production issue.

```
sam logs -n HelloWorldFunction --stack-name mystack --tail
```

## Viewing logs for a specific time range
<a name="serverless-logging-time-range"></a>

You can view logs for a specific time range by using the `-s` and `-e` options:

```
sam logs -n HelloWorldFunction --stack-name mystack -s '10min ago' -e '2min ago'
```

## Filtering logs
<a name="serverless-logging-time-range"></a>

Use the `--filter` option to quickly find logs that match terms, phrases, or values in your log events:

```
sam logs -n HelloWorldFunction --stack-name mystack --filter "error"
```

In the output, the AWS SAM CLI underlines all occurrences of the word "error" so you can easily locate the filter keyword within the log output.

## Error highlighting
<a name="serverless-logging-error-highlight"></a>

When your Lambda function crashes or times out, the AWS SAM CLI highlights the timeout message in red. This helps you easily locate specific executions that are timing out within a giant stream of log output.

## JSON pretty printing
<a name="serverless-logging-error-highlight"></a>

If your log messages print JSON strings, the AWS SAM CLI automatically pretty prints the JSON to help you visually parse and understand the JSON.