refactor(core): Use logger for packages/cli messages (no-changelog) (#9302)

This commit is contained in:
Iván Ovejero 2024-05-03 15:24:27 +02:00 committed by GitHub
parent b65e0e2811
commit 7bda92cc7c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 63 additions and 46 deletions

View file

@ -154,7 +154,7 @@ export abstract class AbstractServer {
this.server.on('error', (error: Error & { code: string }) => { this.server.on('error', (error: Error & { code: string }) => {
if (error.code === 'EADDRINUSE') { if (error.code === 'EADDRINUSE') {
console.log( this.logger.info(
`n8n's port ${PORT} is already in use. Do you have another instance of n8n running already?`, `n8n's port ${PORT} is already in use. Do you have another instance of n8n running already?`,
); );
process.exit(1); process.exit(1);
@ -167,7 +167,7 @@ export abstract class AbstractServer {
await this.setupHealthCheck(); await this.setupHealthCheck();
console.log(`n8n ready on ${ADDRESS}, port ${PORT}`); this.logger.info(`n8n ready on ${ADDRESS}, port ${PORT}`);
} }
async start(): Promise<void> { async start(): Promise<void> {
@ -236,11 +236,11 @@ export abstract class AbstractServer {
await this.configure(); await this.configure();
if (!inTest) { if (!inTest) {
console.log(`Version: ${N8N_VERSION}`); this.logger.info(`Version: ${N8N_VERSION}`);
const defaultLocale = config.getEnv('defaultLocale'); const defaultLocale = config.getEnv('defaultLocale');
if (defaultLocale !== 'en') { if (defaultLocale !== 'en') {
console.log(`Locale: ${defaultLocale}`); this.logger.info(`Locale: ${defaultLocale}`);
} }
await this.externalHooks.run('n8n.ready', [this, config]); await this.externalHooks.run('n8n.ready', [this, config]);

View file

@ -10,6 +10,8 @@ import { Readable } from 'node:stream';
import { inDevelopment } from '@/constants'; import { inDevelopment } from '@/constants';
import { ResponseError } from './errors/response-errors/abstract/response.error'; import { ResponseError } from './errors/response-errors/abstract/response.error';
import Container from 'typedi';
import { Logger } from './Logger';
export function sendSuccessResponse( export function sendSuccessResponse(
res: Response, res: Response,
@ -83,7 +85,7 @@ export function sendErrorResponse(res: Response, error: Error) {
if (isResponseError(error)) { if (isResponseError(error)) {
if (inDevelopment) { if (inDevelopment) {
console.error(picocolors.red(error.httpStatusCode), error.message); Container.get(Logger).error(picocolors.red([error.httpStatusCode, error.message].join(' ')));
} }
//render custom 404 page for form triggers //render custom 404 page for form triggers
@ -112,7 +114,7 @@ export function sendErrorResponse(res: Response, error: Error) {
if (error instanceof NodeApiError) { if (error instanceof NodeApiError) {
if (inDevelopment) { if (inDevelopment) {
console.error(picocolors.red(error.name), error.message); Container.get(Logger).error([picocolors.red(error.name), error.message].join(' '));
} }
Object.assign(response, error); Object.assign(response, error);

View file

@ -637,7 +637,10 @@ function hookFunctionsSaveWorker(): IWorkflowExecuteHooks {
]); ]);
} catch (error) { } catch (error) {
ErrorReporter.error(error); ErrorReporter.error(error);
console.error('There was a problem running hook "workflow.postExecute"', error); Container.get(Logger).error(
'There was a problem running hook "workflow.postExecute"',
error,
);
} }
} }
}, },

View file

@ -211,13 +211,16 @@ export class WorkflowRunner {
]); ]);
} catch (error) { } catch (error) {
ErrorReporter.error(error); ErrorReporter.error(error);
console.error('There was a problem running hook "workflow.postExecute"', error); this.logger.error('There was a problem running hook "workflow.postExecute"', error);
} }
} }
}) })
.catch((error) => { .catch((error) => {
ErrorReporter.error(error); ErrorReporter.error(error);
console.error('There was a problem running internal hook "onWorkflowPostExecute"', error); this.logger.error(
'There was a problem running internal hook "onWorkflowPostExecute"',
error,
);
}); });
} }
@ -411,7 +414,7 @@ export class WorkflowRunner {
try { try {
job = await this.jobQueue.add(jobData, jobOptions); job = await this.jobQueue.add(jobData, jobOptions);
console.log(`Started with job ID: ${job.id.toString()} (Execution ID: ${executionId})`); this.logger.info(`Started with job ID: ${job.id.toString()} (Execution ID: ${executionId})`);
hooks = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerMain( hooks = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerMain(
data.executionMode, data.executionMode,

View file

@ -320,7 +320,7 @@ export abstract class BaseCommand extends Command {
const forceShutdownTimer = setTimeout(async () => { const forceShutdownTimer = setTimeout(async () => {
// In case that something goes wrong with shutdown we // In case that something goes wrong with shutdown we
// kill after timeout no matter what // kill after timeout no matter what
console.log(`process exited after ${this.gracefulShutdownTimeoutInS}s`); this.logger.info(`process exited after ${this.gracefulShutdownTimeoutInS}s`);
const errorMsg = `Shutdown timed out after ${this.gracefulShutdownTimeoutInS} seconds`; const errorMsg = `Shutdown timed out after ${this.gracefulShutdownTimeoutInS} seconds`;
await this.exitWithCrash(errorMsg, new Error(errorMsg)); await this.exitWithCrash(errorMsg, new Error(errorMsg));
}, this.gracefulShutdownTimeoutInS * 1000); }, this.gracefulShutdownTimeoutInS * 1000);

View file

@ -178,11 +178,11 @@ export class ExecuteBatch extends BaseCommand {
if (flags.snapshot !== undefined) { if (flags.snapshot !== undefined) {
if (fs.existsSync(flags.snapshot)) { if (fs.existsSync(flags.snapshot)) {
if (!fs.lstatSync(flags.snapshot).isDirectory()) { if (!fs.lstatSync(flags.snapshot).isDirectory()) {
console.log('The parameter --snapshot must be an existing directory'); this.logger.error('The parameter --snapshot must be an existing directory');
return; return;
} }
} else { } else {
console.log('The parameter --snapshot must be an existing directory'); this.logger.error('The parameter --snapshot must be an existing directory');
return; return;
} }
@ -191,11 +191,11 @@ export class ExecuteBatch extends BaseCommand {
if (flags.compare !== undefined) { if (flags.compare !== undefined) {
if (fs.existsSync(flags.compare)) { if (fs.existsSync(flags.compare)) {
if (!fs.lstatSync(flags.compare).isDirectory()) { if (!fs.lstatSync(flags.compare).isDirectory()) {
console.log('The parameter --compare must be an existing directory'); this.logger.error('The parameter --compare must be an existing directory');
return; return;
} }
} else { } else {
console.log('The parameter --compare must be an existing directory'); this.logger.error('The parameter --compare must be an existing directory');
return; return;
} }
@ -205,7 +205,7 @@ export class ExecuteBatch extends BaseCommand {
if (flags.output !== undefined) { if (flags.output !== undefined) {
if (fs.existsSync(flags.output)) { if (fs.existsSync(flags.output)) {
if (fs.lstatSync(flags.output).isDirectory()) { if (fs.lstatSync(flags.output).isDirectory()) {
console.log('The parameter --output must be a writable file'); this.logger.error('The parameter --output must be a writable file');
return; return;
} }
} }
@ -225,7 +225,7 @@ export class ExecuteBatch extends BaseCommand {
const matchedIds = paramIds.filter((id) => re.exec(id)); const matchedIds = paramIds.filter((id) => re.exec(id));
if (matchedIds.length === 0) { if (matchedIds.length === 0) {
console.log( this.logger.error(
'The parameter --ids must be a list of numeric IDs separated by a comma or a file with this content.', 'The parameter --ids must be a list of numeric IDs separated by a comma or a file with this content.',
); );
return; return;
@ -245,7 +245,7 @@ export class ExecuteBatch extends BaseCommand {
.filter((id) => re.exec(id)), .filter((id) => re.exec(id)),
); );
} else { } else {
console.log('Skip list file not found. Exiting.'); this.logger.error('Skip list file not found. Exiting.');
return; return;
} }
} }
@ -302,18 +302,18 @@ export class ExecuteBatch extends BaseCommand {
if (flags.output !== undefined) { if (flags.output !== undefined) {
fs.writeFileSync(flags.output, this.formatJsonOutput(results)); fs.writeFileSync(flags.output, this.formatJsonOutput(results));
console.log('\nExecution finished.'); this.logger.info('\nExecution finished.');
console.log('Summary:'); this.logger.info('Summary:');
console.log(`\tSuccess: ${results.summary.successfulExecutions}`); this.logger.info(`\tSuccess: ${results.summary.successfulExecutions}`);
console.log(`\tFailures: ${results.summary.failedExecutions}`); this.logger.info(`\tFailures: ${results.summary.failedExecutions}`);
console.log(`\tWarnings: ${results.summary.warningExecutions}`); this.logger.info(`\tWarnings: ${results.summary.warningExecutions}`);
console.log('\nNodes successfully tested:'); this.logger.info('\nNodes successfully tested:');
Object.entries(results.coveredNodes).forEach(([nodeName, nodeCount]) => { Object.entries(results.coveredNodes).forEach(([nodeName, nodeCount]) => {
console.log(`\t${nodeName}: ${nodeCount}`); this.logger.info(`\t${nodeName}: ${nodeCount}`);
}); });
console.log('\nCheck the JSON file for more details.'); this.logger.info('\nCheck the JSON file for more details.');
} else if (flags.shortOutput) { } else if (flags.shortOutput) {
console.log( this.logger.info(
this.formatJsonOutput({ this.formatJsonOutput({
...results, ...results,
executions: results.executions.filter( executions: results.executions.filter(
@ -322,7 +322,7 @@ export class ExecuteBatch extends BaseCommand {
}), }),
); );
} else { } else {
console.log(this.formatJsonOutput(results)); this.logger.info(this.formatJsonOutput(results));
} }
await this.stopProcess(true); await this.stopProcess(true);

View file

@ -76,7 +76,7 @@ export class Start extends BaseCommand {
const editorUrl = Container.get(UrlService).baseUrl; const editorUrl = Container.get(UrlService).baseUrl;
open(editorUrl, { wait: true }).catch(() => { open(editorUrl, { wait: true }).catch(() => {
console.log( this.logger.info(
`\nWas not able to open URL in browser. Please open manually by visiting:\n${editorUrl}\n`, `\nWas not able to open URL in browser. Please open manually by visiting:\n${editorUrl}\n`,
); );
}); });
@ -339,7 +339,7 @@ export class Start extends BaseCommand {
} }
async catch(error: Error) { async catch(error: Error) {
console.log(error.stack); if (error.stack) this.logger.error(error.stack);
await this.exitWithCrash('Exiting due to an error.', error); await this.exitWithCrash('Exiting due to an error.', error);
} }
} }

View file

@ -28,24 +28,24 @@ export class UpdateWorkflowCommand extends BaseCommand {
const { flags } = await this.parse(UpdateWorkflowCommand); const { flags } = await this.parse(UpdateWorkflowCommand);
if (!flags.all && !flags.id) { if (!flags.all && !flags.id) {
console.info('Either option "--all" or "--id" have to be set!'); this.logger.error('Either option "--all" or "--id" have to be set!');
return; return;
} }
if (flags.all && flags.id) { if (flags.all && flags.id) {
console.info( this.logger.error(
'Either something else on top should be "--all" or "--id" can be set never both!', 'Either something else on top should be "--all" or "--id" can be set never both!',
); );
return; return;
} }
if (flags.active === undefined) { if (flags.active === undefined) {
console.info('No update flag like "--active=true" has been set!'); this.logger.error('No update flag like "--active=true" has been set!');
return; return;
} }
if (!['false', 'true'].includes(flags.active)) { if (!['false', 'true'].includes(flags.active)) {
console.info('Valid values for flag "--active" are only "false" or "true"!'); this.logger.error('Valid values for flag "--active" are only "false" or "true"!');
return; return;
} }

View file

@ -14,9 +14,11 @@ import { MfaService } from '@/Mfa/mfa.service';
import { Push } from '@/push'; import { Push } from '@/push';
import { CacheService } from '@/services/cache/cache.service'; import { CacheService } from '@/services/cache/cache.service';
import { PasswordUtility } from '@/services/password.utility'; import { PasswordUtility } from '@/services/password.utility';
import Container from 'typedi';
import { Logger } from '@/Logger';
if (!inE2ETests) { if (!inE2ETests) {
console.error('E2E endpoints only allowed during E2E tests'); Container.get(Logger).error('E2E endpoints only allowed during E2E tests');
process.exit(1); process.exit(1);
} }
@ -149,7 +151,9 @@ export class E2EController {
`DELETE FROM ${table}; DELETE FROM sqlite_sequence WHERE name=${table};`, `DELETE FROM ${table}; DELETE FROM sqlite_sequence WHERE name=${table};`,
); );
} catch (error) { } catch (error) {
console.warn('Dropping Table for E2E Reset error: ', error); Container.get(Logger).warn('Dropping Table for E2E Reset error', {
error: error as Error,
});
} }
} }
} }

View file

@ -10,6 +10,8 @@ import { MessageEventBusDestination } from './MessageEventBusDestination.ee';
import { isLogStreamingEnabled } from '../MessageEventBus/MessageEventBusHelper'; import { isLogStreamingEnabled } from '../MessageEventBus/MessageEventBusHelper';
import { eventMessageGenericDestinationTestEvent } from '../EventMessageClasses/EventMessageGeneric'; import { eventMessageGenericDestinationTestEvent } from '../EventMessageClasses/EventMessageGeneric';
import type { MessageEventBus, MessageWithCallback } from '../MessageEventBus/MessageEventBus'; import type { MessageEventBus, MessageWithCallback } from '../MessageEventBus/MessageEventBus';
import Container from 'typedi';
import { Logger } from '@/Logger';
export const isMessageEventBusDestinationSyslogOptions = ( export const isMessageEventBusDestinationSyslogOptions = (
candidate: unknown, candidate: unknown,
): candidate is MessageEventBusDestinationSyslogOptions => { ): candidate is MessageEventBusDestinationSyslogOptions => {
@ -63,7 +65,7 @@ export class MessageEventBusDestinationSyslog
}); });
this.logger.debug(`MessageEventBusDestinationSyslog with id ${this.getId()} initialized`); this.logger.debug(`MessageEventBusDestinationSyslog with id ${this.getId()} initialized`);
this.client.on('error', function (error) { this.client.on('error', function (error) {
console.error(error); Container.get(Logger).error(`${error.message}`);
}); });
} }

View file

@ -180,7 +180,7 @@ export class MessageEventBusDestinationWebhook
try { try {
JSON.parse(this.jsonQuery); JSON.parse(this.jsonQuery);
} catch { } catch {
console.log('JSON parameter need to be an valid JSON'); this.logger.error('JSON parameter need to be an valid JSON');
} }
this.axiosRequestOptions.params = jsonParse(this.jsonQuery); this.axiosRequestOptions.params = jsonParse(this.jsonQuery);
} }
@ -198,7 +198,7 @@ export class MessageEventBusDestinationWebhook
try { try {
JSON.parse(this.jsonHeaders); JSON.parse(this.jsonHeaders);
} catch { } catch {
console.log('JSON parameter need to be an valid JSON'); this.logger.error('JSON parameter need to be an valid JSON');
} }
this.axiosRequestOptions.headers = jsonParse(this.jsonHeaders); this.axiosRequestOptions.headers = jsonParse(this.jsonHeaders);
} }

View file

@ -1,10 +1,12 @@
import { Help } from '@oclif/core'; import { Help } from '@oclif/core';
import Container from 'typedi';
import { Logger } from 'winston';
// oclif expects a default export // oclif expects a default export
// eslint-disable-next-line import/no-default-export // eslint-disable-next-line import/no-default-export
export default class CustomHelp extends Help { export default class CustomHelp extends Help {
async showRootHelp() { async showRootHelp() {
console.log( Container.get(Logger).info(
'You can find up to date information about the CLI here:\nhttps://docs.n8n.io/hosting/cli-commands/', 'You can find up to date information about the CLI here:\nhttps://docs.n8n.io/hosting/cli-commands/',
); );
} }

View file

@ -14,10 +14,14 @@ import { getN8nPackageJson, inDevelopment } from '@/constants';
import type { WorkflowEntity } from '@db/entities/WorkflowEntity'; import type { WorkflowEntity } from '@db/entities/WorkflowEntity';
import type { RiskReporter, Risk, n8n } from '@/security-audit/types'; import type { RiskReporter, Risk, n8n } from '@/security-audit/types';
import { isApiEnabled } from '@/PublicApi'; import { isApiEnabled } from '@/PublicApi';
import { Logger } from '@/Logger';
@Service() @Service()
export class InstanceRiskReporter implements RiskReporter { export class InstanceRiskReporter implements RiskReporter {
constructor(private readonly instanceSettings: InstanceSettings) {} constructor(
private readonly instanceSettings: InstanceSettings,
private readonly logger: Logger,
) {}
async report(workflows: WorkflowEntity[]) { async report(workflows: WorkflowEntity[]) {
const unprotectedWebhooks = this.getUnprotectedWebhookNodes(workflows); const unprotectedWebhooks = this.getUnprotectedWebhookNodes(workflows);
@ -174,7 +178,7 @@ export class InstanceRiskReporter implements RiskReporter {
versions = await this.getNextVersions(localVersion).then((v) => this.removeIconData(v)); versions = await this.getNextVersions(localVersion).then((v) => this.removeIconData(v));
} catch (error) { } catch (error) {
if (inDevelopment) { if (inDevelopment) {
console.error('Failed to fetch n8n versions. Skipping outdated instance report...'); this.logger.error('Failed to fetch n8n versions. Skipping outdated instance report...');
} }
return null; return null;
} }

View file

@ -398,9 +398,6 @@ describe('PATCH /credentials/:id', () => {
.patch(`/credentials/${savedCredential.id}`) .patch(`/credentials/${savedCredential.id}`)
.send(invalidPayload); .send(invalidPayload);
if (response.statusCode === 500) {
console.log(response.statusCode, response.body);
}
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
} }
}); });

View file

@ -66,7 +66,7 @@ describe('RedisService', () => {
const mockHandler = jest.fn(); const mockHandler = jest.fn();
mockHandler.mockImplementation((stream: string, id: string, message: string[]) => { mockHandler.mockImplementation((stream: string, id: string, message: string[]) => {
console.log('Received message', stream, id, message); Container.get(Logger).info('Received message', { stream, id, message });
}); });
consumer.addMessageHandler('some handler', mockHandler); consumer.addMessageHandler('some handler', mockHandler);