当前位置: 首页 > 工具软件 > knex > 使用案例 >

nodejs插件knex & 日志打印

曹普松
2023-12-01

nodejs学习

knex

  npm install -save knex
  • 引入,封装
const {dbconfig} = require('../config/index');
const knex = require('knex')({
    client: 'mysql',
    connection: dbconfig,
    log: {
        error (message) {
            console.log('[knex error]', message)
        }
    }
})
class Base{
  //查询
  all (tableName,where,who){
    return knex(tableName).where(where).select(...who)
  }
  // 新增
  insert (tableName,params){
    return knex(tableName).insert(params);
  }
  // 更改
  update (tableName,id, params){
    return knex(tableName).where('id', '=', id).update(params);
  }
  // 删除
  delete (tableName,id){
    return knex(tableName).where('id', '=', id).del();
  }
  //查询双表
  selectab(aobj,bobj){
    return knex({ a:aobj.name, b:bobj.name})
    .select({
      auser: `a.${aobj.out}`,
      bupload: `b.${bobj.out}`
    })
    .whereRaw('?? = ??', [`a.${aobj.where}`, `b.${bobj.where}`])
  }
}
// 测试------start
// let db = new Base()

//1、select
// db.all('user',{id:'33'},['name']).then(res=>{
//   console.log(res);
// }).catch(e=>{
//   console.log(e);
// })

//2、insert
// db.insert('user',{name:'lisa',password:'123456'}).then(res=>{
//   console.log(res);
// }).catch(e=>{
//   console.log(e);
// })

//3、update
// db.update('user',36,{name:'jenny'}).then(res=>{
//   console.log(res);
// }).catch(e=>{
//   console.log(e);
// })

// 4、delete
// db.delete('user',35).then(res=>{
//   console.log(res);
// }).catch(e=>{
//   console.log(e);
// })

// 5、selectab
// db.selectab({name:'user',out:'name',where:'relation'},{name:'upload',out:'name',where:'id'}).then(res=>{
//   console.log(res);
// }).catch(e=>{
//   console.log(e);
// })

// 测试------end
module.exports = new Base();

  • 运行测试
node utils/knex.ts

打印日志

  • npm i winston
    
  • 根目录添加一个配置打印日志格式的文件 logger.js文末有github地址,内参考logger.js

    const { createLogger, format, transports } = require('winston');
    const fs = require('fs');
    const path = require('path');
    
    const env = process.env.NODE_ENV || 'development';
    const logDir = 'log';
    
    // Create the log directory if it does not exist
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir);
    }
    
    const filename = path.join(logDir, 'results.log');
    
    const logger = createLogger({
      // change level if in dev environment versus production
      level: env === 'production' ? 'info' : 'debug',
      format: format.combine(
        format.label({ label: path.basename(process.mainModule.filename) }),
        format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' })
      ),
      transports: [
        new transports.Console({
          format: format.combine(
            format.colorize(),
            format.printf(
              info =>
                `${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
            )
          )
        }),
        new transports.File({
          filename,
          format: format.combine(
            format.printf(
              info =>
                `${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
            )
          )
        })
      ]
    });
    
    module.exports = logger;
    
  • app.js内请求错误处理的部分删掉,更改为打印日志

    const logger = require('./logger')
    app.use(function(err, req, res, next) {
      logger.error(`${req.method} ${req.originalUrl} ` + err.message)
      const errmsg = err.message
      res.status(err.status||500).json({
        code:-1,
        success:false,
        message:errmsg,
        data:{} 
      })
    });
    

参考:

Node.js + Express + MySQL 搭建项目框架

winston

Knex.js

 类似资料: