diff --git a/astro.sidebar.ts b/astro.sidebar.ts index c808283eaf9f9..fc2f291134e0e 100644 --- a/astro.sidebar.ts +++ b/astro.sidebar.ts @@ -147,6 +147,7 @@ export const sidebar = [ 'reference/dev-toolbar-app-reference', 'reference/session-driver-reference', 'reference/font-provider-reference', + 'reference/logger-reference', 'reference/container-reference', 'reference/programmatic-reference', ], @@ -162,7 +163,6 @@ export const sidebar = [ 'reference/experimental-flags/queued-rendering', 'reference/experimental-flags/rust-compiler', 'reference/experimental-flags/advanced-routing', - 'reference/experimental-flags/logger', ], }), 'reference/legacy-flags', diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index df1dc39c77d6c..802175eacb9b7 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -1229,3 +1229,55 @@ content=" " > ``` +### `logger` + +

+ + **Type**: `object | undefined` + +

+ +An object that allows you to add additional logs during the rendering of a page. This is particularly useful with [on-demand routes](/en/guides/on-demand-rendering/) and when connecting log aggregation services (e.g. Kibana, Grafana, Loki). +#### `logger.error()` +

+ + **Type**: `(msg: string) => void` + +

+ +Emits a message with `error` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.error("Can't find the checkout ID."); +--- +``` + +#### `logger.warn()` +

+ + **Type**: `(msg: string) => void` + +

+Emits a message with `warn` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.warn("Can't find the checkout ID."); +--- +``` + +#### `logger.info()` +

+ + **Type**: `(msg: string) => void` + +

+ +Emits a message with `info` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.info("Can't find the checkout ID."); +--- +``` diff --git a/src/content/docs/en/reference/experimental-flags/logger.mdx b/src/content/docs/en/reference/logger-reference.mdx similarity index 74% rename from src/content/docs/en/reference/experimental-flags/logger.mdx rename to src/content/docs/en/reference/logger-reference.mdx index 8f1be3cba772c..4e37433b3a1ae 100644 --- a/src/content/docs/en/reference/experimental-flags/logger.mdx +++ b/src/content/docs/en/reference/logger-reference.mdx @@ -1,49 +1,110 @@ --- -title: Experimental logger +title: Astro Logger API sidebar: - label: Logger + label: Logger API i18nReady: true --- - import Since from '~/components/Since.astro';

- -**Type:** `object`
-**Default:** `undefined`
- +

