# 日志

> 英文标题：Logging
> 官网原文：https://typeorm.io/docs/logging
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 31 块

---

<!-- EN -->
# Logging

<!-- ZH -->
# 日志

<!-- EN -->
## Enabling logging

<!-- ZH -->
## 启用日志

<!-- EN -->
You can enable logging of all queries and errors by simply setting `logging: true` in data source options:

<!-- ZH -->
只需在数据源选项中设置 `logging: true`，就可以启用所有查询和错误的日志：

<!-- EN -->
```typescript
{
    name: "mysql",
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    ...
    logging: true
}
```

<!-- ZH -->
```typescript
{
    name: "mysql",
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    ...
    logging: true
}
```

<!-- EN -->
## Logging options

<!-- ZH -->
## 日志选项

<!-- EN -->
You can enable different types of logging in data source options:

<!-- ZH -->
你可以在数据源选项中启用不同类型的日志：

<!-- EN -->
```typescript
{
    host: "localhost",
    ...
    logging: ["query", "error"]
}
```

<!-- ZH -->
```typescript
{
    host: "localhost",
    ...
    logging: ["query", "error"]
}
```

<!-- EN -->
If you want to enable logging of failed queries only then only add `error`:

<!-- ZH -->
如果你只想启用失败查询的日志，那就只加 `error`：

<!-- EN -->
```typescript
{
    host: "localhost",
    ...
    logging: ["error"]
}
```

<!-- ZH -->
```typescript
{
    host: "localhost",
    ...
    logging: ["error"]
}
```

<!-- EN -->
There are other options you can use:

<!-- ZH -->
还有其他可用的选项：

<!-- EN -->
* `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.

<!-- ZH -->
* `query` - 记录所有查询。
* `error` - 记录所有失败的查询和错误。
* `schema` - 记录结构构建过程。
* `warn` - 记录 orm 内部警告。
* `info` - 记录 orm 内部提示性消息。
* `log` - 记录 orm 内部日志消息。

<!-- EN -->
You can specify as many options as needed. If you want to enable all logging you can simply specify `logging: "all"`:

<!-- ZH -->
你可以按需指定任意多个选项。如果想启用全部日志，只需指定 `logging: "all"`：

<!-- EN -->
```typescript
{
    host: "localhost",
    ...
    logging: "all"
}
```

<!-- ZH -->
```typescript
{
    host: "localhost",
    ...
    logging: "all"
}
```

<!-- EN -->
## Log long-running queries

<!-- ZH -->
## 记录耗时过长的查询

<!-- EN -->
If you have performance issues, you can log queries that take too much time to execute by setting `maxQueryExecutionTime` in data source options:

<!-- ZH -->
如果你遇到性能问题，可以通过在数据源选项中设置 `maxQueryExecutionTime` 来记录执行耗时过长的查询：

<!-- EN -->
```typescript
{
    host: "localhost",
    ...
    maxQueryExecutionTime: 1000
}
```

<!-- ZH -->
```typescript
{
    host: "localhost",
    ...
    maxQueryExecutionTime: 1000
}
```

<!-- EN -->
This code will log all queries which run for more than `1 second`.

<!-- ZH -->
这段代码会记录所有运行超过 `1 秒` 的查询。

<!-- EN -->
## Changing default logger

<!-- ZH -->
## 更换默认日志记录器

<!-- EN -->
TypeORM ships with 5 different built-in loggers:

<!-- ZH -->
TypeORM 内置了 5 种不同的日志记录器：

<!-- EN -->
* `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](https://github.com/mtxr/vscode-sqltools)).
* `file` - this logger writes all logs into the specified file (or `ormlogs.log` in the current working directory if no path is provided).
* `debug` - this logger uses [debug package](https://github.com/debug-js/debug), to turn on logging set your env variable `DEBUG=typeorm:*` (note: this logger will pass all logs to the `debug` package, which controls the log level setting).

<!-- ZH -->
* `advanced-console` - 这是默认的日志记录器，它使用颜色和 sql 语法高亮把所有消息输出到控制台。
* `simple-console` - 这是一个简单的控制台日志记录器，与 advanced 记录器完全相同，但不使用任何颜色高亮。如果你对彩色日志有困扰或不喜欢它，可以用这个记录器。
* `formatted-console` - 这与 advanced 记录器几乎相同，但它会把 sql 查询格式化得更易读（使用 [@sqltools/formatter](https://github.com/mtxr/vscode-sqltools)）。
* `file` - 该记录器把所有日志写入指定文件（如果未提供路径，则写入当前工作目录下的 `ormlogs.log`）。
* `debug` - 该记录器使用 [debug 包](https://github.com/debug-js/debug)，要开启日志请设置环境变量 `DEBUG=typeorm:*`（注意：该记录器会把所有日志交给 `debug` 包，由它控制日志级别设置）。

<!-- EN -->
You can enable any of them in data source options:

<!-- ZH -->
你可以在数据源选项中启用其中任意一种：

<!-- EN -->
```typescript
{
    host: "localhost",
    ...
    logging: true,
    logger: "file"
}
```

<!-- ZH -->
```typescript
{
    host: "localhost",
    ...
    logging: true,
    logger: "file"
}
```

<!-- EN -->
## Using custom logger

<!-- ZH -->
## 使用自定义日志记录器

<!-- EN -->
You can create your own logger class by implementing the `Logger` interface:

<!-- ZH -->
你可以通过实现 `Logger` 接口创建自己的日志记录器类：

<!-- EN -->
```typescript
import { Logger } from "typeorm"

export class MyCustomLogger implements Logger {
    // implement all methods from logger class
}
```

<!-- ZH -->
```typescript
import { Logger } from "typeorm"

export class MyCustomLogger implements Logger {
    // 实现日志记录器类的所有方法
}
```

<!-- EN -->
Or you can extend the `AbstractLogger` class:

<!-- ZH -->
或者你也可以继承 `AbstractLogger` 类：

<!-- EN -->
```typescript
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
            }
        }
    }
}
```

<!-- ZH -->
```typescript
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
            }
        }
    }
}
```

<!-- EN -->
And specify it in data source options:

<!-- ZH -->
并在数据源选项中指定它：

<!-- EN -->
```typescript
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(),
})
```

<!-- ZH -->
```typescript
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(),
})
```

<!-- EN -->
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:

<!-- ZH -->
日志记录器的方法在可用时可以接受 `QueryRunner`。如果你想记录额外数据，这会很有帮助。此外，通过 query runner，你还能访问在 persist/remove 期间传入的额外数据。例如：

<!-- EN -->
```typescript
// 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);
}
```

<!-- ZH -->
```typescript
// 用户在实体保存期间发出请求
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);
}
```
