//elastic-apm-js-core 的ServiceFactory提供的TransactionService是返回的单例模式 //暂时只能从源代码库中拉取原始Transaction import Transaction from 'elastic-apm-js-core/src/performance-monitoring/transaction' import { UserContext } from '../instance/type' import * as Tools from "../tool"; class TracerTransaction { private serviceFactory: any; //part private customInitialized = false; private customServiceFactory:any private customPerformanceMonitoring: any; private customApmServer: any constructor(serviceFactory,newServiceFactory) { this.serviceFactory = serviceFactory this.customServiceFactory = newServiceFactory } public createTransaction = (name: string, type: string) => { var transactionService = this.serviceFactory.getService( "TransactionService" ); return transactionService.startTransaction(name, type); }; // custom transcation public initCustomTransaction = (config) =>{ //part server init config const { agentName,version, transactionDurationThreshold } = config var ConfigService= this.customServiceFactory.getService("ConfigService"); ConfigService.setConfig(config); this.customServiceFactory.init(); //create server this.customPerformanceMonitoring = this.customServiceFactory.getService("PerformanceMonitoring"); this.customPerformanceMonitoring.init(); this.customPerformanceMonitoring.cancelPatchSub(); this.customApmServer = this.customServiceFactory.getService('ApmServer') this.customInitialized = true } public setCustomTransactionUserInfo = (userInfo:UserContext) => { var configService = this.customServiceFactory.getService("ConfigService"); configService.setUserContext(userInfo); } public createCustomEventTransaction = (name:string,type:string,options?:any) => { var self = this if(!self.customInitialized){ return false; } var _option = Tools.extend({ transactionSampleRate:1 },options) var transaction = new Transaction(name,type,_option) //添加onEnd事件 Object.defineProperty(transaction,'onEnd',{ enumerable: false, configurable: false, writable: false, value:function(){ if(this instanceof Transaction ){ self.customPerformanceMonitoring.prepareTransaction(this) let payload = self.customPerformanceMonitoring.createTransactionDataModel(this) self.customApmServer.addTransaction(payload) } } }) return transaction } } export default TracerTransaction;