@homecheck/logger
Version:
A simple logger for Web, Node, Capacitor apps.
147 lines (146 loc) • 5.26 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeStorage = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class NodeStorage {
constructor(storagePath) {
this.logs = [];
this.initialized = false;
this.storagePath = storagePath || path.join(process.cwd(), '.logs');
}
async init() {
try {
// 디렉토리가 없으면 생성
if (!fs.existsSync(this.storagePath))
fs.mkdirSync(this.storagePath, { recursive: true });
// 기존 로그 파일 로드
const logFiles = fs.readdirSync(this.storagePath)
.filter(file => file.endsWith('.json'));
for (const file of logFiles) {
try {
const content = fs.readFileSync(path.join(this.storagePath, file), 'utf8');
const logData = JSON.parse(content);
this.logs.push(logData);
}
catch (error) {
throw error;
}
}
this.initialized = true;
}
catch (error) {
throw new Error(`Failed to load log file: ${error}`);
}
}
async addLog(logData) {
try {
if (!this.initialized)
await this.init();
// ID와 생성 시간 추가
const logWithId = {
...logData,
id: crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
createdAt: Date.now()
};
// 메모리에 추가
this.logs.push(logWithId);
// 파일로 저장
const filePath = path.join(this.storagePath, `${logWithId.id}.json`);
fs.writeFileSync(filePath, JSON.stringify(logWithId));
}
catch (error) {
throw error;
}
}
async getLogs(limit) {
try {
if (!this.initialized)
await this.init();
// 생성 시간 순으로 정렬
return [...this.logs]
.sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))
.slice(0, limit);
}
catch (error) {
throw new Error(`Failed to get logs from node storage: ${error}`);
}
}
async removeLogs(ids) {
try {
if (!this.initialized)
await this.init();
// 메모리에서 제거
this.logs = this.logs.filter(log => !log.id || !ids.includes(log.id));
// 파일 삭제
for (const id of ids) {
const filePath = path.join(this.storagePath, `${id}.json`);
if (fs.existsSync(filePath))
fs.unlinkSync(filePath);
}
}
catch (error) {
throw new Error(`Failed to remove logs from node storage: ${error}`);
}
}
async getCount() {
try {
if (!this.initialized)
await this.init();
return this.logs.length;
}
catch (error) {
throw new Error(`Failed to get log count from node storage: ${error}`);
}
}
async clear() {
try {
if (!this.initialized)
await this.init();
// 메모리 초기화
this.logs = [];
// 모든 로그 파일 삭제
const logFiles = fs.readdirSync(this.storagePath)
.filter(file => file.endsWith('.json'));
for (const file of logFiles)
fs.unlinkSync(path.join(this.storagePath, file));
}
catch (error) {
throw new Error(`Failed to clear node storage: ${error}`);
}
}
}
exports.NodeStorage = NodeStorage;
;