-Enables an experimental, custom logger that can be controlled by the user. -When provided, the user has total control over the logs emitted by Astro. Additionally, the feature comes with some built-in loggers that can be used via the new `logHandlers`. +The Logger API provides greater control over Astro's logging infrastructure. This allows you to replace the default console output with custom logging implementations and connect to log aggregation services. -The following example enables the built-in JSON logger, with a pretty output: +This API includes three ready-to-use loggers and allows you to integrate your own loggers and compose them. -```js title="astro.config.mjs" {5} ins="logHandlers" -import { defineConfig, logHandlers } from 'astro/config'; +## Custom loggers + +You can create a custom logger by providing the correct configuration to the `logger` setting. It accepts an object with a mandatory `entrypoint`, the module where the logger is exported, and an optional configuration to pass to the logger. The configuration must be serializable. + +The logger function must be exported as `default`. + +When you define a custom logger, you are in charge of all logs, even the ones emitted by Astro. + +The following example defines a custom logger exported by the `@org/custom-logger` package and accepting only one parameter to configure the logging `level`: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; export default defineConfig({ experimental: { - logger: logHandlers.json({ pretty: true }) + logger: { + entrypoint: "@org/custom-logger", + config: { + level: "warn" + } + } } }); ``` -Alternatively, you can enable JSON logging for the `dev`, `build`, and `sync` commands using the `--experimentalJson` flag: +The following example implements a minimal logger returning an [`AstroLoggerDestination` object](#astrologgerdestination) with the required `write()` function: -```shell -astro dev --experimentalJson -astro sync --experimentalJson -astro build --experimentalJson +```ts title="@org/custom-logger/index.ts" +import type { + AstroLoggerLevel, + AstroLoggerDestination, + AstroLoggerMessage +} from "astro"; +import { matchesLevel } from "astro/logger"; + +type LoggerOptions = { + level: AstroLoggerLevel +} + +function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { + const { level = 'info' } = options; + return { + write(message: AstroLoggerMessage) { + // Use this utility to understand if the message should be printed + if (matchesLevel(message.level, level)) { + // log message somewhere and take the level into consideration + } + } + } +} + +export default orgLogger; +``` + +You can now add your own logs during the rendering of a page using [the runtime APIs](/en/reference/api-reference/#logger). + +## Log level + +A level is an internal, arbitrary score assigned to each message. When a logger is configured with a certain level, only the messages with a level equal to or higher are printed. + +There are three levels, from the highest to the lowest score: +1. `error` +2. `warn` +3. `info` + +The following example configures the JSON logger to print only messages that have the `warn` level or higher: + +```js title="astro.config.mjs" {5} ins='level: "warn"' +import { defineConfig, logHandlers } from 'astro/config'; + +export default defineConfig({ + experimental: { + logger: logHandlers.json({ level: "warn" }) + } +}); ``` +The `astro/logger` package exposes a [`matchesLevel()`](#matcheslevel) helper to check the log level. This can be useful when [building a custom logger](#custom-loggers). + +```js +import { matchesLevel } from "astro/logger"; + +matchesLevel("error", "info"); +``` ## Built-in loggers -The feature comes with three built-in loggers. +Astro offers built-in loggers that applications can use. -### `logHandlers.json` +### `logHandlers.json()` A logger that outputs messages in a JSON format. A log would look like this: ```json @@ -53,9 +114,9 @@ A logger that outputs messages in a JSON format. A log would look like this: #### JSON logger options

-**Type:** `{ pretty: boolean; level: AstroLoggerLevel; }`
-**Default:** `{ pretty: false, level: 'info' }` - + **Type:** `{ pretty: boolean; level: AstroLoggerLevel; }`
+ **Default:** `{ pretty: false, level: 'info' }` +

The `json` logger accepts the following options: @@ -73,7 +134,7 @@ export default defineConfig({ }); ``` -### `logHandlers.console` +### `logHandlers.console()` A logger that prints messages using the `console` as its destination. Based on the level of the message, it uses different channels: @@ -84,9 +145,9 @@ A logger that prints messages using the `console` as its destination. Based on t #### Console logger options

-**Type:** `{ level: AstroLoggerLevel }`
-**Default:** `{ level: 'info' }` - + **Type:** `{ level: AstroLoggerLevel }`
+ **Default:** `{ level: 'info' }` +

The `console` logger accepts the following options: @@ -103,7 +164,7 @@ export default defineConfig({ }); ``` -### `logHandlers.node` +### `logHandlers.node()` A logger that prints messages to [`process.stdout`](https://nodejs.org/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/api/process.html#processstderr). Level `error` messages are printed to `stderr`, while the others are printed to `stdout`. @@ -112,9 +173,9 @@ This is Astro's default logger. #### Node logger options

-**Type:** `{ level: AstroLoggerLevel }`
-**Default:** `{ level: 'info' }` - + **Type:** `{ level: AstroLoggerLevel }`
+ **Default:** `{ level: 'info' }` +

