Skip to content

Commit

Permalink
fix(serve-runtime): construct logger during init (#7155)
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan authored Jun 26, 2024
1 parent 2eaea7e commit f985978
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 39 deletions.
6 changes: 6 additions & 0 deletions .changeset/moody-cameras-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-mesh/serve-runtime': patch
'@graphql-mesh/utils': patch
---

Construct Logger during Mesh init
67 changes: 45 additions & 22 deletions packages/legacy/utils/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,21 @@ export const errorColor: MessageTransformer = msg => ANSI_CODES.red + msg + ANSI
export const debugColor: MessageTransformer = msg => ANSI_CODES.magenta + msg + ANSI_CODES.reset;
export const titleBold: MessageTransformer = msg => ANSI_CODES.bold + msg + ANSI_CODES.reset;

export enum LogLevel {
debug = 0,
info = 1,
warn = 2,
error = 3,
silent = 4,
}

const noop: VoidFunction = () => {};

export class DefaultLogger implements Logger {
constructor(public name?: string) {}
constructor(
public name?: string,
public logLevel = process.env.DEBUG === '1' ? LogLevel.debug : LogLevel.info,
) {}

private getLoggerMessage({ args = [], trim = !this.isDebug }: { args: any[]; trim?: boolean }) {
return args
Expand Down Expand Up @@ -76,70 +89,80 @@ export class DefaultLogger implements Logger {
}

log(...args: any[]) {
if (this.logLevel > LogLevel.info) {
return noop;
}
const message = this.getLoggerMessage({
args,
});
const fullMessage = `${this.prefix} ${message}`;
if (typeof process === 'object') {
process.stderr.write(fullMessage + '\n');
} else {
console.log(fullMessage);
if (process?.stderr?.write(fullMessage + '\n')) {
return;
}
console.log(fullMessage);
}

warn(...args: any[]) {
if (this.logLevel > LogLevel.warn) {
return noop;
}
const message = this.getLoggerMessage({
args,
});
const fullMessage = `${this.prefix} ⚠️ ${warnColor(message)}`;
if (typeof process === 'object') {
process.stderr.write(fullMessage + '\n');
} else {
console.warn(fullMessage);
if (process?.stderr?.write(fullMessage + '\n')) {
return;
}
console.warn(fullMessage);
}

info(...args: any[]) {
if (this.logLevel > LogLevel.info) {
return noop;
}
const message = this.getLoggerMessage({
args,
});
const fullMessage = `${this.prefix} 💡 ${infoColor(message)}`;
if (typeof process === 'object') {
process.stderr.write(fullMessage + '\n');
} else {
console.info(fullMessage);
if (process?.stderr?.write(fullMessage + '\n')) {
return;
}
console.info(fullMessage);
}

error(...args: any[]) {
if (this.logLevel > LogLevel.error) {
return noop;
}
const message = this.getLoggerMessage({
args,
trim: false,
});
const fullMessage = `${this.prefix} 💥 ${errorColor(message)}`;
if (typeof process === 'object') {
process.stderr.write(fullMessage + '\n');
} else {
console.error(fullMessage);
if (process?.stderr?.write(fullMessage + '\n')) {
return;
}
console.error(fullMessage);
}

debug(...lazyArgs: LazyLoggerMessage[]) {
if (this.logLevel > LogLevel.debug) {
return noop;
}
if (this.isDebug) {
const message = this.handleLazyMessage({
lazyArgs,
});
const fullMessage = `${this.prefix} 🐛 ${debugColor(message)}`;
if (typeof process === 'object') {
process.stderr.write(fullMessage + '\n');
} else {
console.debug(fullMessage);
if (process?.stderr?.write(fullMessage + '\n')) {
return;
}
console.debug(fullMessage);
}
}

child(name: string): Logger {
return new DefaultLogger(this.name ? `${this.name} - ${name}` : name);
return new DefaultLogger(this.name ? `${this.name} - ${name}` : name, this.logLevel);
}

addPrefix(prefix: string): Logger {
Expand Down
19 changes: 13 additions & 6 deletions packages/serve-runtime/src/createServeRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { Logger, OnDelegateHook, OnFetchHook } from '@graphql-mesh/types';
import {
DefaultLogger,
getHeadersObj,
LogLevel,
mapMaybePromise,
wrapFetchWithHooks,
} from '@graphql-mesh/utils';
Expand All @@ -41,16 +42,23 @@ export function createServeRuntime<TContext extends Record<string, any> = Record
config: MeshServeConfig<TContext>,
) {
let fetchAPI: Partial<FetchAPI> = config.fetchAPI;
// eslint-disable-next-line prefer-const
let logger: Logger;
if (config.logging == null) {
logger = new DefaultLogger();
} else if (typeof config.logging === 'boolean') {
logger = config.logging ? new DefaultLogger() : new DefaultLogger('', LogLevel.silent);
}
if (typeof config.logging === 'number') {
logger = new DefaultLogger(undefined, config.logging);
} else if (typeof config.logging === 'object') {
logger = config.logging;
}
const onFetchHooks: OnFetchHook<MeshServeContext>[] = [];
const wrappedFetchFn = wrapFetchWithHooks(onFetchHooks);

const configContext: MeshServeConfigContext = {
fetch: wrappedFetchFn,
get logger() {
return logger;
},
logger,
cwd: globalThis.process?.cwd(),
cache: 'cache' in config ? config.cache : undefined,
pubsub: 'pubsub' in config ? config.pubsub : undefined,
Expand Down Expand Up @@ -153,7 +161,7 @@ export function createServeRuntime<TContext extends Record<string, any> = Record
// @ts-expect-error PromiseLike is not compatible with Promise
schema: schemaFetcher,
fetchAPI: config.fetchAPI,
logging: config.logging == null ? new DefaultLogger() : config.logging,
logging: logger,
plugins: [
defaultMeshPlugin,
unifiedGraphPlugin,
Expand Down Expand Up @@ -197,7 +205,6 @@ export function createServeRuntime<TContext extends Record<string, any> = Record
});

fetchAPI ||= yoga.fetchAPI;
logger = yoga.logger as Logger;

Object.defineProperties(yoga, {
invalidateUnifiedGraph: {
Expand Down
26 changes: 15 additions & 11 deletions packages/serve-runtime/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import {
import type {
BatchingOptions,
FetchAPI,
LogLevel,
YogaInitialContext,
YogaLogger,
YogaMaskedErrorOpts,
Plugin as YogaPlugin,
YogaServerOptions,
} from 'graphql-yoga';
import { Plugin as EnvelopPlugin } from '@envelop/core';
import { Transport, TransportsOption, UnifiedGraphPlugin } from '@graphql-mesh/fusion-runtime';
// eslint-disable-next-line import/no-extraneous-dependencies
import { KeyValueCache, Logger, MeshFetch, MeshPubSub, OnFetchHook } from '@graphql-mesh/types';
import { HTTPExecutorOptions } from '@graphql-tools/executor-http';
import { IResolvers } from '@graphql-tools/utils';
import { CORSPluginOptions } from '@whatwg-node/server';
import type { Plugin as EnvelopPlugin } from '@envelop/core';
import type { Transport, TransportsOption, UnifiedGraphPlugin } from '@graphql-mesh/fusion-runtime';
import type {
KeyValueCache,
Logger,
MeshFetch,
MeshPubSub,
OnFetchHook,
} from '@graphql-mesh/types';
import type { LogLevel } from '@graphql-mesh/utils';
import type { HTTPExecutorOptions } from '@graphql-tools/executor-http';
import type { IResolvers } from '@graphql-tools/utils';
import type { CORSPluginOptions } from '@whatwg-node/server';
import type { UnifiedGraphConfig } from './handleUnifiedGraphConfig.js';

export { UnifiedGraphConfig };
Expand Down Expand Up @@ -159,7 +163,7 @@ interface MeshServeConfigWithoutSource<TContext extends Record<string, any>> {
*
* @default true
*/
logging?: boolean | YogaLogger | LogLevel | undefined;
logging?: boolean | Logger | LogLevel | undefined;
/**
* Endpoint of the GraphQL API.
*/
Expand Down

0 comments on commit f985978

Please sign in to comment.