使用Python实现思路
- 选择框架:可以使用Flask框架来处理HTTP请求,因为它轻量级且易于使用。
- 捕获请求信息:在Flask的请求钩子中获取请求时间、请求方法和请求路径。
- 记录日志:使用Python内置的
logging
模块将这些信息写入日志文件。
关键代码片段
from flask import Flask, request
import logging
app = Flask(__name__)
# 配置日志
logging.basicConfig(filename='couchdb_requests.log', level=logging.INFO,
format='%(asctime)s - %(method)s - %(path)s',
datefmt='%Y-%m-%d %H:%M:%S')
@app.before_request
def log_request_info():
request.environ['start_time'] = datetime.now()
method = request.method
path = request.path
logging.info(f"{method} - {path}")
# 假设这里有处理CouchDB请求的路由,例如
@app.route('/couchdb/api', methods=['GET', 'POST'])
def couchdb_api():
# 这里处理具体的CouchDB业务逻辑
return "CouchDB API response"
if __name__ == '__main__':
app.run(debug=True)
使用Node.js实现思路
- 选择框架:Express框架是Node.js中常用的处理HTTP请求的框架。
- 捕获请求信息:利用Express的中间件来获取请求时间、请求方法和请求路径。
- 记录日志:使用
fs
模块将信息写入日志文件。
关键代码片段
const express = require('express');
const fs = require('fs');
const app = express();
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
const method = req.method;
const path = req.path;
const logMessage = `${timestamp} - ${method} - ${path}\n`;
fs.appendFile('couchdb_requests.log', logMessage, (err) => {
if (err) {
console.error('Error writing to log file:', err);
}
});
next();
});
// 假设这里有处理CouchDB请求的路由,例如
app.get('/couchdb/api', (req, res) => {
// 这里处理具体的CouchDB业务逻辑
res.send('CouchDB API response');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});