|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const { ConsoleSpanExporter } = require('@opentelemetry/sdk-trace-base'); |
| 6 | +const { ExportResultCode } = require('@opentelemetry/core'); |
| 7 | + |
| 8 | +// We extend ConsoleSpanExporter as the logic is almost the same, we just need to write to a file instead of log to console |
| 9 | +class FileSpanExporter extends ConsoleSpanExporter { |
| 10 | + constructor(opts) { |
| 11 | + super(); |
| 12 | + this.filePath = this.setOutputPath(opts.output); |
| 13 | + |
| 14 | + // We create the file in the main thread and then append to it in the worker threads |
| 15 | + if (typeof process.env.LOCAL_WORKER_ID === 'undefined') { |
| 16 | + // We write the '[' here to open an array in the file, so we can append spans to it |
| 17 | + fs.writeFileSync(this.filePath, '[\n', { flag: 'w' }); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + _sendSpans(spans, done) { |
| 22 | + const spansToExport = spans.map((span) => |
| 23 | + JSON.stringify(this._exportInfo(span)) |
| 24 | + ); |
| 25 | + if (spansToExport.length > 0) { |
| 26 | + fs.writeFileSync(this.filePath, spansToExport.join(',\n') + ',', { |
| 27 | + flag: 'a' |
| 28 | + }); // TODO fix trailing coma |
| 29 | + } |
| 30 | + if (done) { |
| 31 | + return done({ code: ExportResultCode.SUCCESS }); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + shutdown() { |
| 36 | + this._sendSpans([]); |
| 37 | + this.forceFlush(); |
| 38 | + if (typeof process.env.LOCAL_WORKER_ID === 'undefined') { |
| 39 | + try { |
| 40 | + // Removing the trailing comma and closing the array |
| 41 | + const data = |
| 42 | + fs.readFileSync(this.filePath, 'utf8').slice(0, -1) + '\n]'; |
| 43 | + fs.writeFileSync(this.filePath, data, { flag: 'w' }); |
| 44 | + console.log('File updated successfully.'); |
| 45 | + } catch (err) { |
| 46 | + console.error('FileSpanExporter: Error updating file:'); |
| 47 | + throw err; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + setOutputPath(output) { |
| 53 | + const defaultFileName = `otel-spans-${global.artillery.testRunId}.json`; |
| 54 | + const defaultOutputPath = path.resolve(process.cwd(), defaultFileName); |
| 55 | + if (!output) { |
| 56 | + return defaultOutputPath; |
| 57 | + } |
| 58 | + |
| 59 | + const isFile = path.extname(output); |
| 60 | + const exists = isFile |
| 61 | + ? fs.existsSync(path.dirname(output)) |
| 62 | + : fs.existsSync(output); |
| 63 | + |
| 64 | + if (!exists) { |
| 65 | + throw new Error(`FileSpanExporter: Path '${output}' does not exist`); |
| 66 | + } |
| 67 | + return isFile ? output : path.resolve(output, defaultFileName); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +module.exports = { |
| 72 | + FileSpanExporter |
| 73 | +}; |
0 commit comments