Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(builder): support custom logger #4522

Merged
merged 3 commits into from
Aug 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/shy-countries-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@modern-js/builder-shared': patch
'@modern-js/plugin-tailwindcss': patch
'@modern-js/module-tools-docs': patch
'@modern-js/main-doc': patch
'@modern-js/utils': patch
'@modern-js/doc-core': patch
---

feat(builder): support custom logger in dev server

feat(builder): 支持自定义 logger
9 changes: 7 additions & 2 deletions packages/builder/builder-shared/src/devServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
} from './types';
import type { ModernDevServerOptions, Server } from '@modern-js/server';
import { merge } from '@modern-js/utils/lodash';
import { logger, debug } from './logger';
import { logger as defaultLogger, debug } from './logger';
import { DEFAULT_PORT } from './constants';
import { createAsyncHook } from './createHook';
import { getServerOptions, printServerURLs } from './prodServer';
Expand Down Expand Up @@ -95,10 +95,14 @@ export async function startDevServer<
printURLs = true,
strictPort = false,
serverOptions = {},
logger: customLogger,
getPortSilently,
}: StartDevServerOptions & {
defaultPort?: number;
} = {},
) {
const logger = customLogger ?? defaultLogger;

logger.info('Starting dev server...');

if (!process.env.NODE_ENV) {
Expand All @@ -112,6 +116,7 @@ export async function startDevServer<

const port = await getPort(builderConfig.dev?.port || DEFAULT_PORT, {
strictPort,
slient: getPortSilently,
});

const host =
Expand Down Expand Up @@ -165,7 +170,7 @@ export async function startDevServer<
}
}

await printServerURLs(urls, 'Dev server');
await printServerURLs(urls, 'Dev server', logger);
}

