如何使用express winston记录客户端IP地址



我使用express winston作为express的中间件来记录所有请求及其响应代码。这是我的代码

const myFormat = printf(info => {
console.log(info)
return `${info.timestamp} ${info.level}: ${info.message}`
})

app.use(expressWinston.logger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: "access.log", level: "info" })
],
format: winston.format.combine(
winston.format.timestamp(),
myFormat
),
meta: true,
expressFormat: true, 
}));
app.set('trust proxy', true)
app.use(cors());

myFormat中的info变量不包含用户IPadress.req.headers['x-forwarded-for']req.connection.remoteAddress在那里都不可访问。在myFormat函数中构建日志时,如何获取地址?

您可以按照下面的示例构建动态元。这将导致info.httpRequest上的属性可用,您可以根据需要格式化info.httpRequest.remoteIp

示例:

class myFormat extends Transport {
constructor(opts) {
super(opts);
}
log(info, callback) {
setImmediate(() => {
this.emit('logged', info);
});
callback();
}
};
app.use(expressWinston.logger({
transports: [
new winston.transports.Console(),
new myFormat()
],
metaField: null, //this causes the metadata to be stored at the root of the log entry
responseField: null, // this prevents the response from being included in the metadata (including body and status code)
requestWhitelist: ['headers', 'query'],  //these are not included in the standard StackDriver httpRequest
responseWhitelist: ['body'], // this populates the `res.body` so we can get the response size (not required)
dynamicMeta: (req, res) => {
const httpRequest = {}
const meta = {}
if (req) {
meta.httpRequest = httpRequest
httpRequest.requestMethod = req.method
httpRequest.requestUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`
httpRequest.protocol = `HTTP/${req.httpVersion}`
// httpRequest.remoteIp = req.ip // this includes both ipv6 and ipv4 addresses separated by ':'
httpRequest.remoteIp = req.ip.indexOf(':') >= 0 ? req.ip.substring(req.ip.lastIndexOf(':') + 1) : req.ip   // just ipv4
httpRequest.requestSize = req.socket.bytesRead
httpRequest.userAgent = req.get('User-Agent')
httpRequest.referrer = req.get('Referrer')
}
return meta
}
}));

文档上元字段下的更多信息。

最新更新