日志
启用日志
只需在数据源选项中设置 logging: true,就可以启用所有查询和错误的日志:
{
name: "mysql",
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
...
logging: true
}日志选项
你可以在数据源选项中启用不同类型的日志:
{
host: "localhost",
...
logging: ["query", "error"]
}如果你只想启用失败查询的日志,那就只加 error:
{
host: "localhost",
...
logging: ["error"]
}还有其他可用的选项:
query- 记录所有查询。error- 记录所有失败的查询和错误。schema- 记录结构构建过程。warn- 记录 orm 内部警告。info- 记录 orm 内部提示性消息。log- 记录 orm 内部日志消息。
你可以按需指定任意多个选项。如果想启用全部日志,只需指定 logging: "all":
{
host: "localhost",
...
logging: "all"
}记录耗时过长的查询
如果你遇到性能问题,可以通过在数据源选项中设置 maxQueryExecutionTime 来记录执行耗时过长的查询:
{
host: "localhost",
...
maxQueryExecutionTime: 1000
}这段代码会记录所有运行超过 1 秒 的查询。
更换默认日志记录器
TypeORM 内置了 5 种不同的日志记录器:
advanced-console- 这是默认的日志记录器,它使用颜色和 sql 语法高亮把所有消息输出到控制台。simple-console- 这是一个简单的控制台日志记录器,与 advanced 记录器完全相同,但不使用任何颜色高亮。如果你对彩色日志有困扰或不喜欢它,可以用这个记录器。formatted-console- 这与 advanced 记录器几乎相同,但它会把 sql 查询格式化得更易读(使用 @sqltools/formatter)。file- 该记录器把所有日志写入指定文件(如果未提供路径,则写入当前工作目录下的ormlogs.log)。debug- 该记录器使用 debug 包,要开启日志请设置环境变量DEBUG=typeorm:*(注意:该记录器会把所有日志交给debug包,由它控制日志级别设置)。
你可以在数据源选项中启用其中任意一种:
{
host: "localhost",
...
logging: true,
logger: "file"
}使用自定义日志记录器
你可以通过实现 Logger 接口创建自己的日志记录器类:
import { Logger } from "typeorm"
export class MyCustomLogger implements Logger {
// 实现日志记录器类的所有方法
}或者你也可以继承 AbstractLogger 类:
import { AbstractLogger } from "typeorm"
export class MyCustomLogger extends AbstractLogger {
/**
* 把日志写入指定输出。
*/
protected writeLog(
level: LogLevel,
logMessage: LogMessage | LogMessage[],
queryRunner?: QueryRunner,
) {
const messages = this.prepareLogMessages(
logMessage,
{
highlightSql: false,
},
queryRunner,
)
for (let message of messages) {
switch (message.type ?? level) {
case "log":
case "schema-build":
case "migration":
console.log(message.message)
break
case "info":
case "query":
if (message.prefix) {
console.info(message.prefix, message.message)
} else {
console.info(message.message)
}
break
case "warn":
case "query-slow":
if (message.prefix) {
console.warn(message.prefix, message.message)
} else {
console.warn(message.message)
}
break
case "error":
case "query-error":
if (message.prefix) {
console.error(message.prefix, message.message)
} else {
console.error(message.message)
}
break
}
}
}
}并在数据源选项中指定它:
import { DataSource } from "typeorm"
import { MyCustomLogger } from "./logger/MyCustomLogger"
const dataSource = new DataSource({
name: "mysql",
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
logger: new MyCustomLogger(),
})日志记录器的方法在可用时可以接受 QueryRunner。如果你想记录额外数据,这会很有帮助。此外,通过 query runner,你还能访问在 persist/remove 期间传入的额外数据。例如:
// 用户在实体保存期间发出请求
postRepository.save(post, { data: { request: request } });
// 在日志记录器中你可以这样访问它:
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
const requestUrl = queryRunner && queryRunner.data["request"] ? "(" + queryRunner.data["request"].url + ") " : "";
console.log(requestUrl + "executing query: " + query);
}Enabling logging
You can enable logging of all queries and errors by simply setting logging: true in data source options:
{
name: "mysql",
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
...
logging: true
}Logging options
You can enable different types of logging in data source options:
{
host: "localhost",
...
logging: ["query", "error"]
}If you want to enable logging of failed queries only then only add error:
{
host: "localhost",
...
logging: ["error"]
}There are other options you can use:
query- logs all queries.error- logs all failed queries and errors.schema- logs the schema build process.warn- logs internal orm warnings.info- logs internal orm informative messages.log- logs internal orm log messages.
You can specify as many options as needed. If you want to enable all logging you can simply specify logging: "all":
{
host: "localhost",
...
logging: "all"
}Log long-running queries
If you have performance issues, you can log queries that take too much time to execute by setting maxQueryExecutionTime in data source options:
{
host: "localhost",
...
maxQueryExecutionTime: 1000
}This code will log all queries which run for more than 1 second.
Changing default logger
TypeORM ships with 5 different built-in loggers:
advanced-console- this is the default logger which logs all messages into the console using color and sql syntax highlighting.simple-console- this is a simple console logger which is exactly the same as the advanced logger, but it does not use any color highlighting. This logger can be used if you have problems / or don't like colorized logs.formatted-console- this is almost the same as the advanced logger, but it formats sql queries to be more readable (using @sqltools/formatter).file- this logger writes all logs into the specified file (orormlogs.login the current working directory if no path is provided).debug- this logger uses debug package, to turn on logging set your env variableDEBUG=typeorm:*(note: this logger will pass all logs to thedebugpackage, which controls the log level setting).
You can enable any of them in data source options:
{
host: "localhost",
...
logging: true,
logger: "file"
}Using custom logger
You can create your own logger class by implementing the Logger interface:
import { Logger } from "typeorm"
export class MyCustomLogger implements Logger {
// implement all methods from logger class
}Or you can extend the AbstractLogger class:
import { AbstractLogger } from "typeorm"
export class MyCustomLogger extends AbstractLogger {
/**
* Write log to specific output.
*/
protected writeLog(
level: LogLevel,
logMessage: LogMessage | LogMessage[],
queryRunner?: QueryRunner,
) {
const messages = this.prepareLogMessages(
logMessage,
{
highlightSql: false,
},
queryRunner,
)
for (let message of messages) {
switch (message.type ?? level) {
case "log":
case "schema-build":
case "migration":
console.log(message.message)
break
case "info":
case "query":
if (message.prefix) {
console.info(message.prefix, message.message)
} else {
console.info(message.message)
}
break
case "warn":
case "query-slow":
if (message.prefix) {
console.warn(message.prefix, message.message)
} else {
console.warn(message.message)
}
break
case "error":
case "query-error":
if (message.prefix) {
console.error(message.prefix, message.message)
} else {
console.error(message.message)
}
break
}
}
}
}And specify it in data source options:
import { DataSource } from "typeorm"
import { MyCustomLogger } from "./logger/MyCustomLogger"
const dataSource = new DataSource({
name: "mysql",
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
logger: new MyCustomLogger(),
})Logger methods can accept QueryRunner when it's available. It's helpful if you want to log additional data. Also, via query runner, you can get access to additional data passed during to persist/remove. For example:
// user sends request during entity save
postRepository.save(post, { data: { request: request } });
// in logger you can access it this way:
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
const requestUrl = queryRunner && queryRunner.data["request"] ? "(" + queryRunner.data["request"].url + ") " : "";
console.log(requestUrl + "executing query: " + query);
}