adicionado integração com loki

This commit is contained in:
Luiz Silva 2025-02-21 14:37:06 -03:00
parent 745c04819b
commit 3c8aa13a5e
14 changed files with 202 additions and 7 deletions

1
dist/index.d.ts vendored
View file

@ -8,3 +8,4 @@ export * from "./ecosistema";
export * from "./variaveisComuns"; export * from "./variaveisComuns";
export * from "./tipagemRotas"; export * from "./tipagemRotas";
export * from "./extensoes"; export * from "./extensoes";
export * from "./logger";

1
dist/index.js vendored
View file

@ -24,4 +24,5 @@ __exportStar(require("./ecosistema"), exports);
__exportStar(require("./variaveisComuns"), exports); __exportStar(require("./variaveisComuns"), exports);
__exportStar(require("./tipagemRotas"), exports); __exportStar(require("./tipagemRotas"), exports);
__exportStar(require("./extensoes"), exports); __exportStar(require("./extensoes"), exports);
__exportStar(require("./logger"), exports);
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

2
dist/index.js.map vendored
View file

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA4B;AAC5B,6CAA0B;AAC1B,8CAA2B;AAC3B,gDAA6B;AAC7B,oDAAiC;AACjC,yCAAsB;AACtB,+CAA4B;AAC5B,oDAAiC;AACjC,iDAA8B;AAC9B,8CAA2B"} {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA4B;AAC5B,6CAA0B;AAC1B,8CAA2B;AAC3B,gDAA6B;AAC7B,oDAAiC;AACjC,yCAAsB;AACtB,+CAA4B;AAC5B,oDAAiC;AACjC,iDAA8B;AAC9B,8CAA2B;AAC3B,2CAAwB"}

15
dist/logger.d.ts vendored Normal file
View file

@ -0,0 +1,15 @@
interface LogOptions {
app?: string;
conta?: string;
usuario?: string;
detalhes?: unknown[];
}
export declare const logger: {
/** 🟢 Informação geral */
info: (message: string, options?: LogOptions) => Promise<void>;
/** 🟡 Aviso/atenção necessária */
warn: (message: string, options?: LogOptions) => Promise<void>;
/** 🔴 Erro crítico na execução */
error: (message: string, options?: LogOptions) => Promise<void>;
};
export {};

51
dist/logger.js vendored Normal file
View file

