Skip to main content
Version: 6.4

日志记录

出于开发目的,启用日志记录和调试模式可能会很方便:

¥For development purposes it might come handy to enable logging and debug mode:

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

通过这样做,MikroORM 将开始使用 console.log() 函数转储所有查询:

¥By doing this MikroORM will start using console.log() function to dump all queries:

[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]

它对于调试实体发现的问题也很有用,因为你将看到有关每个已处理实体的信息:

¥It is also useful for debugging problems with entity discovery, as you will see information about every processed entity:

[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

禁用彩色输出

¥Disabling colored output

要禁用彩色输出,你可以使用 ORM 配置中的 colors 选项,或以下环境变量之一:

¥To disable colored output, you can use the colors option in the ORM config, or one of the following environment variables:

  • MIKRO_ORM_NO_COLOR

  • NO_COLOR

  • MIKRO_ORM_COLORS

  • FORCE_COLOR

记录器命名空间

¥Logger Namespaces

你可以专门请求多个 Logger 命名空间,同时省略其余的。只需通过 debug 选项指定它们的数组:

¥There are multiple Logger Namespaces that you can specifically request, while omitting the rest. Just specify array of them via the debug option:

return MikroORM.init({
debug: ['query'], // now only queries will be logged
});

目前,有 6 个命名空间 - queryquery-paramsschemadiscoveryinfodeprecated

¥Currently, there are 6 namespaces – query, query-params, schema, discovery, info and deprecated.

如果你提供 query-params,则还必须提供 query 才能使其生效。

¥If you provide query-params then you must also provide query in order for it to take effect.

弃用警告

¥Deprecation warnings

即使没有启用 debugMode,默认记录器也会在控制台中显示 deprecated 消息。

¥Even without debugMode enabled, the default logger will show deprecated messages in console.

当某些东西被弃用时,这意味着有意图在未来版本中删除它。弃用消息应该会为你建议在迁移到主要版本之前应切换到的替代方案。

¥When something is deprecated, it means there is an intention for it to be removed in a future version. The deprecation message should suggest alternatives for you that you should switch to before migrating to a major version.

你可以通过将 ignoreDeprecations 设置为 true 来忽略所有弃用警告

¥You can ignore all deprecation warnings by setting ignoreDeprecations to true

return MikroORM.init({
ignoreDeprecations: true, // now no deprecations will be logged, though you may be surprised when upgrading
});

当你积极尝试删除弃用警告以准备升级时,你可能希望一次解决一个问题。你可以仅忽略你现在无法处理的特定弃用警告,同时仍会收到你不知道的其他警告的警报。为此,请列出你想要忽略的弃用警告,例如

¥When you are actively trying to remove deprecation warnings in preparation for an upgrade, you would likely want to tackle them one at a time. You can ignore only specific deprecation warnings you can't deal with right now, while still being alerted of others you didn't know about. To do this, list the deprecation warnings you want to ignore, e.g.

return MikroORM.init({
ignoreDeprecations: ['D0001'], // ignore deprecation with label "D0001", but show others if they pop up
});

你可以在 配置中关于弃用警告的部分 中看到弃用错误列表。

¥You can see a list of deprecation errors in Configuration's section on deprecated warnings.

高亮器

¥Highlighters

以前,Highlight.js 用于高亮 CLI 中的各种内容,例如 SQL 和 mongo 查询,或通过 CLI 生成的迁移或实体。虽然该库运行良好,但它主要对通过 webpack 打包并使用 lambda 的用户造成性能问题,因为该库非常庞大。

¥Previously Highlight.js was used to highlight various things in the CLI, like SQL and mongo queries, or migrations or entities generated via CLI. While the library worked fine, it was causing performance issues mainly for those bundling via webpack and using lambdas, as the library was huge.

自 v4 以来, 不再返回实体,现在返回 实例。

¥Since v4, highlighting is disabled by default, and there are 2 highlighters you can optionally use (you need to install them first).

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

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

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

¥For MongoDB, you can use MongoHighlighter from @mikro-orm/mongo-highlighter package.

记录器自定义

¥Logger Customization

设置拥有实体上的哪些操作应级联到关系。

¥Several customization options exist to allow for style changes or custom logic.

查询标签

¥Query Labels

在使用 EntityManager.findEntityManager.findOne 进行调试和消除冗余时,记录查询的来源通常很有用。

¥It may often be beneficial to log the origin of a query when using EntityManager.find or EntityManager.findOne for debugging and redundancy elimination purposes.

可选的 logging.label 选项可以包含在任一调用的 FindOptions 参数中,当启用调试模式时,它将向输出添加标签。

¥An optional logging.label option can be included within the FindOptions parameter of either call which will add a label to the output when debug mode is enabled.

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]

