Skip to content

Commit 426b2fc

Browse files
committed
added logger and runtime features, improvements and code cleanup
1 parent da60dc2 commit 426b2fc

15 files changed

Lines changed: 165 additions & 121 deletions

File tree

index.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1 @@
1-
import { Middleware, catchException } from "./lib/node/middlewares";
2-
import * as Traceo from "./lib/node/sdk";
3-
4-
export { Middleware, Traceo, catchException };
1+
export * from "./lib/node";

lib/core/http.ts

Lines changed: 31 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,25 @@
11
import * as http from "http";
2-
import { sanitizeDsn } from "../node/helpers";
32
import { EventResponse, Incident } from "../transport/events";
4-
import { TraceoIncomingMessage, RequestOptions } from "../transport/http";
3+
import { TraceoIncomingMessage, RequestOptions, HTTP_ENDPOINT, RequestStatus } from "../transport/http";
4+
import { TraceoLog } from "../transport/logger";
5+
import { RequestType } from "../transport/types";
56
import { getGlobalClientData } from "./global";
6-
import { isClientConnected } from "./is";
77
import { TRACEO_SDK_VERSION } from "./version";
88

9-
enum RequestStatus {
10-
SUCCESS = "success",
11-
ERROR = "error",
12-
}
13-
14-
const createHttpOptions = (path: string): http.RequestOptions => {
9+
const createHttpOptions = (
10+
path: string,
11+
method: RequestType = "POST"
12+
): http.RequestOptions => {
1513
const client = getGlobalClientData();
1614

17-
const { dsn } = client;
18-
const { host, secretKey } = sanitizeDsn(dsn);
15+
const { host, port } = client;
1916

2017
const baseOptions: RequestOptions = {
2118
hostname: host,
22-
method: "POST",
19+
port,
20+
method,
2321
headers: {
2422
"Content-Type": "application/json",
25-
"Traceo-Secret-Key": secretKey,
2623
},
2724
};
2825

@@ -32,84 +29,44 @@ const createHttpOptions = (path: string): http.RequestOptions => {
3229
};
3330
};
3431

35-
const statusFromCode = (code: number) =>
36-
code >= 200 && code <= 299 ? RequestStatus.SUCCESS : RequestStatus.ERROR;
37-
38-
export const sendRuntimeMetrics = async (data: {}) => {
39-
const { appId, environment } = getGlobalClientData();
40-
41-
if (!appId) {
42-
return;
43-
}
32+
const sendLog = async (log: TraceoLog) => {
33+
const httpOptions = createHttpOptions(HTTP_ENDPOINT.LOG);
34+
await sendEvent(log, httpOptions);
35+
};
4436

45-
const httpOptions = createHttpOptions(
46-
`/${appId}/${environment}/metrics/runtime`
47-
);
37+
const sendRuntimeMetrics = async (data: {}) => {
38+
const httpOptions = createHttpOptions(HTTP_ENDPOINT.RUNTIME);
4839
await sendEvent(data, httpOptions);
4940
};
5041

51-
export const sendIncidentEvent = async (incident: Incident) => {
52-
const { environment, appId } = getGlobalClientData();
53-
54-
if (!environment || !appId) {
55-
return;
56-
}
57-
42+
const sendIncident = async (incident: Incident) => {
5843
const version = TRACEO_SDK_VERSION;
59-
const baseData = { version, env: environment };
44+
const baseData = { version };
6045

6146
const payload = Object.assign(incident, baseData);
6247

63-
const httpOptions = createHttpOptions(`/${appId}`);
48+
const httpOptions = createHttpOptions(HTTP_ENDPOINT.INCIDENT);
6449
await sendEvent(payload, httpOptions);
6550
};
6651

67-
export const sendEvent = async (
52+
const sendEvent = async (
6853
payload: any,
6954
httpOptions: http.RequestOptions
7055
): Promise<EventResponse | void> => {
71-
const { environment, dsn } = getGlobalClientData();
56+
const { host, appId } = getGlobalClientData();
7257

73-
if (!environment || !dsn) {
58+
if (!host || !appId) {
7459
return;
7560
}
7661

77-
return new Promise<EventResponse>((resolve, reject) => {
78-
// const httpOptions = createHttpOptions({ payload });
79-
if (!httpOptions) {
80-
reject({
81-
statusCode: 400,
82-
statusMessage:
83-
"[Traceo] Error during sending event to Traceo. No HTTP options.",
84-
});
62+
return new Promise<EventResponse>((_, reject) => {
63+
const options = {
64+
...httpOptions,
65+
path: httpOptions.path + `/${appId}`
8566
}
8667

87-
if (!isClientConnected()) {
88-
reject({
89-
statusCode: 400,
90-
statusMessage:
91-
"[Traceo] Error during sending event to Traceo. No client global data in NodeJS scope.",
92-
});
93-
}
94-
95-
const request = http.request(httpOptions, (res: TraceoIncomingMessage) => {
68+
const request = http.request(options, (res: TraceoIncomingMessage) => {
9669
res.setEncoding("utf8");
97-
98-
const status = statusFromCode(res?.statusCode as number);
99-
const isSuccess = status === RequestStatus.SUCCESS;
100-
101-
if (!isSuccess) {
102-
reject({
103-
statusCode: res?.statusCode as number,
104-
statusMessage: "[Traceo] Error during sending event to Traceo.",
105-
});
106-
} else {
107-
resolve({
108-
statusCode: res?.statusCode as number,
109-
statusMessage: "[Traceo] Event successfully sended to Traceo.",
110-
});
111-
}
112-
11370
res.on("error", reject);
11471
});
11572

@@ -128,3 +85,7 @@ export const sendEvent = async (
12885
request.end();
12986
});
13087
};
88+
89+
export const httpService = {
90+
sendLog, sendIncident, sendRuntimeMetrics
91+
}

lib/core/is.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,5 @@
11
import { getGlobalClientData } from "./global";
22

3-
export const isInternal = (fileName: string): boolean =>
4-
!!fileName &&
5-
!fileName.includes("node_modules") &&
6-
!fileName.startsWith("/") &&
7-
!fileName.startsWith("node:") &&
8-
fileName.includes(":\\");
9-
103
export const isEmpty = (obj?: any): boolean => Object.keys(obj).length === 0;
114

125
export const isLocalhost = (ip: string): boolean => {

lib/node/helpers.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ export const getOsPlatform = (): Platform => {
2121
};
2222
};
2323

24-
export const sanitizeDsn = (dsn: string) => {
25-
const [secretKey, rest] = dsn
26-
.replace("http://", "")
27-
.replace("https://", "")
28-
.split(":");
29-
const [host, appId] = rest.split("/");
24+
// export const sanitizeDsn = (dsn: string) => {
25+
// const [secretKey, rest] = dsn
26+
// .replace("http://", "")
27+
// .replace("https://", "")
28+
// .split(":");
29+
// const [host, appId] = rest.split("/");
3030

31-
return {
32-
secretKey,
33-
host,
34-
appId,
35-
};
36-
};
31+
// return {
32+
// secretKey,
33+
// host,
34+
// appId,
35+
// };
36+
// };

lib/node/index.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { Middleware } from "./middlewares";
2-
import * as Traceo from "./sdk";
3-
4-
export { Middleware, Traceo };
1+
export { Middleware, catchException } from "./middlewares";
2+
export { logger } from "./logger";
3+
export * as Traceo from "./sdk";

lib/node/logger.ts

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { format } from "util";
2+
import { httpService } from "../core/http";
3+
import { LogLevel } from "../transport/logger";
4+
5+
const getTimestamp = () => {
6+
const localeStringOptions = {
7+
year: "numeric",
8+
hour: "numeric",
9+
minute: "numeric",
10+
second: "numeric",
11+
day: "2-digit",
12+
month: "2-digit",
13+
};
14+
return new Date(Date.now()).toLocaleString(
15+
undefined,
16+
localeStringOptions as Intl.DateTimeFormatOptions
17+
);
18+
};
19+
20+
const printMessage = ({ message }: { message: string }, level: LogLevel) => {
21+
const timestamp = getTimestamp();
22+
const messagePayload = `[TraceoLogger][${level.toUpperCase()}] - ${timestamp} - ${message}`;
23+
24+
if (level === LogLevel.Error) {
25+
console[level](`\x1B[31m${messagePayload}\x1B[39m`);
26+
} else {
27+
console[level](messagePayload);
28+
}
29+
30+
httpService.sendLog({
31+
level,
32+
message,
33+
timestamp,
34+
unix: Math.floor(Date.now() / 1000),
35+
resources: logResources(),
36+
});
37+
};
38+
39+
const logResources = () => {
40+
return {
41+
nodeVersion: process.env["npm_package_engines_node"],
42+
packageName: process.env["npm_package_name"],
43+
packageVersion: process.env["npm_package_version"],
44+
traceoVersion:
45+
process.env["npm_package_dependencies_traceo"] ||
46+
process.env["npm_package_devDependencies_traceo"],
47+
};
48+
};
49+
50+
const debug = (...args: any[]) =>
51+
printMessage(getEntryFromArgs(args), LogLevel.Debug);
52+
const log = (...args: any[]) =>
53+
printMessage(getEntryFromArgs(args), LogLevel.Log);
54+
const info = (...args: any[]) =>
55+
printMessage(getEntryFromArgs(args), LogLevel.Info);
56+
const warn = (...args: any[]) =>
57+
printMessage(getEntryFromArgs(args), LogLevel.Warn);
58+
const error = (...args: any[]) =>
59+
printMessage(getEntryFromArgs(args), LogLevel.Error);
60+
61+
const getEntryFromArgs = (args: any[]): { message: string } =>
62+
Object.assign(
63+
{},
64+
{
65+
message: format.apply(null, args),
66+
}
67+
);
68+
69+
export const logger = {
70+
debug,
71+
log,
72+
info,
73+
warn,
74+
error,
75+
};

lib/node/metrics.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as os from "os";
22
import * as v8 from "v8";
3-
import { sendRuntimeMetrics } from "../core/http";
3+
import { httpService } from "../core/http";
44

55
const sanitizePackageName = (pkg: string, pkgType: string) => {
66
let targetKey = pkg.replace(pkgType, "").replace("__", "@");
@@ -97,7 +97,7 @@ const collectMetricsDataOnRuntime = () => {
9797
},
9898
};
9999

100-
sendRuntimeMetrics(data);
100+
httpService.sendRuntimeMetrics(data);
101101
};
102102

103103
export const metrics = {

lib/node/middlewares.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { stacktrace } from "stacktrace-parser-node";
2-
import { sendEvent, sendIncidentEvent } from "../core/http";
2+
import { httpService } from "../core/http";
33
import { isClientConnected, isLocalhost } from "../core/is";
44
import { TraceoError } from "../transport/base";
55
import { Incident } from "../transport/events";
@@ -114,7 +114,7 @@ export const catchException = async (error: any, catchOptions?: Catch) => {
114114
const handleException = async (error: TraceoError) => {
115115
try {
116116
const event: Incident = await prepareException(error);
117-
await sendIncidentEvent(event);
117+
await httpService.sendIncident(event);
118118
} catch (err) {
119119
//
120120
}

lib/node/sdk.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,15 @@ export const init = (options: TraceoOptions): void => {
1616
return;
1717
}
1818

19-
if (!options.environment) {
20-
console.warn(
21-
"Traceo SDK: Empty environment property. Please set current env or use offline mode."
22-
);
23-
return;
24-
}
25-
2619
if (!isClientConnected()) {
2720
setGlobalClientData({
2821
...options,
2922
});
3023
}
3124

32-
metrics.collectMetricsDataOnRuntime();
25+
if (options?.collectMetrics) {
26+
metrics.collectMetricsDataOnRuntime();
27+
}
3328
};
3429

3530
export const collectMetricsData = () => {};

lib/transport/base.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import { Environment } from "./types";
2-
31
export interface TraceoGlobal {
4-
dsn?: string;
2+
host?: string;
3+
port?: number;
54
appId?: number;
6-
environment?: Environment;
75
}
86

97
export interface TraceoError extends Error {}

0 commit comments

Comments
 (0)