await options.context.hooks.onAfterStartDevServerHook.call({ port });
Expand Down
8 changes: 6 additions & 2 deletions packages/builder/builder-shared/src/prodServer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import prodServer, { type ModernServerOptions } from '@modern-js/prod-server';
import { logger } from './logger';
import prodServer, {
Logger,
type ModernServerOptions,
} from '@modern-js/prod-server';
import { logger as defaultLogger } from './logger';
import { DEFAULT_PORT } from './constants';
import type {
BuilderContext,
Expand Down Expand Up @@ -32,6 +35,7 @@ export const getServerOptions = (
export async function printServerURLs(
urls: Array<{ url: string; label: string }>,
name = 'Server',
logger: Logger = defaultLogger,
) {
const { chalk } = await import('@modern-js/utils');
let message = `${name} running at:\n\n`;
Expand Down
3 changes: 3 additions & 0 deletions packages/builder/builder-shared/src/types/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Compiler, MultiCompiler } from 'webpack';
import type { BuilderMode, CreateBuilderOptions } from './builder';
import type { Server, ModernDevServerOptions } from '@modern-js/server';
import type { AddressUrl } from '@modern-js/utils';
import { Logger } from '@modern-js/prod-server';

export type Bundler = 'webpack' | 'rspack';

Expand All @@ -12,7 +13,9 @@ export type CreateCompilerOptions = { watch?: boolean };
export type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
printURLs?: boolean | ((urls: AddressUrl[]) => AddressUrl[]);
logger?: Logger;
strictPort?: boolean;
getPortSilently?: boolean;
sanyuan0704 marked this conversation as resolved.
Show resolved Hide resolved
serverOptions?: Partial<Omit<ModernDevServerOptions, 'config'>> & {
config?: Partial<ModernDevServerOptions['config']>;
};
Expand Down
51 changes: 50 additions & 1 deletion packages/document/builder-doc/docs/en/api/builder-instance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
// passing through the build-independent dev server configuration
serverOptions?: Partial<ModernDevServerOptions>;
// Whether to get the port silently, the default is false
getPortSliently?: boolean;
// custom logger
logger?: Logger;
};

type StartServerResult = {
Expand Down Expand Up @@ -293,6 +297,52 @@ await builder.startDevServer({
});
```

### Get Port Silently

In some cases, the default startup port number is already occupied. In this situation, Builder will automatically increment the port number until it finds an available one. This process will output a prompt log. If you do not want this log, you can set `getPortSliently` to `true`.

```ts
await builder.startDevServer({
getPortSliently: true,
});
```

### Custom Logger

By default, Builder uses `@modern-js/utils/logger` to output logs. You can customize the log output object through the `logger` parameter.

```ts
const customLogger = {
// You need to define the following methods
info(msg: string) {
console.log(msg);
},
error(msg: string) {
console.error(msg);
},
warn(msg: string) {
console.warn(msg);
},
success(msg: string) {
console.log(`✅ msg`);
},
debug(msg: string) {
if (process.env.DEBUG) {
console.log(msg);
}
},
log(msg: string) {
console.log(msg);
};
}

await builder.startDevServer({
logger: customLogger,
});
```

Then Builder will use the custom logger to output logs.

## builder.serve

Start a server to preview the production build locally. This method should be executed after `builder.build`.
Expand Down Expand Up @@ -332,7 +382,6 @@ console.log(port); // 8080
await server.close();
```


## builder.createCompiler

Create a Compiler object.
Expand Down
52 changes: 50 additions & 2 deletions packages/document/builder-doc/docs/zh/api/builder-instance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
// 透传与构建无关的 dev server 配置
serverOptions?: Partial<ModernDevServerOptions>;
// 是否在启动时静默获取端口号,默认为 false
getPortSliently?: boolean;
// 自定义日志输出对象
logger?: Logger;
};

type StartServerResult = {
Expand Down Expand Up @@ -293,6 +297,52 @@ await builder.startDevServer({
});
```

### 静默获取端口号

某些情况下,默认启动的端口号已经被占用,此时 Builder 会自动递增端口号,直至找到一个可用端口。这个过程会输出提示日志,如果你不希望这段日志,可以将 `getPortSliently` 设置为 `true`

```ts
await builder.startDevServer({
getPortSliently: true,
});
```

### 自定义日志输出对象

默认情况下,Builder 会使用 `@modern-js/utils/logger` 来输出日志,你可以通过 `logger` 参数来自定义日志输出对象。

```ts
const customLogger = {
// 你需要定义以下的方法
info(msg: string) {
console.log(msg);
},
error(msg: string) {
console.error(msg);
},
warn(msg: string) {
console.warn(msg);
},
success(msg: string) {
console.log(`✅ msg`);
},
debug(msg: string) {
if (process.env.DEBUG) {
console.log(msg);
}
},
log(msg: string) {
console.log(msg);
};
}

await builder.startDevServer({
logger: customLogger,
});
```

这样,Builder 会使用你自定义的日志输出对象来输出日志。

## builder.serve

在本地启动 Server 来预览生产环境构建的产物,需要在 `builder.build` 方法之后执行。
Expand All @@ -317,7 +367,6 @@ function server(): Promise<StartServerResult>;
await builder.serve();
```


`serve` 会返回以下参数:

- `urls`:访问 Server 的 URLs
Expand All @@ -333,7 +382,6 @@ console.log(port); // 8080
await server.close();
```


## builder.createCompiler

创建一个 compiler 对象。
Expand Down
4 changes: 3 additions & 1 deletion packages/toolkit/utils/src/cli/port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ export const getPort = async (
{
tryLimits = 20,
strictPort = false,
slient = false,
}: {
tryLimits?: number;
strictPort?: boolean;
slient?: boolean;
} = {},
): Promise<number> => {
if (typeof port === 'string') {
Expand Down Expand Up @@ -63,7 +65,7 @@ export const getPort = async (
throw new Error(
`Port "${original}" is occupied, please choose another one.`,
);
} else {
} else if (!slient) {
logger.info(
`Something is already running on port ${original}. ${chalk.yellow(
`Use port ${port} instead.`,
Expand Down