Skip to content

Instantly share code, notes, and snippets.

@dominicbartl
Last active January 26, 2022 13:33
Show Gist options
  • Save dominicbartl/0ea4e13528bb50b7b0a809b72b4b3a17 to your computer and use it in GitHub Desktop.
Save dominicbartl/0ea4e13528bb50b7b0a809b72b4b3a17 to your computer and use it in GitHub Desktop.
Express middleware to log HTTP requests on Firebase functions
import { NextFunction, Request, Response } from 'express';
import { LogEntry, LogSeverity, write } from 'firebase-functions/lib/logger';
export function functionRequestLogger(req: Request, res: Response, next: NextFunction) {
const start = Date.now();
res.on('finish', () => {
const code = res.statusCode;
const logEntry: LogEntry = {
severity: getSeverity(code),
httpRequest: {
requestMethod: req.method,
status: code,
requestUrl: req.url,
remoteIp: req.ip,
referer: req.get('Referrer'),
userAgent: req.get('User-Agent'),
latency: latency(start)
},
};
write(logEntry);
});
next();
}
function latency(startMs: number) {
const diff = Date.now() - startMs;
const seconds = Math.floor(diff / 1000);
const remainingMs = diff - seconds * 1000;
return {
seconds: seconds,
nanos: remainingMs * 1000000
};
}
function getSeverity(code: number): LogSeverity {
if (code >= 100 && code < 400) {
return 'INFO';
} else if (code >= 500) {
return 'CRITICAL';
} else if ([400, 401, 404].includes(code)) {
return 'WARNING';
}
return 'ERROR';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment