archunit
Version:
ArchUnit TypeScript is an architecture testing library, to specify and assert architecture rules in your TypeScript app
193 lines • 7.33 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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CheckLogger = exports.sharedLogger = void 0;
const node_fs_1 = require("node:fs");
const path = __importStar(require("node:path"));
/**
* CheckLogger is designed to output logging information during the execution of architectural checks.
* It creates a single log file per instance and supports both console and file logging.
*/
class CheckLogger {
constructor() {
this.isFileInitialized = false;
// Auto-assign log file path with timestamp in logs directory
const now = new Date();
const timestamp = now
.toISOString()
.replace(/T/, '_')
.replace(/:/g, '-')
.replace(/\.\d{3}Z$/, '');
this.logFilePath = path.join(process.cwd(), 'logs', `archunit-${timestamp}.log`);
}
/**
* Determines whether to log to console based on options
*/
shouldLogToConsole(options) {
return options?.enabled || false;
}
/**
* Determines whether to log to file based on options
*/
shouldLogToFile(options) {
return options?.enabled === true && options?.logFile === true;
}
/**
* Determines if the given log level should be logged based on the configured minimum level
*/
shouldLogLevel(messageLevel, options) {
const levels = ['debug', 'info', 'warn', 'error'];
const minLevel = options?.level || 'info';
const minLevelIndex = levels.indexOf(minLevel);
const messageLevelIndex = levels.indexOf(messageLevel.toLowerCase());
// If message level is at or above the minimum level, log it
return messageLevelIndex >= minLevelIndex;
} /**
* Prepares file for writing if needed
*/
prepareFileWriting(options) {
if (!this.shouldLogToFile(options)) {
return;
}
if (!this.isFileInitialized) {
const append = options?.appendToLogFile ?? true;
const dir = path.dirname(this.logFilePath);
// Ensure directory exists
if (!(0, node_fs_1.existsSync)(dir)) {
(0, node_fs_1.mkdirSync)(dir, { recursive: true });
}
if (!append || !(0, node_fs_1.existsSync)(this.logFilePath)) {
// Create new file or overwrite existing
const sessionHeader = `ArchUnitTS Logging Session Started\n${new Date().toISOString()}\n${'='.repeat(50)}\n`;
(0, node_fs_1.writeFileSync)(this.logFilePath, sessionHeader);
}
this.isFileInitialized = true;
}
}
/**
* Writes message to file if file logging is enabled
*/
writeToFile(message, options) {
if (!this.shouldLogToFile(options)) {
return;
}
this.prepareFileWriting(options);
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}\n`;
(0, node_fs_1.appendFileSync)(this.logFilePath, logEntry);
}
/**
* Formats log message with level and arguments
*/
formatMessage(level, message, args) {
const formattedArgs = args.length > 0 ? ` ${args.map((arg) => String(arg)).join(' ')}` : '';
return `[${level}] ${message}${formattedArgs}`;
}
debug(options, message, ...args) {
if (!this.shouldLogLevel('debug', options)) {
return;
}
const fullMessage = this.formatMessage('DEBUG', message, args);
if (this.shouldLogToConsole(options)) {
console.debug(fullMessage);
}
this.writeToFile(fullMessage, options);
}
info(options, message, ...args) {
if (!this.shouldLogLevel('info', options)) {
return;
}
const fullMessage = this.formatMessage('INFO', message, args);
if (this.shouldLogToConsole(options)) {
console.info(fullMessage);
}
this.writeToFile(fullMessage, options);
}
warn(options, message, ...args) {
if (!this.shouldLogLevel('warn', options)) {
return;
}
const fullMessage = this.formatMessage('WARN', message, args);
if (this.shouldLogToConsole(options)) {
console.warn(fullMessage);
}
this.writeToFile(fullMessage, options);
}
error(options, message, ...args) {
if (!this.shouldLogLevel('error', options)) {
return;
}
const fullMessage = this.formatMessage('ERROR', message, args);
if (this.shouldLogToConsole(options)) {
console.error(fullMessage);
}
this.writeToFile(fullMessage, options);
}
/**
* Gets the path to the log file for this logger instance
*/
getLogFilePath() {
return this.logFilePath;
}
// Additional specialized methods for architectural checks
isEnabled() {
return true; // Always enabled, controlled by options passed to individual calls
}
startCheck(ruleName, options) {
const message = `Starting architecture rule check: ${ruleName}`;
this.info(options, message);
}
endCheck(ruleName, violationCount, options) {
const message = `Completed architecture rule check: ${ruleName} (${violationCount} violations)`;
if (violationCount > 0) {
this.warn(options, message);
}
else {
this.info(options, message);
}
}
logViolation(violation, options) {
const message = `Violation found: ${violation}`;
this.warn(options, message);
}
logProgress(message, options) {
this.debug(options, message);
}
logMetric(metricName, value, threshold, options) {
let message = `Metric ${metricName}: ${value}`;
if (threshold !== undefined) {
message += ` (threshold: ${threshold})`;
}
this.debug(options, message);
}
logFileProcessing(fileName, matchedRules, options) {
const message = `Processed file: ${fileName} (matched ${matchedRules} rules)`;
this.debug(options, message);
}
}
exports.CheckLogger = CheckLogger;
// Shared logger instance used across all architecture checks
exports.sharedLogger = new CheckLogger();
//# sourceMappingURL=logger.js.map
;