添加日志模块
日志记录是网站开发必备的模块,方便我们进行线上问题定位。
安装 log4js
代码语言:javascript复制yarn add log4js
yarn add -D @types/log4js
配置和使用
- 配置文件中增加日志配置 src/config/index.ts
log: {
appenders: {
out: { type: 'stdout' },
app: {
type: 'file',
filename: 'logs/app.log',
pattern: '-yyyy-MM-dd',
maxLogSize: 10485760,
numBackups: 3,
},
},
categories: {
default: { appenders: ['out', 'app'], level: 'info' },
},
}
- 创建日志处理文件 src/utils/logger.ts
import { configure, getLogger } from 'log4js';
import config from '../config';
configure(config.log);
export default getLogger();
- 创建日志记录中间件 src/middlewares/logMiddleWare.ts
统计请求耗时
代码语言:javascript复制import type { Context, Next } from 'koa';
import logger from '../utils/logger';
const logMiddleWare = () => {
return async (ctx: Context, next: Next) => {
const start = new Date();
await next();
const ms = new Date().getTime() - start.getTime();
logger.info(`${ctx.method} ${ctx.url} - ${ms}ms`);
};
};
export default logMiddleWare;
- 注册中间件 src/app.ts
import logMiddleWare from './middlewares/logMiddleWare';
app.use(logMiddleWare());
文件上传
koa-body 配置文件上传
代码语言:javascript复制// src/index.ts
KoaBody({
// 启用表单解析,可以支持文件上传
multipart: true,
formidable: {
// 文件上传路径
uploadDir: './uploads',
// 保持文件的扩展名
keepExtensions: true,
// 文件上传大小限制,默认5M
maxFieldsSize: 5 * 1024 * 1024,
// 保持文件的扩展名
onFileBegin: (name, file) => {
// 文件上传前的设置
// console.log(name, file);
},
},
})
文件上传接口 src/controller/common/view.ts
代码语言:javascript复制import { Context } from 'koa';
import type { Files, File as FileType } from 'formidable';
class IndexController {
......
async upload(ctx: Context) {
const files: Files | undefined = ctx.request.files;
if (files) {
const data: { url: string; name: string; size: number }[] = [];
for (const key in files) {
const file: FileType = files[key] as FileType;
data.push({
url: file.path,
name: file.name!,
size: file.size,
});
}
response.success(ctx, data, '上传成功');
} else {
response.error(ctx, '上传失败');
}
}
}
配置路由
代码语言:javascript复制// src/controller/common/view.ts
import IndexController from '../controller/common/view';
router.post('/upload', IndexController.upload);