mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Consolidate stdout logging and add audit retention
This commit is contained in:
@@ -3,11 +3,36 @@ const path = require('node:path');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
// Satu deskriptor append per proses membatasi memori tanpa menunggu layanan log eksternal.
|
||||
function createAuditArchive(directory) {
|
||||
function createAuditArchive(directory, { retentionDays = 0 } = {}) {
|
||||
let day;
|
||||
let descriptor;
|
||||
let lastPrunedDay;
|
||||
const runId = randomUUID();
|
||||
|
||||
function pruneExpiredFiles(time) {
|
||||
if (!retentionDays || lastPrunedDay === new Date(time).toISOString().slice(0, 10)) return 0;
|
||||
lastPrunedDay = new Date(time).toISOString().slice(0, 10);
|
||||
const cutoffDay = new Date(time - retentionDays * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
let errors = 0;
|
||||
|
||||
try {
|
||||
for (const name of fs.readdirSync(directory)) {
|
||||
const match = /^(\d{4}-\d{2}-\d{2})-\d+-[a-f0-9-]+\.jsonl$/i.exec(name);
|
||||
if (!match || match[1] >= cutoffDay) continue;
|
||||
try {
|
||||
fs.unlinkSync(path.join(directory, name));
|
||||
} catch {
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
errors += 1;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
function append(line, time) {
|
||||
const date = new Date(time).toISOString().slice(0, 10);
|
||||
if (day !== date) {
|
||||
@@ -17,6 +42,7 @@ function createAuditArchive(directory) {
|
||||
day = date;
|
||||
}
|
||||
fs.appendFileSync(descriptor, `${line}\n`);
|
||||
return { retentionErrors: pruneExpiredFiles(time) };
|
||||
}
|
||||
|
||||
function close() {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const winston = require("winston");
|
||||
require("winston-daily-rotate-file");
|
||||
const expressWinston = require("express-winston");
|
||||
const fs = require("fs");
|
||||
const moment = require("moment");
|
||||
const responseAudit = require("./response-audit");
|
||||
const { writeStdoutLine, formatLog } = require("./stdout-log");
|
||||
@@ -13,16 +11,6 @@ const {
|
||||
topuponline_metrics_load_balance,
|
||||
} = require("../helpers/prometheusmetrics");
|
||||
|
||||
const filename = () => {
|
||||
fs.mkdirSync(`./expresswinstonlog/${moment().format("YYYY/MM")}`, { recursive: true });
|
||||
|
||||
return `expresswinstonlog/${moment().format("YYYY")}-${moment().format(
|
||||
"MM"
|
||||
)}-${moment().format("DD")}.log`;
|
||||
};
|
||||
|
||||
filename();
|
||||
|
||||
const routes = new Set([
|
||||
"/api/reservation",
|
||||
"/api/reservation/v2",
|
||||
@@ -121,14 +109,8 @@ function recordResponse(event, partnerId, reservationNumber, message) {
|
||||
const logger = {
|
||||
correlation,
|
||||
response: expressWinston.logger({
|
||||
transports: [
|
||||
new winston.transports.DailyRotateFile({
|
||||
filename: "./expresswinstonlog/%DATE%.log",
|
||||
frequency: "24h",
|
||||
datePattern: "YYYY/MM/DD",
|
||||
maxFiles: "1d",
|
||||
}),
|
||||
],
|
||||
// Formatter mencatat audit/metrics sebagai efek samping; jangan gandakan ke file.
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
@@ -149,7 +131,7 @@ const logger = {
|
||||
response_time_ms: responseTime,
|
||||
};
|
||||
|
||||
// Format Winston harus sinkron agar log file tetap berisi respons yang dapat dibaca.
|
||||
// Format Winston dijalankan sinkron agar audit dan metrik tercatat sebelum respons selesai.
|
||||
const reservationNumber = route.startsWith('/api/reservation') && successfulCodes.has(event.status_code)
|
||||
? data?.reservation_number
|
||||
: undefined;
|
||||
@@ -182,30 +164,8 @@ const logger = {
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip", "partner_id_token"],
|
||||
bodyWhitelist: ["trxID", "load_balance_number"],
|
||||
}),
|
||||
request: expressWinston.logger({
|
||||
transports: [
|
||||
new winston.transports.DailyRotateFile({
|
||||
filename: "./expresswinstonlog/%DATE%.log",
|
||||
frequency: "24h",
|
||||
datePattern: "YYYY/MM/DD",
|
||||
maxFiles: "1d",
|
||||
}),
|
||||
],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
let body = {};
|
||||
body.id = info.meta.req.id;
|
||||
body.tag = "REQ";
|
||||
body.from = info.meta.req.ip;
|
||||
body.method = info.meta.req.method;
|
||||
body.endpoint = info.meta.req.originalUrl;
|
||||
body.time = moment().format();
|
||||
return `[${moment().format()}] | ${JSON.stringify(body)}`;
|
||||
})
|
||||
),
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "id", "ip"],
|
||||
}),
|
||||
// Request terpisah dihilangkan karena respons terstruktur sudah menjadi audit.
|
||||
request: (req, res, next) => next(),
|
||||
};
|
||||
|
||||
module.exports = { logger, filename };
|
||||
module.exports = { logger };
|
||||
|
||||
@@ -7,14 +7,31 @@ const auditErrors = new Counter({
|
||||
name: 'topuponline_audit_write_errors_total',
|
||||
help: 'Failed local audit archive writes',
|
||||
});
|
||||
const archive = createAuditArchive(process.env.TOPUP_AUDIT_DIR || './lokiLog/audit');
|
||||
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 {
|
||||
archive.append(line, time);
|
||||
const result = archive.append(line, time);
|
||||
if (result.retentionErrors > 0) retentionErrors.inc(result.retentionErrors);
|
||||
archiveUnavailable = false;
|
||||
} catch (error) {
|
||||
auditErrors.inc();
|
||||
@@ -31,4 +48,4 @@ function record(event) {
|
||||
writeStdoutLine(line);
|
||||
}
|
||||
|
||||
module.exports = { record, auditMetrics: [auditErrors] };
|
||||
module.exports = { record, auditMetrics: [auditErrors, retentionErrors] };
|
||||
|
||||
@@ -34,11 +34,18 @@ function createStdoutWriter(stream, onSkip) {
|
||||
const writeStdoutLine = createStdoutWriter(process.stdout, (reason) => skipped.inc({ reason }));
|
||||
|
||||
function formatLog(event, time = Date.now()) {
|
||||
const safeEvent = { ...event };
|
||||
if (typeof safeEvent.message === 'string') {
|
||||
safeEvent.message = safeEvent.message
|
||||
.replace(/\bBearer\s+[\w.+/=-]+/gi, 'Bearer [redacted]')
|
||||
.replace(/(["']?(?:password|passwd|pin|token|authorization|card[_ ]?number|uid|cvv|nik|requestData|responseData)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,}\]]+)/gi, '$1[redacted]')
|
||||
.slice(0, 512);
|
||||
}
|
||||
return JSON.stringify({
|
||||
timestamp: new Date(time).toISOString(),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
...event,
|
||||
...safeEvent,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
const moment = require("moment");
|
||||
const winston = require("winston");
|
||||
const { formatLog, writeStdoutLine } = require("./stdout-log");
|
||||
require("winston-daily-rotate-file");
|
||||
require("dotenv").config();
|
||||
const { combine, timestamp, printf, colorize, align, json } = winston.format;
|
||||
const { combine, timestamp, printf, align } = winston.format;
|
||||
|
||||
function stdoutMessage(message) {
|
||||
if (typeof message !== "string") return "Application log";
|
||||
// Legacy log calls append whole payloads after a separator.
|
||||
const payloadStart = message.search(/[:|]\s+(?:\{|\[\s*[{\]"\d]|<\?xml\b)/i);
|
||||
// Ringkasan mempertahankan konteks lama tanpa mengirim isi kartu, XML, atau data HSM.
|
||||
const payloadStart = message.search(/[:|]\s+(?:\{|"|\[\s*[{\]"\d]|<\?xml\b|(?:request|response)\s*data\b|message from HSM\b)/i);
|
||||
const summary = payloadStart === -1 ? message : message.slice(0, payloadStart);
|
||||
return summary.trim().replace(/\bBearer\s+[\w.+/=-]+/gi, "Bearer [redacted]");
|
||||
return summary.trim()
|
||||
.replace(/\bBearer\s+[\w.+/=-]+/gi, "Bearer [redacted]")
|
||||
.replace(/(["']?(?:password|passwd|pin|token|authorization|card[_ ]?number|uid|cvv|nik|requestData|responseData)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,}\]]+)/gi, "$1[redacted]")
|
||||
.slice(0, 512);
|
||||
}
|
||||
|
||||
class StdoutTransport extends winston.Transport {
|
||||
@@ -35,32 +36,6 @@ const logLevels = {
|
||||
};
|
||||
var logger;
|
||||
|
||||
//
|
||||
// Replaces the previous transports with those in the
|
||||
// new configuration wholesale.
|
||||
//
|
||||
// const DailyRotateFile = require("winston-daily-rotate-file");
|
||||
// logger.configure({
|
||||
// level: "verbose",
|
||||
// transports: [new DailyRotateFile()],
|
||||
// });
|
||||
|
||||
const fileRotateTransport = new winston.transports.DailyRotateFile({
|
||||
filename: `application/logs/%DATE%-onlinetopup.log`,
|
||||
datePattern: "YYYY-MM-DD",
|
||||
maxFiles: "60d",
|
||||
});
|
||||
|
||||
const fileRotateTransportDebug = new winston.transports.DailyRotateFile({
|
||||
filename: `application/logs/debug/%DATE%-onlinetopup.log`,
|
||||
datePattern: "YYYY-MM-DD",
|
||||
maxFiles: "30d",
|
||||
});
|
||||
//
|
||||
// If we're not in production then log to the `console` with the format:
|
||||
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
|
||||
//
|
||||
|
||||
if (
|
||||
process.env.NODE_ENV == "production" ||
|
||||
process.env.NODE_ENV == "PRODUCTION"
|
||||
@@ -69,9 +44,7 @@ if (
|
||||
levels: logLevels,
|
||||
level: process.env.LOG_LEVEL || "info",
|
||||
exitOnError: false,
|
||||
// format: combine(timestamp(), json()),
|
||||
format: combine(
|
||||
// colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
@@ -79,30 +52,14 @@ if (
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
|
||||
),
|
||||
defaultMeta: { service: "topuponline-service" },
|
||||
transports: [
|
||||
fileRotateTransport,
|
||||
fileRotateTransportDebug,
|
||||
//
|
||||
// - Write all logs with importance level of `error` or less to `error.log`
|
||||
// - Write all logs with importance level of `info` or less to `onlinetopup.log`
|
||||
//
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/error.log`,
|
||||
level: "error",
|
||||
}),
|
||||
// new winston.transports.File({
|
||||
// filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`,
|
||||
// }),
|
||||
],
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
});
|
||||
} else {
|
||||
logger = winston.createLogger({
|
||||
levels: logLevels,
|
||||
level: process.env.LOG_LEVEL || "debug",
|
||||
exitOnError: false,
|
||||
// format: combine(timestamp(), json()),
|
||||
format: combine(
|
||||
// colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
@@ -110,25 +67,7 @@ if (
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
|
||||
),
|
||||
defaultMeta: { service: "topuponline-service" },
|
||||
transports: [
|
||||
fileRotateTransport,
|
||||
fileRotateTransportDebug,
|
||||
//
|
||||
// - Write all logs with importance level of `error` or less to `error.log`
|
||||
// - Write all logs with importance level of `info` or less to `onlinetopup.log`
|
||||
//
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/error.log`,
|
||||
level: "error",
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/debug/${moment().format("YYYY-MM-DD")}.log`,
|
||||
level: "debug",
|
||||
}),
|
||||
// new winston.transports.File({
|
||||
// filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`,
|
||||
// }),
|
||||
],
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@ request ID, atau durasi minimum.
|
||||
Aplikasi menulis satu objek JSON per baris ke stdout. URL tujuan Loki berada
|
||||
di konfigurasi Promtail. Tambahkan label stream `app=topuponline` di target
|
||||
scrape agar dashboard dan kueri di atas tetap menemukan log.
|
||||
Respons terpantau menggunakan `event=http_response`; log Winston menggunakan
|
||||
`event=application_log`. Request tidak dicatat sebagai event terpisah karena
|
||||
ID request dan statusnya tersedia pada event respons.
|
||||
|
||||
Untuk service yang menulis stdout ke file, arahkan `__path__` ke file stdout
|
||||
yang sebenarnya. Contoh ini berlaku untuk file yang memuat pesan aplikasi
|
||||
|
||||
@@ -3,15 +3,23 @@
|
||||
## Arsip dan Loki
|
||||
|
||||
Setiap respons yang dipantau ditulis sebagai JSONL sebelum salinannya dikirim
|
||||
ke stdout. Promtail mengambil stdout dari log process manager atau kontainer
|
||||
dan mengirimkannya ke Loki. Arsip dapat dicari dengan `request_id`, `trx_id`,
|
||||
ke stdout. Log operasional Winston dan ringkasan respons hanya dikirim ke stdout;
|
||||
aplikasi tidak membuat salinan operasional di file harian. Collector mengambil
|
||||
stdout dari process manager atau kontainer dan mengirimkannya ke Loki. Arsip
|
||||
dapat dicari dengan `request_id`, `trx_id`,
|
||||
`reservation_number`, atau `load_balance_number` jika tersedia. Riwayat
|
||||
transaksi PostgreSQL tetap menjadi sumber status bisnis.
|
||||
|
||||
Gunakan `TOPUP_AUDIT_DIR` pada volume persisten yang dapat ditulis oleh proses
|
||||
aplikasi. Path bawaan adalah `./lokiLog/audit`. File dibagi per tanggal UTC dan
|
||||
proses. Atur pemantauan ruang disk dan pengarsipan sesuai retensi audit organisasi.
|
||||
Aplikasi tidak menghapus file JSONL. Jika penulisan gagal, aplikasi menaikkan
|
||||
proses. Secara default aplikasi tidak menghapus file JSONL. Tetapkan
|
||||
`TOPUP_AUDIT_RETENTION_DAYS` sebagai bilangan hari positif sesuai kebijakan
|
||||
retensi audit organisasi untuk mengaktifkan penghapusan file yang melewati usia
|
||||
tersebut. Pembersihan berjalan
|
||||
paling banyak sekali per hari per proses saat respons audit pertama dicatat;
|
||||
hanya file JSONL buatan aplikasi yang dikenali berdasarkan nama file yang dihapus.
|
||||
Pantau `topuponline_audit_retention_errors_total` untuk kegagalan pembersihan.
|
||||
Tetap pantau ruang disk volume audit. Jika penulisan gagal, aplikasi menaikkan
|
||||
`topuponline_audit_write_errors_total` dan tetap mencoba mencatat ke stdout.
|
||||
Ketersediaan audit saat disk gagal bergantung pada penampung stdout yang terpisah.
|
||||
|
||||
@@ -20,8 +28,12 @@ direktori kerja aplikasi. Contoh di Linux untuk volume yang sudah dipasang.
|
||||
|
||||
```dotenv
|
||||
TOPUP_AUDIT_DIR=/var/lib/onlinetopup/audit
|
||||
TOPUP_AUDIT_RETENTION_DAYS=60
|
||||
```
|
||||
|
||||
Jangan aktifkan masa retensi sebelum kebijakan audit dan kewajiban penyimpanan
|
||||
transaksi disetujui. Nilai contoh `60` hari harus disesuaikan untuk lingkungan.
|
||||
|
||||
Restart aplikasi melalui service manager setelah mengubah environment. Lakukan
|
||||
satu request ke endpoint yang dipantau dan cocokkan nilai `X-Request-Id` dengan
|
||||
arsip JSONL pada direktori tersebut. Gunakan akun service yang sama saat
|
||||
@@ -29,7 +41,8 @@ memeriksa izin tulis, dan simpan arsip setiap replika di volume persisten.
|
||||
|
||||
Jika stdout sedang tersendat, aplikasi melewatkan salinan terminal dan menaikkan
|
||||
`topuponline_stdout_copies_skipped_total`. Cari audit respons tersebut di arsip
|
||||
JSONL. Log Winston tetap memiliki salinan di file log aplikasi sesuai levelnya.
|
||||
JSONL. Log operasional Winston hanya memiliki jalur stdout; retensi salinannya
|
||||
diatur oleh process manager/container dan collector.
|
||||
|
||||
```powershell
|
||||
rg --fixed-strings '<request-id>' ./lokiLog/audit
|
||||
|
||||
@@ -78,7 +78,6 @@ app.get('/', async (req, res) => {
|
||||
});
|
||||
|
||||
app.use(logger.correlation);
|
||||
app.use(logger.request);
|
||||
app.use(logger.response);
|
||||
|
||||
app.use('/api/', authRoute);
|
||||
|
||||
Reference in New Issue
Block a user