# Set Up Logs | Sentry for SvelteKit

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/sveltekit/logs.md#requirements)

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

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

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

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

## [Usage](https://docs.sentry.io/platforms/javascript/guides/sveltekit/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
Sentry.logger.error(
  Sentry.logger.fmt`Uh on, something broke, here's the error: '${error}'`
);
Sentry.logger.info(
  Sentry.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
Sentry.logger.trace("Starting database connection", { database: "users" });
Sentry.logger.debug("Cache miss for user", { userId: 123 });
Sentry.logger.info("Updated profile", { profileId: 345 });
Sentry.logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
Sentry.logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
Sentry.logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```

Setting a log message is required for the Sentry SDK to send the log to Sentry.

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]
);
```

##### Runtime Support

Using `printf` log syntax only works server-side in the Node.js and Bun runtimes.

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

### [Console Logging Integration](https://docs.sentry.io/platforms/javascript/guides/sveltekit/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.warn, and console.error calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "warn", "error"] }),
  ],
});
```

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`.

If you provide multiple arguments to your `console` object calls the integration will parse them as different attributes, which can be searched and filtered for in the Sentry UI. This requires SDK version [`10.13.0`](https://github.com/getsentry/sentry-javascript/releases/tag/10.13.0) or higher.

```js
// This will be logged as:
// {
//   "message": "Executed Action for User: 123 true",
//   "attributes": {
//     "message.template": "Executed Action for User: {} {}",
//     "message.parameter.0": 123,
//     "message.parameter.1": true
//   }
// }
console.log("Executed Action for User:", 123, true);
```

### [Pino Integration](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#pino-integration)

In `10.18.0` and above of the JavaScript SDKs, we've added support to send logs via the pino logging library. To add the pino integration, you need to add the `pinoIntegration` to your Sentry initialization.

```js
Sentry.init({
  integrations: [Sentry.pinoIntegration()],
});
```

You can look at the [Pino integration documentation](https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/integrations/pino.md) for more information on the options you can pass to the `pinoIntegration`.

### [Consola Integration](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#consola-integration)

In `10.12.0` and above of the JavaScript SDKs, we've added support to send logs via the [consola](https://github.com/unjs/consola) logging library.

```js
import { consola } from "consola";

// Create a Sentry reporter for consola
const sentryReporter = Sentry.createConsolaReporter();

// Add the reporter to consola
consola.addReporter(sentryReporter);
```

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

```js
const sentryReporter = Sentry.createConsolaReporter({
  levels: ["error", "warn"],
});
```

### [Winston Integration](https://docs.sentry.io/platforms/javascript/guides/sveltekit/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/sveltekit/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.

* [Node Bunyan](https://github.com/getsentry/sentry-javascript/issues/16474)

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

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

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

```js
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  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.

## [Default Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#default-attributes)

The SvelteKit SDK automatically sets several default attributes on all log entries to provide context and improve debugging:

### [Core Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#core-attributes)

* `environment`: The environment set in the SDK if defined. This is sent from the SDK as `sentry.environment`.
* `release`: The release set in the SDK if defined. This is sent from the SDK as `sentry.release`.
* `sdk.name`: The name of the SDK that sent the log. This is sent from the SDK as `sentry.sdk.name`.
* `sdk.version`: The version of the SDK that sent the log. This is sent from the SDK as `sentry.sdk.version`.

### [Message Template Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#message-template-attributes)

If the log was parameterized, Sentry adds the message template and parameters as log attributes.

* `message.template`: The parameterized template string. This is sent from the SDK as `sentry.message.template`.
* `message.parameter.X`: The parameters to fill the template string. X can either be the number that represent the parameter's position in the template string (`sentry.message.parameter.0`, `sentry.message.parameter.1`, etc) or the parameter's name (`sentry.message.parameter.item_id`, `sentry.message.parameter.user_id`, etc). This is sent from the SDK as `sentry.message.parameter.X`.

For example, with the following log:

```javascript
const user = "John";
const product = "Product 1";
Sentry.logger.info(
  Sentry.logger.fmt`'${user}' added '${product}' to cart.`,
);
```

Sentry will add the following attributes:

* `message.template`: "%s added %s to cart."
* `message.parameter.0`: "John"
* `message.parameter.1`: "Product 1"

### [Browser Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#browser-attributes)

* `browser.name`: Display name of the browser application.
* `browser.version`: Version string of the browser.

### [Server Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#server-attributes)

* `server.address`: The address of the server that sent the log. Equivalent to `server_name` that gets attached to Sentry errors.

### [User Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#user-attributes)

If user information is available in the current scope, the following attributes are added to the log:

* `user.id`: The user ID.
* `user.name`: The username.
* `user.email`: The email address.

### [Integration Attributes](https://docs.sentry.io/platforms/javascript/guides/sveltekit/logs.md#integration-attributes)

If a log is generated by an SDK integration, the SDK will set additional attributes to help you identify the source of the log.

* `origin`: The origin of the log. This is sent from the SDK as `sentry.origin`.
