@topgroup/diginext
Version:
A BUILD SERVER & CLI to deploy apps to any Kubernetes clusters.
90 lines (89 loc) • 3.86 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SystemLogService = void 0;
const log_1 = require("diginext-utils/dist/xconsole/log");
const SystemLog_1 = require("../entities/SystemLog");
const BaseService_1 = __importDefault(require("./BaseService"));
class SystemLogService extends BaseService_1.default {
constructor(ownership) {
super(SystemLog_1.systemLogSchema, ownership);
}
async saveLog(message, options = {}) {
if (typeof message === "undefined")
return;
if (typeof options.level === "undefined")
options.level = 1;
if (typeof options.type === "undefined")
options.type = "debug";
const log = await this.create({ message, ...options });
// check expired logs and deleted expired ones
this.deleteExpiredLogs();
return log;
}
async saveError(error, options) {
(0, log_1.logError)(error.stack);
return this.saveLog(error.stack, { ...options, level: 3, type: "error" });
}
async deleteExpiredLogs() {
var _a, _b, _c;
const { type, value } = ((_c = (_b = (_a = this.workspace) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.system_log) === null || _c === void 0 ? void 0 : _c.retention) || {};
if (!type && !value)
return;
console.log(`Deleting expired logs...`);
const now = new Date();
if (type === "duration") {
// Mark as deleted based on duration
const thresholdDate = new Date(Date.now() - value);
// Count system logs that would be marked as deleted
return this.model
.countDocuments({
createdAt: { $lt: thresholdDate },
deletedAt: null,
})
.then((toDeleteCount) => {
console.log(`${toDeleteCount} system logs will be marked as deleted based on duration.`);
// Now, perform the update if there are any system logs to be marked as deleted
if (toDeleteCount > 0) {
return this.model.updateMany({
createdAt: { $lt: thresholdDate },
deletedAt: null,
}, {
$set: { deletedAt: new Date() },
});
}
})
.catch((e) => {
console.error(`Unable to delete expired logs:`, e);
});
}
else if (type === "limit") {
// Mark as deleted based on item count
return this.model
.countDocuments({ deletedAt: null })
.then((count) => {
const itemsToDelete = count - value;
if (itemsToDelete > 0) {
// We need to delete the oldest items, so we sort by 'createdAt'
return this.model
.find({ deletedAt: null })
.sort({ createdAt: 1 })
.limit(itemsToDelete)
.then((docs) => {
const idsToDelete = docs.map((doc) => doc._id);
return this.model.updateMany({ _id: { $in: idsToDelete } }, { $set: { deletedAt: now } });
})
.catch((e) => {
console.error(`Unable to delete expired logs:`, e);
});
}
})
.catch((e) => {
console.error(`Unable to delete expired logs:`, e);
});
}
}
}
exports.SystemLogService = SystemLogService;