_comuns/src/logger.ts
2025-02-27 16:04:14 -03:00

124 lines
2.8 KiB
TypeScript

import crossFetch from "cross-fetch"
import { nomeVariavel } from "./variaveisComuns"
const LOKI_BASE_URL = "https://log.idz.one"
const LOKI_ENDPOINT = "/loki/api/v1/push"
export type tipoLokiObjeto = {
streams: {
stream: {
[k: string]: string
}
values: [string, string][]
}[]
}
export const postLogger = async ({
objeto,
}: { objeto: tipoLokiObjeto }): Promise<
[objeto: tipoLokiObjeto, erro?: string]
> => {
const response = await crossFetch(`${LOKI_BASE_URL}${LOKI_ENDPOINT}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(objeto),
}).catch((a) => a)
if (!response.ok) {
return [objeto, `Erro ${response.status}: ${await response?.text?.()}`]
} else {
return [objeto]
}
}
let cwd = ""
/** define a localização da pasta do projeto */
export const defineCwd = (novoCwd: string) => {
cwd = novoCwd
}
type tipoLevel = "info" | "warn" | "error"
type tipoOpSessao = {
inquilino: string
usuario: string
parametros?: { [k: string]: string }
}
type tipoLog = {
detalhes?: unknown[]
__filename?: string
local?: string
parametros?: { [k: string]: string }
}
export type tipoLoggerLog = (
level: tipoLevel,
mensagem: string,
op_tipoLog?: tipoLog,
) => Promise<[objeto: tipoLokiObjeto, erro?: string]>
export type TipoLoggerSessao = (sess: tipoOpSessao) => tipoLoggerLog
export type tipoLogger = (amb: {
app: string
eProducao: boolean
parametros?: {
[k: string]: string
}
}) => TipoLoggerSessao
export const logger: tipoLogger =
({ app: app_e, eProducao, parametros: parametrosAmbiente }) =>
({ inquilino, usuario, parametros: parametrosSessao }) =>
async (level, mensagem, op_tipoLog) => {
let {
__filename,
detalhes,
local,
parametros: parametrosLog,
} = op_tipoLog || {}
const app = `${eProducao ? "" : "DEV-"}${app_e}`
if (cwd && __filename) {
__filename = __filename.replace(cwd, "")
}
if (local) {
detalhes = [`${nomeVariavel({ local })}="${local}"`]
}
if (__filename) {
detalhes = [`${nomeVariavel({ __filename })}="${__filename}"`]
}
const timestamp = `${Date.now()}000000`
const mainLog = detalhes?.length
? `${mensagem} | ${detalhes.map((d) => JSON.stringify(d)).join(" ")}`
: mensagem
const payload: tipoLokiObjeto["streams"][number] = {
stream: {
app,
inquilino,
usuario,
level,
...(parametrosAmbiente || {}),
...(parametrosSessao || {}),
...(parametrosLog || {}),
},
values: [
[
timestamp,
mainLog, // Linha de log direta
],
],
}
const objeto: tipoLokiObjeto = { streams: [payload] }
const response = await postLogger({ objeto })
return response
}