The `node` logger accepts the following options: @@ -150,104 +211,7 @@ export default defineConfig({ }); ``` -## Custom loggers - -You can create a custom logger by providing the correct configuration to the `logger` setting. It accepts an object with a mandatory `entrypoint`, the module where the logger is exported, and an optional configuration to pass to the logger. The configuration must be serializable. - -The logger function must be exported as `default`. -When you define a custom logger, you are in charge of all logs, even the ones emitted by Astro. - -The following example defines a custom logger exported by the `@org/custom-logger` package and accepting only one parameter to configure the logging `level`: - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: { - entrypoint: "@org/custom-logger", - config: { - level: "warn" - } - } - } -}); -``` - -The following example implements a minimal logger returning an [`AstroLoggerDestination` object](#astrologgerdestination) with the required `write()` function: - -```ts title="@org/custom-logger/index.ts" -import type { - AstroLoggerLevel, - AstroLoggerDestination, - AstroLoggerMessage -} from "astro"; -import { matchesLevel } from "astro/logger"; - -type LoggerOptions = { - level: AstroLoggerLevel -} - -function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { - const { level = 'info' } = options; - return { - write(message: AstroLoggerMessage) { - // Use this utility to understand if the message should be printed - if (matchesLevel(message.level, level)) { - // log message somewhere and take the level into consideration - } - } - } -} - -export default orgLogger; -``` - -## Runtime - -The [context object](/en/reference/api-reference/#the-context-object) now exposes a `logger` object containing the following functions: - -- `error()`, which emits a message with `error` level. -- `warn()`, which emits a message with `warn` level. -- `info()`, which emits a message with `info` level. - -```astro ---- -Astro.logger.error("This is an error"); -Astro.logger.warn("This is a warning"); -Astro.logger.info("This is an info"); ---- -``` - -## Log level - -A level is an internal, arbitrary score assigned to each message. When a logger is configured with a certain level, only the messages with a level equal to or higher are printed. - -There are three levels, from the highest to the lowest score: -1. `error` -2. `warn` -3. `info` - -The following example configures the JSON logger to print only messages that have the `warn` level or higher: - -```js title="astro.config.mjs" {5} ins='level: "warn"' -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ level: "warn" }) - } -}); -``` - -The `astro/logger` package exposes a [`matchesLevel()`](#matcheslevel) helper to check the log level. This can be useful when [building a custom logger](#custom-loggers). - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); -``` ## Types reference @@ -262,7 +226,7 @@ This is the interface that custom loggers must implement.

-**Type:** `(message: AstroLoggerMessage) => void` + **Type:** `(message: AstroLoggerMessage) => void`

A mandatory method called for each log and accepting an [`AstroLoggerMessage`](#astrologgermessage). @@ -271,7 +235,7 @@ A mandatory method called for each log and accepting an [`AstroLoggerMessage`](#

-**Type:** `() => Promise | void` + **Type:** `() => Promise | void`

An optional function called at the end of each request. This is useful for advanced loggers that need to flush log messages while keeping the connection to the destination alive. @@ -280,7 +244,7 @@ An optional function called at the end of each request. This is useful for advan

-**Type:** `() => Promise | void` + **Type:** `() => Promise | void`

An optional function called before a server is shut down. This function is usually called by adapters such as `@astrojs/node`. @@ -298,7 +262,7 @@ The level of the message. Available variants:

-**Type:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }` + **Type:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }`

The incoming object from the [`AstroLoggerDestination.write()`](#astrologgerdestinationwrite) function: - `message`: the message being logged. @@ -306,18 +270,18 @@ The incoming object from the [`AstroLoggerDestination.write()`](#astrologgerdest - `label`: an arbitrary label assigned to the log message. - `newLine`: whether this message should add a trailing newline. -## APIs reference +## APIs reference The following APIs can be imported from the `astro/logger` specifier. -### `matchesLevel` +### `matchesLevel()`

-**Type:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean` + **Type:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean`

-Given two [log levels](#log-level), it returns whether the first level matches the second level. +Given two [log levels](#log-level), it returns whether the first level matches the second level. ```js import { matchesLevel } from "astro/logger"; diff --git a/src/content/docs/ko/reference/experimental-flags/logger.mdx b/src/content/docs/ko/reference/experimental-flags/logger.mdx deleted file mode 100644 index d3930e138a7c0..0000000000000 --- a/src/content/docs/ko/reference/experimental-flags/logger.mdx +++ /dev/null @@ -1,328 +0,0 @@ ---- -title: 실험적 로거 -sidebar: - label: 로거 -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**타입:** `object`
-**기본값:** `undefined`
- -

- -사용자가 제어할 수 있는 실험적인 커스텀 로거를 활성화합니다. - -이 설정이 제공되면 사용자는 Astro에서 내보내는 로그를 완전히 제어할 수 있습니다. 또한 이 기능에는 새로운 `logHandlers`를 통해 사용할 수 있는 몇 가지 내장 로거가 포함되어 있습니다. - -다음 예시는 가독성 있는 출력 형식을 사용하는 내장 JSON 로거를 활성화합니다. - -```js title="astro.config.mjs" {5} ins="logHandlers" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -또는 `--experimentalJson` 플래그를 사용하면 `dev`, `build`, `sync` 명령어 실행 시 JSON 로깅을 사용할 수 있습니다. - -```shell -astro dev --experimentalJson -astro sync --experimentalJson -astro build --experimentalJson -``` - - -## 내장 로거 - -이 기능에는 세 가지 내장 로거가 포함되어 있습니다. - -### `logHandlers.json` - -메시지를 JSON 형식으로 출력하는 로거입니다. 로그는 다음과 같은 형태입니다. -```json -{ "message": "", "label": "router", "level": "info", "time": "" } -``` - -#### JSON 로거 옵션 - -

-**타입:** `{ pretty: boolean; level: AstroLoggerLevel; }`
-**기본값:** `{ pretty: false, level: 'info' }` - -

- -`json` 로거는 다음 옵션을 허용합니다. - -- `pretty`: `true`일 경우 JSON 로그가 여러 줄로 출력됩니다. 기본값은 `false`입니다. -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="json" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -### `logHandlers.console` - -`console`을 출력 대상으로 사용하는 로거입니다. 메시지 레벨에 따라 서로 다른 채널을 사용합니다. - -- `error` 메시지는 `console.error()`를 사용하여 출력됩니다. -- `warn` 메시지는 `console.warn()`을 사용하여 출력됩니다. -- `info` 메시지는 `console.info()`를 사용하여 출력됩니다. - -#### Console 로거 옵션 - -

-**타입:** `{ level: AstroLoggerLevel }`
-**기본값:** `{ level: 'info' }` - -

- -`console` 로거는 다음 옵션을 허용합니다. - -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="console" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.console({ level: 'warn' }) - } -}); -``` - -### `logHandlers.node` - -메시지를 [`process.stdout`](https://nodejs.org/api/process.html#processstdout) 및 [`process.stderr`](https://nodejs.org/api/process.html#processstderr)로 출력하는 로거입니다. `error` 레벨 메시지는 `stderr`로 출력되며, 나머지는 `stdout`으로 출력됩니다. - -Astro의 기본 로거입니다. - -#### Node 로거 옵션 - -

-**타입:** `{ level: AstroLoggerLevel }`
-**기본값:** `{ level: 'info' }` - -

- -`node` 로거는 다음 옵션을 허용합니다. - -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="node" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.node({ level: 'warn' }) - } -}); -``` - -### `logHandlers.compose` - -여러 로거를 임의의 순서로 구성할 수 있게 해주는 특별한 함수입니다. 동일한 메시지가 모든 로거에 전달됩니다. - -다음 예시는 기본 로그 레벨을 사용하여 콘솔 로거와 JSON 로거를 조합합니다. - -```js title="astro.config.mjs" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.compose( - logHandlers.console(), - logHandlers.json() - ) - } -}); -``` - -## 커스텀 로거 - -`logger` 설정에 적절한 구성을 제공하여 커스텀 로거를 만들 수 있습니다. 이 설정은 로거가 내보내지는 모듈을 지정하는 필수 `entrypoint`와 로거에 전달할 선택적 구성을 포함한 객체를 사용합니다. 구성은 직렬화 가능해야 합니다. - -로거 함수는 `default`로 내보내야 합니다. - -커스텀 로거를 정의하면 Astro에서 출력하는 로그를 포함한 모든 로그를 직접 관리하게 됩니다. - -다음 예시는 `@org/custom-logger` 패키지에서 내보내는 커스텀 로거를 정의하며, 로깅 `level`을 구성하기 위한 하나의 매개변수만 받습니다. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: { - entrypoint: "@org/custom-logger", - config: { - level: "warn" - } - } - } -}); -``` - -다음 예시는 필수 `write()` 함수를 포함하는 [`AstroLoggerDestination` 객체](#astrologgerdestination)를 반환하는 최소한의 로거를 구현합니다. - -```ts title="@org/custom-logger/index.ts" -import type { - AstroLoggerLevel, - AstroLoggerDestination, - AstroLoggerMessage -} from "astro"; -import { matchesLevel } from "astro/logger"; - -type LoggerOptions = { - level: AstroLoggerLevel -} - -function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { - const { level = 'info' } = options; - return { - write(message: AstroLoggerMessage) { - // 이 유틸리티를 사용하여 메시지를 출력해야 하는지 확인합니다. - if (matchesLevel(message.level, level)) { - // 메시지를 적절한 위치에 기록하고 로그 레벨을 반영합니다. - } - } - } -} - -export default orgLogger; -``` - -## 런타임 - -이제 [컨텍스트 객체](/ko/reference/api-reference/#컨텍스트-객체)는 다음 함수를 포함하는 `logger` 객체를 노출합니다. - -- `error()`: `error` 레벨의 메시지를 내보냅니다. -- `warn()`: `warn` 레벨의 메시지를 내보냅니다. -- `info()`: `info` 레벨의 메시지를 내보냅니다. - -```astro ---- -Astro.logger.error("에러입니다"); -Astro.logger.warn("경고입니다"); -Astro.logger.info("정보입니다"); ---- -``` - -## 로그 레벨 - -레벨은 각 메시지에 할당되는 내부적인 점수입니다. 로거가 특정 레벨로 구성되면 해당 레벨 이상인 메시지만 출력됩니다. - -가장 높은 점수부터 가장 낮은 점수까지 세 가지 레벨이 있습니다. -1. `error` -2. `warn` -3. `info` - -다음 예시는 JSON 로거가 `warn` 레벨 이상의 메시지만 출력하도록 구성합니다. - -```js title="astro.config.mjs" {5} ins='level: "warn"' -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ level: "warn" }) - } -}); -``` - -`astro/logger` 패키지는 로그 레벨을 확인하기 위해 [`matchesLevel()`](#matcheslevel) 헬퍼를 노출합니다. 이는 [커스텀 로거를 빌드할 때](#커스텀-로거) 유용할 수 있습니다. - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); -``` - - -## 타입 참조 - -다음 타입은 `astro` 식별자에서 가져올 수 있습니다. - -### `AstroLoggerDestination` - -커스텀 로거가 구현해야 하는 인터페이스입니다. - -#### `AstroLoggerDestination.write()` - -

- -**타입:** `(message: AstroLoggerMessage) => void` -

- -각 로그에 대해 호출되는 필수 메서드이며 [`AstroLoggerMessage`](#astrologgermessage)를 인자로 받습니다. - -#### `AstroLoggerDestination.flush()` - -

- -**타입:** `() => Promise | void` -

- -각 요청이 끝날 때 호출되는 선택적 함수입니다. 출력 대상과의 연결을 유지하면서 로그 메시지를 플러시해야 하는 고급 로거에 유용합니다. - -#### `AstroLoggerDestination.close()` - -

- -**타입:** `() => Promise | void` -

- -서버가 종료되기 전에 호출되는 선택적 함수입니다. 이 함수는 일반적으로 `@astrojs/node`와 같은 어댑터에 의해 호출됩니다. - -### `AstroLoggerLevel` - -메시지 레벨입니다. 사용 가능한 레벨은 다음과 같습니다. -- `'debug'` -- `'info'` -- `'warn'` -- `'error'` -- `'silent'` - -### `AstroLoggerMessage` - -

- -**타입:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }` -

-[`AstroLoggerDestination.write()`](#astrologgerdestinationwrite) 함수로부터 들어오는 객체입니다. -- `message`: 로깅되는 메시지입니다. -- `level`: 메시지의 레벨입니다. -- `label`: 로그 메시지에 할당된 임의의 레이블입니다. -- `newLine`: 이 메시지가 후행 줄바꿈을 추가해야 하는지 여부입니다. - -## API 참조 - -다음 API는 `astro/logger` 식별자에서 가져올 수 있습니다. - -### `matchesLevel` - -

- -**타입:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean` -

- -두 개의 [로그 레벨](#로그-레벨)이 주어졌을 때, 첫 번째 레벨이 두 번째 레벨 이상인지 여부를 반환합니다. - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); // true -matchesLevel("info", "error"); // false - -```