---
title: 日志
---

来源：https://mikro-orm.io/docs/logging

出于开发目的，启用日志与调试模式可能会很有用：

```ts
return MikroORM.init({
  debug: true,
});
```

这样做之后，`MikroORM` 会开始使用 `console.log()` 函数输出所有查询：

```
[query] select `e0`.* from `author` as `e0` where `e0`.`name` = ? limit ? [took 2 ms]
[query] begin [took 1 ms]
[query] insert into `author` (`name`, `email`, `created_at`, `updated_at`, `terms_accepted`) values (?, ?, ?, ?, ?) [took 2 ms]
[query] commit [took 2 ms]
```

这对排查实体发现相关的问题同样有用，因为你会看到每个被处理实体的信息：

```
[discovery] ORM entity discovery started
[discovery] - processing entity Author
[discovery] - using cached metadata for entity Author
[discovery] - processing entity Book
[discovery] - processing entity BookTag
[discovery] - entity discovery finished after 13 ms
```

<a id="disabling-colored-output"></a>
## 禁用彩色输出

要禁用彩色输出，你可以在 ORM 配置中使用 `colors` 选项，或使用下面这些环境变量之一：

- `MIKRO_ORM_NO_COLOR`
- `NO_COLOR`
- `MIKRO_ORM_COLORS`
- `FORCE_COLOR`

<a id="logger-namespaces"></a>
## Logger 命名空间

有多个 Logger 命名空间，你可以只请求其中特定的一些而省略其余的。只需通过 `debug` 选项指定它们的数组：

```ts
return MikroORM.init({
  debug: ['query'], // 现在只会记录查询
});
```

目前共有 7 个命名空间——`query`、`query-params`、`schema`、`discovery`、`info`、`deprecated` 与 `slow-query`。

如果你提供了 `query-params`，那么必须同时提供 `query` 它才会生效。

<a id="slow-query-logging"></a>
## 慢查询日志

你可以配置一个阈值（毫秒），自动记录耗时过长的查询。只要达到阈值，慢查询日志就一定会被输出，与 `debug` 设置无关。

```ts
return MikroORM.init({
  slowQueryThreshold: 200, // 记录耗时 200ms 及以上的查询
});
```

慢查询会通过 `slow-query` 命名空间以 `warning` 级别记录。失败的慢查询会以 `error` 级别记录。把阈值设为 `0` 会把每条查询都记录为慢查询。

```
[slow-query] select * from `user` where `id` = 1 [took 450 ms]
```

<a id="custom-slow-query-logger"></a>
### 自定义慢查询 logger

默认情况下，慢查询日志走主 logger。你可以通过 `slowQueryLoggerFactory` 提供一个独立的 logger 实例——例如把慢查询写入文件或发送给监控服务：

```ts
return MikroORM.init({
  slowQueryThreshold: 200,
  slowQueryLoggerFactory: options => new DefaultLogger({
    ...options,
    writer: msg => fs.appendFileSync('slow-queries.log', msg + '\n'),
  }),
});
```

该工厂的形态与 `loggerFactory` 相同。慢查询日志条目会以 `context.enabled = true` 输出，以绕过调试模式检查，因此自定义 logger 实现必须在其 `isEnabled()` 方法中尊重 `context.enabled`（如 `DefaultLogger` 所做的那样），慢查询日志才能生效。

<a id="deprecation-warnings"></a>
## 弃用警告

即使没有启用 `debugMode`，默认 logger 也会在控制台显示 `deprecated` 消息。

当某个东西被弃用时，意味着有意在未来的版本中移除它。弃用消息应该会为你建议替代方案，你应该在升级到主版本之前切换过去。

你可以通过把 `ignoreDeprecations` 设为 `true` 忽略所有弃用警告

```ts
return MikroORM.init({
  ignoreDeprecations: true, // 现在不会再记录任何弃用警告，不过升级时你可能会措手不及
});
```

当你正在积极消除弃用警告、为升级做准备时，你多半希望逐个处理它们。你可以只忽略那些眼下无法处理的特定弃用警告，同时仍然被那些你还不知道的其他警告提醒到。为此，请列出你想忽略的弃用警告，例如：

```ts
return MikroORM.init({
  ignoreDeprecations: ['D0001'], // 忽略标签为 "D0001" 的弃用，但出现其他弃用时仍然显示
});
```

