zephyr-agent
Version:
Zephyr plugin agent
86 lines (85 loc) • 3.26 kB
JavaScript
import "node:module";
import { PromiseLazyLoad, ZE_API_ENDPOINT, stripAnsi, ze_api_gateway } from "zephyr-edge-contract";
import { getApplicationConfiguration } from "../edge-requests/get-application-configuration.mjs";
import { ZeErrors, ZephyrError } from "../errors/index.mjs";
import { makeRequest } from "../http/http-request.mjs";
import { getToken } from "../node-persist/token.mjs";
import { brightBlueBgName, brightGreenBgName, brightRedBgName, brightYellowBgName } from "./debug.mjs";
import { isFileLoggingEnabled, writeLogToFile } from "./file-logger.mjs";
import { redactString, safeStringifyForLogging } from "../security/redaction.mjs";
const logFn = (level, msg, action)=>{
const messageStr = redactString(String(msg));
if (isFileLoggingEnabled()) writeLogToFile({
level: level,
message: messageStr,
action,
timestamp: Date.now()
});
const formatted = formatLogMsg(messageStr, level);
switch(level){
case 'warn':
console.warn(formatted);
break;
case 'debug':
console.debug(formatted);
break;
case 'error':
console.error(formatted);
break;
default:
console.log(formatted);
}
};
function toLevelPrefix(level) {
switch(level){
case 'warn':
return brightYellowBgName;
case 'debug':
return brightGreenBgName;
case 'error':
return brightRedBgName;
default:
return brightBlueBgName;
}
}
function formatLogMsg(msg, level = 'info') {
return redactString(msg).split('\n').map((m)=>`${toLevelPrefix(level)} ${m.trimEnd()}`).join('\n');
}
function logger(props) {
const { application_uid, buildId, git } = props;
const loadLogData = PromiseLazyLoad(()=>Promise.all([
getApplicationConfiguration({
application_uid
}),
getToken()
]));
const url = new URL(ze_api_gateway.logs, ZE_API_ENDPOINT());
return function(...logs) {
for (const log of logs){
if (!log.level && !log.action) throw new ZephyrError(ZeErrors.ERR_UNKNOWN, {
message: 'Log level and action are required'
});
logFn(log.level, log.message, log.action);
}
loadLogData().then(([config, token])=>void makeRequest(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
credentialToken: token
}, safeStringifyForLogging(logs.filter((l)=>l.message.length && !l.ignore).map((log)=>({
application_uid: application_uid,
userId: config.user_uuid,
username: config.username,
zeBuildId: buildId,
logLevel: log.level,
actionType: log.action,
git: git,
message: stripAnsi(log.message.trim()),
createdAt: Date.now()
}))))).catch(()=>void 0);
};
}
export { formatLogMsg, logFn, logger };
//# sourceMappingURL=ze-log-event.mjs.map