# Set Up Logs | Sentry for AWS Lambda

AI Rules for Logs in Code Editors

When created as a rules file this should be placed alongside other editor specific rule files. For example, if you are using Cursor, place this file in the `.cursorrules` directory.

`rules.md`

````markdown
# Logs

- Where logs are used, ensure Sentry is imported using `import * as Sentry from "@sentry/node"`
- Enable logging in Sentry using `Sentry.init({ _experiments: { enableLogs: true } })`
- Reference the logger using `const { logger } = Sentry`
- Sentry offers a `consoleLoggingIntegration` that can be used to log specific console error types automatically without instrumenting the individual logger calls

## Configuration

The Sentry initialization needs to be updated to enable the logs feature.

### Baseline

```javascript
import * as Sentry from "@sentry/node";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  _experiments: {
    enableLogs: true,
  },
});
```

### Logger Integration

```javascript
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // send console.log, console.error, and console.warn calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
  ],
});
```

## Logger Examples

`logger.fmt` is a template literal function that should be used to bring variables into the structured logs.

```javascript
import * as Sentry from "@sentry/node";

const { logger } = Sentry;

logger.trace("Starting database connection", { database: "users" });
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```
````

##### Now in Beta

Sentry Logs is currently in Beta. Features are still in-progress and may have bugs. We recognize the irony. For any questions or feedback, you can reach us on [Discord](https://discord.gg/sentry) or [GitHub](https://github.com/getsentry/sentry/discussions/86804).

With Sentry Structured Logs, you can send text based log information from your applications to Sentry. Once in Sentry, these logs can be viewed alongside relevant errors, searched by text-string, or searched using their individual attributes.

## [Requirements](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#requirements)

Logs for JavaScript are supported in Sentry JavaScript SDK version `9.17.0` and above.

## [Setup](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#setup)

To enable logging, you need to initialize the SDK with the `_experiments.enableLogs` option set to `true`.

```js
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  // Enable logs to be sent to Sentry
  _experiments: { enableLogs: true },
});
```

## [Usage](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#usage)

Once the feature is enabled on the SDK and the SDK is initialized, you can send logs using the `Sentry.logger` APIs.

The `Sentry.logger` namespace exposes six methods that you can use to log messages at different log levels: `trace`, `debug`, `info`, `warn`, `error`, and `fatal`.

Aside from the primary logging methods, we've provided a format text function, `Sentry.logger.fmt`, that you can use to insert properties into to your log entries.

These properties will be sent to Sentry, and can be searched from within the Logs UI, and even added to the Logs views as a dedicated column.

```js
const { logger } = Sentry;

logger.error(logger.fmt`Uh on, something broke, here's the error: '${error}'`);
logger.info(logger.fmt`'${user.username}' added '${product.name}' to cart.`);
```

You can also pass additional attributes directly to the logging functions, avoiding the need to use the `fmt` function.

```js
const { logger } = Sentry;

logger.trace("Starting database connection", { database: "users" });
logger.debug("Cache miss for user", { userId: 123 });
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```

You can also avoid using the `fmt` function by formatting the log message via a `printf`-like format string and arguments.

This follows the same structure as the [`util.format` Node.js standard library function](https://nodejs.org/api/util.html#utilformatformat-args).

```js
Sentry.logger.info("User %s logged in successfully", ["John Doe"]);
Sentry.logger.warn("Failed to load user %s data", ["John Doe"], {
  errorCode: 404,
});
Sentry.logger.error(
  "Failed to process payment. Order: %s. Amount: %d. Details: %o",
  ["order_123", 99.99, paymentDetailsObject]
);
```

## [Integrations](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#integrations)

### [Console Logging Integration](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#console-logging-integration)

You can also configure the SDK to send logs via the JavaScript console object, using the SDK's `consoleLoggingIntegration`.

```js
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // send console.log, console.error, and console.warn calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
  ],
});
```

The `consoleLoggingIntegration` accepts a `levels` option, which is an array of console method names to log. By default the integration will log calls from `console.debug`, `console.info`, `console.warn`, `console.error`, `console.log`, `console.assert`, and `console.trace`.

### [Winston Integration](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#winston-integration)

In `9.13.0` and above of the JavaScript SDKs, we've added support to send logs via the winston logging library.

```js
const winston = require("winston");
const Transport = require("winston-transport");

const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);

const logger = winston.createLogger({
  transports: [new SentryWinstonTransport()],
});
```

The `createSentryWinstonTransport` method accepts a `levels` option, which allows you to filter which levels are sent to Sentry. By default all levels are logged.

```js
const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {
  // Only capture error and warn logs
  levels: ["error", "warn"],
});
```

### [Upcoming Integrations](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#upcoming-integrations)

We're actively working on adding more integration support for Logs. You can follow progress on the following GitHub issues or open a [new one](https://github.com/getsentry/sentry-javascript/issues/new/choose) for any integration you would like to see.

* [Consola](https://github.com/getsentry/sentry-javascript/issues/16659)
* [Pino](https://github.com/getsentry/sentry-javascript/issues/15952)

## [Options](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#options)

#### [beforeSendLog](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/logs.md#beforesendlog)

To filter logs, or update them before they are sent to Sentry, you can use the `_experiments.beforeSendLog` option.

```js
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  _experiments: {
    enableLogs: true,
    beforeSendLog: (log) => {
      if (log.level === "info") {
        // Filter out all info logs
        return null;
      }

      return log;
    },
  },
});
```

The `beforeSendLog` function receives a log object, and should return the log object if you want it to be sent to Sentry, or `null` if you want to discard it.

The log object has the following properties:

* `level`: (string - one of `trace`, `debug`, `info`, `warn`, `error`, `fatal`) The log level.
* `message`: (string) The message to be logged.
* `timestamp`: (number) The timestamp of the log.
* `attributes`: (object) The attributes of the log.
