Skip to content

Commit

Permalink
Fix error logging and remove process exit
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Dec 23, 2023
1 parent e91a088 commit 1b772cb
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 82 deletions.
10 changes: 1 addition & 9 deletions crates/compiler/src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,20 +133,12 @@ impl Compiler {
}

self.handle_global_log(&mut errors);

if !errors.is_empty() {
let mut error_messages = vec![];
for error in errors {
error_messages.push(error.to_string());
}
let error_message = format!(
"\n Build failed due to errors: \n\n {}",
error_messages.join("\n")
);
println!("{}", error_message);
// TODO Temporarily exit the process with exit
std::process::exit(1);
// return Err(CompilationError::GenericError(error_messages.join(", ")));
return Err(CompilationError::GenericError(error_messages.join(", ")));
}

// set module graph cache
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/utils/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export async function compilerHandler(
try {
await callback();
} catch (error) {
logger.error(error);
logger.error(error, {
exit: true
});
}
const endTime = performance.now();
const elapsedTime = Math.floor(endTime - startTime);
Expand Down
33 changes: 31 additions & 2 deletions packages/core/src/utils/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,36 @@ export const bgMagenta = enabled ? formatter('\x1b[45m', '\x1b[49m') : String;
export const bgCyan = enabled ? formatter('\x1b[46m', '\x1b[49m') : String;
export const bgWhite = enabled ? formatter('\x1b[47m', '\x1b[49m') : String;

export const colors = {
reset,
bold,
dim,
italic,
underline,
inverse,
hidden,
strikethrough,
black,
red,
green,
yellow,
blue,
magenta,
cyan,
white,
gray,
bgBlack,
bgRed,
bgGreen,
bgYellow,
bgBlue,
bgMagenta,
bgCyan,
bgWhite,
debugColor,
brandColor
};

export function gradientString(text: string, colors: number[][]) {
const steps = text.length;
const gradient = colors.map(
Expand All @@ -120,7 +150,6 @@ export function gradientString(text: string, colors: number[][]) {
output += `${gradient[colorIndex]}${text[i]}`;
}

// 重置颜色
output += '\x1b[0m';

return output;
Expand All @@ -138,7 +167,7 @@ export function interpolateColor(
];
}

export const PersistentCacheBrand = gradientString('⚡️FULL EXTREME !', [
export const PersistentCacheBrand = gradientString('⚡️ FULL EXTREME !', [
[176, 106, 179],
interpolateColor([176, 106, 179], [198, 66, 110], 0.1),
interpolateColor([176, 106, 179], [198, 66, 110], 0.2),
Expand Down
127 changes: 57 additions & 70 deletions packages/core/src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

import {
ColorFunction,
PersistentCacheBrand,
blue,
bold,
brandColor,
cyan,
debugColor,
green,
magenta,
red,
yellow
colors
} from './color.js';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { Config } from '../../binding/index.js';

type LogLevelNames = 'trace' | 'debug' | 'info' | 'warn' | 'error';
Expand All @@ -28,17 +21,16 @@ enum LogLevel {
}

export interface Logger {
trace(message: string | string[]): void;
debug(message: string | string[]): void;
info(message: string | string[]): void;
warn(message: string | string[]): void;
error(message: string | string[] | Error[], options?: ErrorOptions): void;
trace(message: string): void;
debug(message: string): void;
info(message: string): void;
warn(message: string): void;
error(message: string | Error, options?: ErrorOptions): void;
}

export interface ErrorOptions {
exit?: boolean;
e?: Error;
timestamp?: boolean;
error?: Error;
}
interface LoggerOptions {
Expand All @@ -47,7 +39,7 @@ interface LoggerOptions {
exit?: boolean;
}

const LOGGING_METHOD = {
const LOGGER_METHOD = {
info: 'log',
warn: 'warn',
error: 'error'
Expand Down Expand Up @@ -75,41 +67,28 @@ export class DefaultLogger implements Logger {

private brandPrefix(color?: (s: string | string[]) => string): void {
const { name = 'Farm' } = this.options;
const formattedName = bold(name);
const formattedPrefix = bold(`[ ${formattedName} ]`);
const formattedName = colors.bold(name);
const formattedPrefix = colors.bold(`[ ${formattedName} ]`);
this.prefix = color ? color(formattedPrefix) : formattedPrefix;
}

private logMessage(
level: LogLevelNames,
message: string[],
message: string | Error,
color?: (s: string | string[]) => string,
showBanner = true
): void {
const loggerMethod =
level in LOGGING_METHOD
? LOGGING_METHOD[level as keyof typeof LOGGING_METHOD]
level in LOGGER_METHOD
? LOGGER_METHOD[level as keyof typeof LOGGER_METHOD]
: 'log';
if (this.levelValues[level] <= this.levelValues[level]) {
const prefix = showBanner ? this.prefix + ' ' : '';
const loggerMessage = color
? color(prefix + message.join(' '))
: prefix + message.join(' ');
? color(prefix + message)
: prefix + message;
console[loggerMethod](loggerMessage);
}
if (level === LogLevel.Error) {
process.exit(0);
}
}

trace(...message: any[]): void {
this.brandPrefix(green);
this.logMessage(LogLevel.Trace, message, magenta);
}

debug(...message: any[]): void {
this.brandPrefix(debugColor);
this.logMessage(LogLevel.Debug, message, blue);
}

setPrefix(options: LoggerOptions): void {
Expand All @@ -119,62 +98,70 @@ export class DefaultLogger implements Logger {
}
}

info(...message: any[]): void {
let options: LoggerOptions | undefined;

// Check if the last argument is an object (options)
if (message.length > 0 && typeof message[message.length - 1] === 'object') {
options = message.pop() as LoggerOptions;
}
trace(message: string): void {
this.brandPrefix(colors.green);
this.logMessage(LogLevel.Trace, message, colors.magenta);
}

debug(message: string): void {
this.brandPrefix(colors.debugColor);
this.logMessage(LogLevel.Debug, message, colors.blue);
}


info(message: string, iOptions?: LoggerOptions): void {
const options: LoggerOptions | undefined = iOptions;
if (options) {
this.setPrefix(options);
}
if (!options || !options.brandColor) {
this.brandPrefix(brandColor);
this.brandPrefix(colors.brandColor);
}
this.logMessage(LogLevel.Info, message, null);
}

warn(...message: any[]): void {
this.brandPrefix(yellow);
this.logMessage(LogLevel.Warn, message, yellow);
warn(message: string): void {
this.brandPrefix(colors.yellow);
this.logMessage(LogLevel.Warn, message, colors.yellow);
}

error(...message: any[]): void {
this.brandPrefix(red);
this.logMessage(LogLevel.Error, message, red);
error(message: string | Error, errorOptions?: ErrorOptions): void {
this.brandPrefix(colors.red);
this.logMessage(LogLevel.Error, message, colors.red);

if (this.options?.exit) {
const effectiveOptions = { ...this.options, ...errorOptions };

if (effectiveOptions.exit) {
process.exit(1);
}
}
infoOnce(...message: any[]) {
if (!warnOnceMessages.has(message[0])) {
infoOnceMessages.add(message.join(' '));
this.info(...message);
infoOnce(message: string) {
if (!infoOnceMessages.has(message)) {
infoOnceMessages.add(message);
this.info(message);
}
}
warnOnce(...message: any[]) {
if (!warnOnceMessages.has(message[0])) {
warnOnceMessages.add(message.join(' '));
this.warn(...message);
warnOnce(message: string) {
if (!warnOnceMessages.has(message)) {
warnOnceMessages.add(message);
this.warn(message);
}
}
errorOnce(...message: any[]) {
if (!warnOnceMessages.has(message[0])) {
errorOnceMessages.add(message.join(' '));
this.error(...message);
errorOnce(message: string | Error) {
if (!errorOnceMessages.has(message)) {
errorOnceMessages.add(message);
this.error(message);
}
}
}

export function printServerUrls(urls: any, logger: Logger): void {
const colorUrl = (url: string) =>
cyan(url.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`));
colors.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors.bold(port)}/`));

const logUrl = (url: string, type: string) =>
logger.info(`${bold(magenta('>'))} ${bold(type)}${bold(colorUrl(url))}`);
logger.info(`${colors.bold(colors.magenta('>'))} ${colors.bold(type)}${colors.bold(colorUrl(url))}`);

urls.local.map((url: string) => logUrl(url, 'Local: '));
urls.network.map((url: string) => logUrl(url, 'Network: '));
Expand All @@ -187,18 +174,18 @@ export function bootstrapLogger(options?: LoggerOptions): Logger {
export function bootstrap(times: number, config: Config) {
const usePersistentCache = config.config.persistentCache;
const persistentCacheFlag = usePersistentCache
? bold(PersistentCacheBrand)
? colors.bold(PersistentCacheBrand)
: '';
const version = JSON.parse(
readFileSync(
join(fileURLToPath(import.meta.url), '../../../package.json'),
'utf-8'
)
).version;
console.log('\n', bold(brandColor(`${'ϟ'} Farm v${version}`)));
console.log('\n', colors.bold(colors.brandColor(`${'ϟ'} Farm v${version}`)));
console.log(
`${bold(green(` ✓`))} ${bold('Ready in')} ${bold(
green(`${times}ms`)
`${colors.bold(colors.green(` ✓`))} ${colors.bold('Ready in')} ${colors.bold(
colors.green(`${times}ms`)
)} ${persistentCacheFlag}`,
'\n'
);
Expand Down

0 comments on commit 1b772cb

Please sign in to comment.