@ -0,0 +1,51 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const LOKI_BASE_URL = "https://log.idz.one";
const LOKI_ENDPOINT = "/loki/api/v1/push";
const createLogger = (level) => {
const sendToLoki = async (message, options = {}) => {
const { app, conta, usuario, detalhes = [] } = options;
const timestamp = `${Date.now()}000000`;
try {
// Formata a linha de log principal
const mainLog = detalhes.length > 0
? `${message} | ${detalhes.map((d) => JSON.stringify(d)).join(" ")}`
: message;
const payload = {
stream: { app, conta, usuario, level },
values: [
[
timestamp,
mainLog, // Linha de log direta
],
],
};
const response = await (0, cross_fetch_1.default)(`${LOKI_BASE_URL}${LOKI_ENDPOINT}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ streams: [payload] }),
});
if (!response.ok) {
throw new Error(`Erro ${response.status}: ${await response.text()}`);
}
}
catch (error) {
console.error("[Logger] Falha no envio:", error);
}
};
return sendToLoki;
};
exports.logger = {
/** 🟢 Informação geral */
info: createLogger("info"),
/** 🟡 Aviso/atenção necessária */
warn: createLogger("warn"),
/** 🔴 Erro crítico na execução */
error: createLogger("error"),
};
//# sourceMappingURL=logger.js.map

1
dist/logger.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAoC;AAEpC,MAAM,aAAa,GAAG,qBAAqB,CAAA;AAC3C,MAAM,aAAa,GAAG,mBAAmB,CAAA;AAqBzC,MAAM,YAAY,GAAG,CAAC,KAAe,EAAE,EAAE;IACvC,MAAM,UAAU,GAAG,KAAK,EAAE,OAAe,EAAE,UAAsB,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AAA;IAED,OAAO,UAAU,CAAA;AACnB,CAAC,CAAA;AAEY,QAAA,MAAM,GAAG;IACpB,0BAA0B;IAC1B,IAAI,EAAE,YAAY,CAAC,MAAM,CAAC;IAC1B,kCAAkC;IAClC,IAAI,EAAE,YAAY,CAAC,MAAM,CAAC;IAC1B,kCAAkC;IAClC,KAAK,EAAE,YAAY,CAAC,OAAO,CAAC;CAC7B,CAAA"}

1
dist/teste.d.ts vendored Normal file
View file

@ -0,0 +1 @@
export {};

5
dist/teste.js vendored Normal file
View file

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("./logger");
logger_1.logger.error("Esse é um erro", { app: "teste" });
//# sourceMappingURL=teste.js.map

1
dist/teste.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"teste.js","sourceRoot":"","sources":["../src/teste.ts"],"names":[],"mappings":";;AAAA,qCAAiC;AAEjC,eAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAA"}

View file

@ -1,6 +1,6 @@
{ {
"name": "p-comuns", "name": "p-comuns",
"version": "0.70.0", "version": "0.72.0",
"description": "", "description": "",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
@ -15,6 +15,7 @@
}, },
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"cross-fetch": "^4.1.0",
"zod": "3.24.1" "zod": "3.24.1"
}, },
"devDependencies": { "devDependencies": {

53
pnpm-lock.yaml generated
View file

@ -8,9 +8,12 @@ importers:
.: .:
dependencies: dependencies:
cross-fetch:
specifier: ^4.1.0
version: 4.1.0
zod: zod:
specifier: 3.23.8 specifier: 3.24.1
version: 3.23.8 version: 3.24.1
devDependencies: devDependencies:
'@biomejs/biome': '@biomejs/biome':
specifier: ^1.9.4 specifier: ^1.9.4
@ -80,6 +83,21 @@ packages:
'@types/node@20.16.10': '@types/node@20.16.10':
resolution: {integrity: sha512-vQUKgWTjEIRFCvK6CyriPH3MZYiYlNy0fKiEYHWbcoWLEgs4opurGGKlebrTLqdSMIbXImH6XExNiIyNUv3WpA==} resolution: {integrity: sha512-vQUKgWTjEIRFCvK6CyriPH3MZYiYlNy0fKiEYHWbcoWLEgs4opurGGKlebrTLqdSMIbXImH6XExNiIyNUv3WpA==}
cross-fetch@4.1.0:
resolution: {integrity: sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==}
node-fetch@2.7.0:
resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
engines: {node: 4.x || >=6.0.0}
peerDependencies:
encoding: ^0.1.0
peerDependenciesMeta:
encoding:
optional: true
tr46@0.0.3:
resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
typescript@5.7.2: typescript@5.7.2:
resolution: {integrity: sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==} resolution: {integrity: sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==}
engines: {node: '>=14.17'} engines: {node: '>=14.17'}
@ -88,8 +106,14 @@ packages:
undici-types@6.19.8: undici-types@6.19.8:
resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==} resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==}
zod@3.23.8: webidl-conversions@3.0.1:
resolution: {integrity: sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==} resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
whatwg-url@5.0.0:
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
zod@3.24.1:
resolution: {integrity: sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==}
snapshots: snapshots:
@ -132,8 +156,27 @@ snapshots:
dependencies: dependencies:
undici-types: 6.19.8 undici-types: 6.19.8
cross-fetch@4.1.0:
dependencies:
node-fetch: 2.7.0
transitivePeerDependencies:
- encoding
node-fetch@2.7.0:
dependencies:
whatwg-url: 5.0.0
tr46@0.0.3: {}
typescript@5.7.2: {} typescript@5.7.2: {}
undici-types@6.19.8: {} undici-types@6.19.8: {}
zod@3.23.8: {} webidl-conversions@3.0.1: {}
whatwg-url@5.0.0:
dependencies:
tr46: 0.0.3
webidl-conversions: 3.0.1
zod@3.24.1: {}

View file

@ -8,3 +8,4 @@ export * from "./ecosistema"
export * from "./variaveisComuns" export * from "./variaveisComuns"
export * from "./tipagemRotas" export * from "./tipagemRotas"
export * from "./extensoes" export * from "./extensoes"
export * from "./logger"

71
src/logger.ts Normal file
View file

@ -0,0 +1,71 @@
import crossFetch from "cross-fetch"
const LOKI_BASE_URL = "https://log.idz.one"
const LOKI_ENDPOINT = "/loki/api/v1/push"
type LogLevel = "info" | "warn" | "error"
interface LogOptions {
app?: string
conta?: string
usuario?: string
detalhes?: unknown[]
}
interface LokiStream {
stream: {
app?: string
conta?: string
usuario?: string
level: LogLevel
}
values: Array<[string, string]>
}
const createLogger = (level: LogLevel) => {
const sendToLoki = async (message: string, options: LogOptions = {}) => {
const { app, conta, usuario, detalhes = [] } = options
const timestamp = `${Date.now()}000000`
try {
// Formata a linha de log principal
const mainLog =
detalhes.length > 0
? `${message} | ${detalhes.map((d) => JSON.stringify(d)).join(" ")}`
: message
const payload: LokiStream = {
stream: { app, conta, usuario, level },
values: [
[
timestamp,
mainLog, // Linha de log direta
],
],
}
const response = await crossFetch(`${LOKI_BASE_URL}${LOKI_ENDPOINT}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ streams: [payload] }),
})
if (!response.ok) {
throw new Error(`Erro ${response.status}: ${await response.text()}`)
}
} catch (error) {
console.error("[Logger] Falha no envio:", error)
}
}
return sendToLoki
}
export const logger = {
/** 🟢 Informação geral */
info: createLogger("info"),
/** 🟡 Aviso/atenção necessária */
warn: createLogger("warn"),
/** 🔴 Erro crítico na execução */
error: createLogger("error"),
}

3
src/teste.ts Normal file
View file

@ -0,0 +1,3 @@
import { logger } from "./logger"
logger.error("Esse é um erro", { app: "teste" })