你可以在[配置章节中关于弃用警告的部分](./58-configuration.md#deprecation-warnings)看到弃用错误的完整列表。

<a id="highlighters"></a>
## 高亮器

此前使用 Highlight.js 来高亮 CLI 中的各种内容，比如 SQL 与 mongo 查询，或者通过 CLI 生成的迁移与实体。虽然该库工作正常，但它带来了性能问题，主要影响那些用 webpack 打包并使用 lambda 的场景，因为这个库非常庞大。

高亮默认是禁用的。有 2 个高亮器你可以选择使用（需要先安装它们）。

```ts
import { SqlHighlighter } from '@mikro-orm/sql-highlighter';

MikroORM.init({
  highlighter: new SqlHighlighter(),
  // ...
});
```

对于 MongoDB，你可以使用 `@mikro-orm/mongo-highlighter` 包中的 `MongoHighlighter`。

<a id="logger-customization"></a>
## Logger 定制

有若干定制选项，可用于改变风格或加入自定义逻辑。

<a id="query-labels"></a>
### 查询标签

在使用 [`EntityManager.find`](./10-entity-manager.md#fetching-entities-with-entitymanager) 或 [`EntityManager.findOne`](./10-entity-manager.md#fetching-entities-with-entitymanager) 时，出于调试与消除冗余的目的，记录查询的来源往往很有益处。

两个调用的 `FindOptions` 参数中都可以包含一个可选的 `logging.label` 选项，它会在调试模式启用时给输出添加标签。

```ts
const author = await em.findOne(Author, { id: 1 }, { logging: { label: 'Author Retrieval - /authors/me' } });
// [query] (Author Retrieval - /authors/me) select "a0".* from "Author" as "a0" where "a0"."id" = 1 limit 1 [took 21 ms]
```

<a id="changing-debugmode-or-disabling-logging-for-specific-queries"></a>
### 改变 `debugMode` 或对特定查询禁用日志

如果你想按查询粒度禁用日志或改变调试模式，可以利用 `FindOptions.logging` 及其 `enabled` 或 `debugMode` 属性：

```ts
// MikroORM.init({ debug: true });
const author = await em.findOne(Author, { id: 1 }, { logging: { enabled: false } });
// 覆盖配置，不显示任何 logger 输出

// ...

// MikroORM.init({ debug: false });
const author = await em.findOne(Author, { id: 1 }, { logging: { enabled: true } });
// 覆盖配置，显示 logger 输出

// ...

// MikroORM.init({ debug: ['query-labels'] });
const author = await em.findOne(Author, { id: 1 }, { logging: { debugMode: ['query'] } });
// 覆盖配置，显示 query 的 logger 输出
```

<a id="using-a-custom-logger"></a>
### 使用自定义 logger

你可以通过 `logger` 选项提供自己的 logger 函数：

```ts
return MikroORM.init({
  debug: true,
  logger: msg => myCustomLogger.log(msg),
});
```

<a id="using-a-custom-loggerfactory"></a>
### 使用自定义 `LoggerFactory`

如果你想对记录什么以及如何记录有更多控制权，请在配置中使用 `loggerFactory` 选项，并继承 `SimpleLogger` 类、继承 `DefaultLogger` 类，或从头实现你自己的 `Logger`：

<a id="extending-defaultlogger-or-simplelogger"></a>
#### 继承 `DefaultLogger` 或 `SimpleLogger`

你可以继承 `DefaultLogger` 或 `SimpleLogger`，而不必从头实现一切。`DefaultLogger` 与 `SimpleLogger` 都从 `@mikro-orm/core` 包导出，其中 `SimpleLogger` 不带颜色。

```ts
class CustomLogger extends DefaultLogger {
  log(namespace: LoggerNamespace, message: string, context?: LogContext) {
    // 为输出创建你自己的实现：
    console.log(`[${namespace}] (${context.label}) ${message}`);

    // 或者利用 DefaultLogger 的实现：
    super.log(namespace, message, context)
  }
}

return MikroORM.init({
  debug: true,
  loggerFactory: (options) => new CustomLogger(options),
});
```

要改用 `SimpleLogger`，只需把上例中的 `DefaultLogger` 替换掉：
```ts
class CustomLogger extends SimpleLogger {
  // ...
}
```

<a id="creating-a-custom-logger-from-scratch"></a>
#### 从头创建自定义 logger

你可以使用 `loggerFactory` 并使用你自己对 `Logger` 接口的实现：

```ts
import { Logger, LoggerOptions, MikroORM, Configuration } from '@mikro-orm/core';

class MyLogger implements Logger {
  // ...
}

const orm = await MikroORM.init({
  debug: true,
  loggerFactory: (options) => new MyLogger(options),
});
```

`Logger` 接口定义如下：

```ts
interface Logger {
  log(namespace: LoggerNamespace, message: string, context?: LogContext): void;
  error(namespace: LoggerNamespace, message: string, context?: LogContext): void;
  warn(namespace: LoggerNamespace, message: string, context?: LogContext): void;
  logQuery(context: LogContext): void;
  setDebugMode(debugMode: boolean | LoggerNamespace[]): void;
  isEnabled(namespace: LoggerNamespace, context?: LogContext): boolean;
}

type LoggerNamespace = 'query' | 'query-params' | 'schema' | 'discovery' | 'info' | 'deprecated' | 'slow-query';

interface LogContext extends Dictionary {
  query?: string;
  label?: string;
  params?: unknown[];
  took?: number;
  level?: 'info' | 'warning' | 'error';
  enabled?: boolean;
  debugMode?: LoggerNamespace[];
  connection?: {
    type?: string;
    name?: string;
  };
}
```

<a id="providing-additional-context-to-a-custom-logger"></a>
### 为自定义 logger 提供额外上下文

如果你实现了自己的 `LoggerFactory`，并且需要在自定义 logger 实现中访问额外的上下文值，请利用 `FindOptions` 的 `loggerContext` 属性。向该对象添加额外的键/值对，它们就能在你的自定义 logger 中被访问到：

```ts
const res = await em.findAll(Author, { loggerContext: { meaningOfLife: 42 } });

// ...

class CustomLogger extends DefaultLogger {
  log(namespace: LoggerNamespace, message: string, context?: LogContext) {
    console.log(context?.meaningOfLife);
    // 42
  }
}
```

logger 上下文也可以在 `EntityManager` 级别设置，例如通过 `em.fork()`：

```ts
const fork = em.fork({
  loggerContext: { meaningOfLife: 42 },
});
const res = await fork.findAll(Author); // 与上一个示例相同
```

> `EntityManager` 的默认 logger 上下文包含 fork 的 `id`，这样你就能分辨是哪个 `EntityManager` 实例发出了哪些查询。