更改 debugMode 或禁用特定查询的日志记录

¥Changing debugMode or disabling logging for specific queries

如果你想要禁用日志记录或根据每个查询更改调试模式,你可以利用 FindOptions.logging 及其 enableddebugMode 属性:

¥If you'd like to disable logging or change the debug mode on a per-query basis, you can leverage FindOptions.logging and its enabled or debugMode property:

// MikroORM.init({ debug: true });
const author = await em.findOne(Author, { id: 1 }, { logging: { enabled: false } });
// Overrides config and displays no logger output

// ...

// MikroORM.init({ debug: false });
const author = await em.findOne(Author, { id: 1 }, { logging: { enabled: true } });
// Overrides config and displays logger output

// ...

// MikroORM.init({ debug: ['query-labels'] });
const author = await em.findOne(Author, { id: 1 }, { logging: { debugMode: ['query'] } });
// Overrides config and displays logger output for query

使用自定义记录器

¥Using a custom logger

你可以通过 logger 选项提供自己的记录器功能:

¥You can provide your own logger function via the logger option:

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

使用自定义 LoggerFactory

¥Using a custom LoggerFactory

如果你想更好地控制记录的内容和方式,请在你的配置中使用 loggerFactory 选项并扩展 SimpleLogger 类、扩展 DefaultLogger 类或从头开始创建你的 Logger

¥If you want more control over what is logged and how, use the loggerFactory option in your config and extend the SimpleLogger class, extend the DefaultLogger class, or make your Logger from scratch:

扩展 DefaultLoggerSimpleLogger

¥Extending DefaultLogger or SimpleLogger

你可以扩展 DefaultLoggerSimpleLogger,而不是从头开始实现一切。DefaultLoggerSimpleLogger 均从 @mikro-orm/core 包中导出,其中 SimpleLogger 为无色。

¥You can extend the DefaultLogger or SimpleLogger instead of implementing everything from scratch. DefaultLogger and SimpleLogger are both exported from the @mikro-orm/core package with SimpleLogger being colorless.

class CustomLogger extends DefaultLogger {
log(namespace: LoggerNamespace, message: string, context?: LogContext) {
// Create your own implementation for output:
console.log(`[${namespace}] (${context.label}) ${message}`);

// OR Utilize DefaultLogger's implementation:
super.log(namespace, message, context)
}
}

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

要改用 SimpleLogger,只需替换上面示例中的 DefaultLogger

¥To use SimpleLogger instead, simply replace DefaultLogger in the example above:

class CustomLogger extends SimpleLogger {
// ...
}

从头开始创建自定义记录器

¥Creating a custom logger from scratch

你可以使用 loggerFactory 并使用你自己的 Logger 接口实现:

¥You can use loggerFactory and use your own implementation of the Logger interface:

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 接口定义如下:

¥The Logger interface is defined as follows:

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';

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;
};
}

为自定义记录器提供额外上下文

¥Providing additional context to a custom logger

如果你已经实现了自己的 LoggerFactory 并且需要访问客户记录器实现中的其他上下文值,请使用 FindOptionsloggerContext 属性。向该对象添加其他键/值对将使它们在你的自定义记录器中可用:

¥If you have implemented your own LoggerFactory and need to access additional contextual values inside your customer logger implementation, utilize the loggerContext property of FindOptions. Adding additional key/value pairs to that object will make them available inside your custom logger:

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
}
}

记录器上下文也可以在 EntityManager 级别设置,例如通过 em.fork()

¥The logger context can be also set on EntityManager level, e.g. via em.fork():

const fork = em.fork({
loggerContext: { meaningOfLife: 42 },
});
const res = await fork.findAll(Author); // same as previous example

EntityManager 的默认记录器上下文包含 fork id,这样你就可以知道哪个 EntityManager 实例发出了哪些查询。

¥The default logger context of EntityManager contains the fork id, this way you can tell which EntityManager instance issued what queries.