|
| 1 | +import { trace } from '@opentelemetry/api'; |
| 2 | +import { Request, Response, NextFunction, RequestHandler } from 'express'; |
| 3 | +import { get } from 'lodash'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Middleware factory that creates a tracing span with optional dot-notated paths. |
| 7 | + * |
| 8 | + * @param transaction_id_path - Dot path to transaction_id in req.body (default: 'context.transaction_id') |
| 9 | + * @param session_id - Dot path to transaction_id in req.body (default: 'context.transaction_id') |
| 10 | + * @param bap_id_path - Dot path to bap_id in req.body (default: 'context.bap_id') |
| 11 | + * @param bpp_id_path - Dot path to bpp_id in req.body (default: 'context.bpp_id') |
| 12 | + * @returns Express middleware |
| 13 | + */ |
| 14 | +export function otelTracing( |
| 15 | + transaction_id_path: string = 'transaction_id', |
| 16 | + session_id_path: string = 'session_id', |
| 17 | + bap_id_path: string = 'context.bap_id', |
| 18 | + bpp_id_path: string = 'context.bpp_id' |
| 19 | +): RequestHandler { |
| 20 | + return (req: Request, res: Response, next: NextFunction) => { |
| 21 | + const transaction_id: string | undefined = get(req, transaction_id_path); |
| 22 | + const session_id: string | undefined = get(req, session_id_path); |
| 23 | + const bap_id: string | undefined = get(req, bap_id_path); |
| 24 | + const bpp_id: string | undefined = get(req, bpp_id_path); |
| 25 | + |
| 26 | + const tracer = trace.getTracer(process.env.SERVICE_NAME || 'default-service'); |
| 27 | + |
| 28 | + const span = tracer.startSpan("trace_span", { |
| 29 | + attributes: { |
| 30 | + 'transaction_id': transaction_id || '', |
| 31 | + 'session_id': session_id || '', |
| 32 | + 'bap_id': bap_id || '', |
| 33 | + 'bpp_id': bpp_id || '', |
| 34 | + } |
| 35 | + }); |
| 36 | + |
| 37 | + span.end(); |
| 38 | + |
| 39 | + next(); |
| 40 | + |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +export default otelTracing; |
0 commit comments