mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-06 20:16:28 +00:00
56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
const { Counter } = require('prom-client');
|
|
const createAuditArchive = require('./audit-archive');
|
|
const { formatLog, writeStdoutLine } = require('./stdout-log');
|
|
require('dotenv').config();
|
|
|
|
const auditErrors = new Counter({
|
|
name: 'topuponline_audit_write_errors_total',
|
|
help: 'Failed local audit archive writes',
|
|
});
|
|
const retentionErrors = new Counter({
|
|
name: 'topuponline_audit_retention_errors_total',
|
|
help: 'Failed local audit archive retention deletions',
|
|
});
|
|
const retentionDaysValue = process.env.TOPUP_AUDIT_RETENTION_DAYS;
|
|
const retentionDays = retentionDaysValue === undefined || retentionDaysValue === ''
|
|
? 0
|
|
: Number(retentionDaysValue);
|
|
if (retentionDaysValue !== undefined && retentionDaysValue !== '') {
|
|
if (!Number.isSafeInteger(retentionDays) || retentionDays < 1 || retentionDays > 36500) {
|
|
throw new Error('TOPUP_AUDIT_RETENTION_DAYS must be an integer between 1 and 36500');
|
|
}
|
|
}
|
|
const archive = createAuditArchive(
|
|
process.env.TOPUP_AUDIT_DIR || './lokiLog/audit',
|
|
{ retentionDays }
|
|
);
|
|
let archiveUnavailable = false;
|
|
|
|
function record(event) {
|
|
const time = Date.now();
|
|
const line = formatLog(event, time);
|
|
try {
|
|
const result = archive.append(line, time);
|
|
if (result.retentionErrors > 0) retentionErrors.inc(result.retentionErrors);
|
|
archiveUnavailable = false;
|
|
} catch (error) {
|
|
auditErrors.inc();
|
|
if (!archiveUnavailable) {
|
|
writeStdoutLine(formatLog({
|
|
level: 'error',
|
|
event: 'audit_archive_error',
|
|
message: 'Unable to write the local audit archive',
|
|
error_code: error.code || 'UNKNOWN',
|
|
}, time));
|
|
}
|
|
archiveUnavailable = true;
|
|
}
|
|
writeStdoutLine(line);
|
|
}
|
|
|
|
function close() {
|
|
archive.close();
|
|
}
|
|
|
|
module.exports = { record, close, auditMetrics: [auditErrors, retentionErrors] };
|