Files
doneit-web/src/app/services/monitoring/opentelemetry/tracer.ts
T

293 lines
8.1 KiB
TypeScript
Raw Normal View History

2024-07-11 12:12:43 +01:00
import { v4 as uuidv4 } from 'uuid';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { Tracer, Span } from '@opentelemetry/sdk-trace-base';
2024-08-20 16:34:47 +01:00
import { OpentelemetryAgendaProvider, OpentelemetryChatProvider, OpentelemetryInterceptorProvider, OpentelemetryLogging, OpentelemetryNotificationProvider } from './opentelemetry';
2024-07-11 12:12:43 +01:00
import { Device, DeviceInfo } from '@capacitor/device';
import { SessionStore } from 'src/app/store/session.service';
import { environment } from 'src/environments/environment';
import { UseCaseCounter } from './matrix';
2024-07-22 13:28:52 +01:00
import { openTelemetryLogging } from './logging';
2024-07-25 08:51:04 +01:00
import {
SpanStatus, SpanStatusCode
} from '@opentelemetry/api';
2024-07-11 12:12:43 +01:00
const tracerInstance = OpentelemetryAgendaProvider.getTracer('example-tracer-hole', '111', {})
const tracerNotificationInstance = OpentelemetryNotificationProvider.getTracer('example-tracer-hole', '111', {})
2024-08-20 16:34:47 +01:00
const tracerChat = OpentelemetryChatProvider.getTracer('OpentelemetryChatProvider','some' ,{})
2024-07-11 12:12:43 +01:00
let device: DeviceInfo;
Device.getInfo().then(e => {
device = e
});
2024-07-22 13:28:52 +01:00
function convertAttributesToString(obj) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
// Convert only the object attribute to string
result[key] = JSON.stringify(obj[key], null, 2);
} else {
// Convert primitive values to string
2024-08-06 11:24:00 +01:00
result[key] = obj[key];
2024-07-22 13:28:52 +01:00
}
}
}
return result;
}
2024-07-11 12:12:43 +01:00
const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingType => {
const requestId = uuidv4()
let _tracerInstance:Tracer
if(module == 'notification') {
_tracerInstance = tracerNotificationInstance
2024-08-20 16:34:47 +01:00
} else if (module == 'chat') {
_tracerInstance = tracerChat
2024-07-11 12:12:43 +01:00
} else {
_tracerInstance = tracerInstance
}
const span = _tracerInstance.startSpan(name);
2024-08-06 11:24:00 +01:00
let finish = false
2024-07-11 12:12:43 +01:00
const data = {
event: {},
2024-07-25 08:51:04 +01:00
tags: {},
status: {} as any,
2024-08-08 15:53:00 +01:00
logs:[],
errors: []
2024-07-11 12:12:43 +01:00
}
2024-07-25 08:51:04 +01:00
const returnObject = {
2024-08-08 15:53:00 +01:00
name,
2024-07-11 12:12:43 +01:00
span: span as any,
tracer: tracerInstance,
tracerId: requestId,
attributes: SemanticAttributes,
2024-07-25 08:51:04 +01:00
setStatus: (status: SpanStatus) => {
2024-07-11 12:12:43 +01:00
span.setStatus(status);
},
2024-08-08 15:53:00 +01:00
addEvent: (context: string, message: string = "") => {
2024-07-11 12:12:43 +01:00
data.event[context] = message;
2024-08-08 15:53:00 +01:00
span.addEvent(context, message as any);
2024-07-11 12:12:43 +01:00
},
LocalLogEvent:(context: string, message: any, obj: any) => {
data.tags[context] = message;
},
setAttribute: (key: string, value: string) => {
data.tags[key] = value;
span.setAttribute(key, value);
2024-07-16 14:15:58 +01:00
if(key =='outcome' && value == 'failed') {
2024-08-08 15:53:00 +01:00
if(data.errors.length == 0) {
returnObject.hasError('error')
}
2024-08-06 11:24:00 +01:00
if(!autoFinish) {
returnObject.finish()
}
} else if (key =='outcome' && value == 'success') {
span.setStatus({code: SpanStatusCode.OK, message:name})
if(!autoFinish) {
returnObject.finish()
}
2024-07-16 14:15:58 +01:00
}
2024-07-11 12:12:43 +01:00
},
2024-08-06 11:24:00 +01:00
log(message: string, dataObject: Object) {
2024-07-22 13:28:52 +01:00
const spanId = span.spanContext().spanId;
const _tracer = OpentelemetryLogging.getTracer('logging')
const spanContext = _tracer.startSpan(name)
2024-08-06 11:24:00 +01:00
dataObject = convertAttributesToString(dataObject)
2024-07-26 15:33:03 +01:00
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
openTelemetryLogging.send({
type: 'graylog',
spanContext,
payload: {
message: message,
object: {
2024-08-06 11:24:00 +01:00
...dataObject,
2024-07-26 15:33:03 +01:00
spanId,
name,
user: SessionStore?.user?.FullName,
device_name: device?.name || device?.model,
commit_date: environment.version.lastCommitTime,
}
2024-07-22 13:28:52 +01:00
}
2024-07-26 15:33:03 +01:00
})
}
2024-08-06 11:24:00 +01:00
data.logs.push(dataObject)
2024-07-22 13:28:52 +01:00
},
2024-07-11 12:12:43 +01:00
getAttribute: (key: string) => {
return data.tags[key]
},
finish: () => {
2024-08-06 11:24:00 +01:00
if(finish) return
2024-07-11 12:12:43 +01:00
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
2024-08-08 15:53:00 +01:00
span.setAttribute('error.list', data.errors.join(','))
2024-07-11 12:12:43 +01:00
span.end();
2024-07-25 08:51:04 +01:00
UseCaseCounter.add(1, {user: SessionStore?.user?.FullName, outcome:data.tags['outcome'] || data.status?.code , usecase: name})
2024-07-11 12:12:43 +01:00
}
2024-07-25 08:51:04 +01:00
if(bugPrint && (data.tags['outcome'] == 'failed' || data.status?.code == SpanStatusCode.ERROR)) {
2024-07-11 12:12:43 +01:00
console.error(name, data)
}
2024-08-06 11:24:00 +01:00
finish = true
2024-07-11 12:12:43 +01:00
},
2024-07-25 08:51:04 +01:00
hasError:(message: string) => {
2024-08-08 15:53:00 +01:00
data.errors.push(message)
data.status = {code: SpanStatusCode.ERROR, message}
span.setStatus({code: SpanStatusCode.ERROR, message})
2024-07-25 08:51:04 +01:00
},
2024-07-11 12:12:43 +01:00
createSpan: (name, parent?: any) => {
return tracerInstance.startSpan(name, { root: false }, parent) as Span;
}
}
2024-07-25 08:51:04 +01:00
return returnObject
2024-07-11 12:12:43 +01:00
}
export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true, daley =0 }) {
return (
target: unknown,
propertyKey: string,
descriptor: PropertyDescriptor,
) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: unknown[]) {
const tracing = createTracingInstance({bugPrint, name, module, autoFinish})
tracing.setAttribute('User', SessionStore?.user?.FullName);
tracing.setAttribute('current.page', window.location.pathname);
tracing.setAttribute('device.name', device?.name || device?.model)
tracing.setAttribute('commit.date', environment.version.lastCommitTime)
tracing.setAttribute('commit.branch', environment.version.branch)
args.push(tracing)
try {
const result = await originalMethod.apply(this, args);
if(autoFinish ) {
setTimeout(tracing.finish , daley)
}
return result
} catch (e) {
tracing.setAttribute('catch', 'true')
2024-08-20 16:34:47 +01:00
tracing.log("cath", {
error: e
})
2024-07-11 12:12:43 +01:00
if(autoFinish) {
setTimeout(tracing.finish , daley)
}
console.error(e);
return false
}
};
};
}
export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0 }) {
return (
target: unknown,
propertyKey: string,
descriptor: PropertyDescriptor,
) => {
const originalMethod = descriptor.value;
descriptor.value = function (...args: unknown[]) {
const tracing = createTracingInstance({bugPrint, name, module, autoFinish})
tracing.setAttribute('User', SessionStore?.user?.FullName);
tracing.setAttribute('current.page', window.location.pathname);
tracing.setAttribute('device.name', device?.name || device?.model)
tracing.setAttribute('commit.date', environment.version.lastCommitTime)
tracing.setAttribute('commit.branch', environment.version.branch)
args.push(tracing)
try {
const result = originalMethod.apply(this, args);
if(autoFinish) {
setTimeout(tracing.finish , daley)
}
return result
} catch (e) {
tracing.setAttribute('catch', 'true')
2024-08-20 16:34:47 +01:00
tracing.log("cath", {
error: e
})
2024-07-11 12:12:43 +01:00
if(autoFinish) {
setTimeout(tracing.finish , daley)
}
console.error(e);
return false
}
};
};
}
export type TracingType = {
2024-08-08 15:53:00 +01:00
name: string,
2024-07-11 12:12:43 +01:00
span: Span;
tracer: Tracer;
tracerId: string;
attributes: typeof SemanticAttributes;
// axios: (config?: AxiosRequestConfig) => AxiosInstance;
setStatus: (status: any) => void;
2024-07-22 13:28:52 +01:00
log: (message: string, data: Object) => void;
2024-07-11 12:12:43 +01:00
addEvent: (context: string, message?: any, obj?: any) => void;
setAttribute: (key: string, value: string) => void;
getAttribute: (key: string) => string;
LocalLogEvent: (name: string, attributesOrStartTime: any, obj?:any) => void;
finish: () => void;
2024-07-25 08:51:04 +01:00
hasError:(message: string) => void;
2024-07-11 12:12:43 +01:00
createSpan:(name, parent?: any) => Span;
};
export interface UserInteraction {
readonly params: any;
readonly tracing: TracingType;
readonly user: Pick<any, 'login'>;
readonly headers: Headers & { authorization: string };
}
export type InteractionTrancingInput = Pick<UserInteraction, 'user' | 'tracing'>;
export const getPathWithoutUUID = (path: string) =>
path.replace(
/[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
'uuid',
);