📜  日志查询 typeorm (1)

📅  最后修改于: 2023-12-03 14:55:08.857000             🧑  作者: Mango

日志查询 TypeORM

TypeORM是一个ORM框架,可以帮助我们轻松处理数据库操作。在应用程序中,日志系统对于debug和错误追踪非常重要。TypeORM集成了许多日志记录选项,可以方便地使用。本篇文章将介绍如何在TypeORM中使用日志查询。

安装TypeORM

首先,在项目中安装TypeORM:

npm install typeorm
配置TypeORM连接

然后,在应用程序中,我们需要连接数据库。我们可以使用TypeORM连接到各种类型的数据库,包括MySQL,PostgreSQL,SQLite等等。本篇文章使用SQLite作为示例。

首先,我们需要在应用程序中创建一个连接选项对象。我们可以在对象中指定连接的数据库类型,主机地址,端口,用户名,密码等信息。

import { createConnection } from 'typeorm';

const connectionOptions = {
  type: 'sqlite',
  database: 'example.db',
  synchronize: true, 
  entities: [__dirname + '/entities/*.js'],
};

这里我们使用createConnection方法来创建一个TypeORM连接,并传入连接选项对象。entities选项用于指定实体类所在的路径,实体类定义数据库表的结构和字段。定义好后,我们在连接上使用connect()方法。

createConnection(connectionOptions)
  .then(async (connection) => {
    console.log('Database connected.....');
  })
  .catch((error) => {
    console.log('Error while connecting to the database', error);
  });

当我们运行应用程序时,我们应该看到数据库已连接的输出。

添加日志记录器

现在我们的应用程序已经连接到SQLite数据库了,我们可以开始添加日志记录器。TypeORM使用Node.js的内置日志系统。默认情况下,日志系统将输出到控制台。

设置日志级别

我们可以在连接选项对象中指定最低日志级别。

const connectionOptions = {
  type: 'sqlite',
  database: 'example.db',
  synchronize: true,
  logging: 'all',
  entities: [__dirname + '/entities/*.js'],
};

在这里,我们将日志级别设置为all,表示我们记录所有类型的日志。

记录SQL日志

TypeORM拦截并记录所有执行的SQL语句,我们可以通过打开SQL查询日志来查看这些SQL语句。

const connectionOptions = {
  type: 'sqlite',
  database: 'example.db',
  synchronize: true,
  logging: ['all', 'query', 'error'],
  entities: [__dirname + '/entities/*.js'],
}

现在,我们的日志记录器可以记录查询操作了。

查询日志

我们可以使用getRepository()方法从数据库中检索数据。

import { getRepository } from 'typeorm';
import { User } from './entities/user.entity';

const userRepository = getRepository(User);

// 查询数据
const users = await userRepository.find();

通过这种方法执行的查询操作可以在日志中记录。这使得我们可以在调试应用程序时检查数据库的实际查询操作。

结论

TypeORM不仅可以轻松地处理数据库操作,还提供了许多实用功能。使用上述方法,可以添加并记录TypeOrm的日志查询,从而使调试和故障排除更简单。