NodeJS 打开遥测使Next.js初始化极其缓慢

e3bfsja2  于 2023-01-20  发布在  Node.js
关注(0)|答案(1)|浏览(145)

当通过node -rnode --require初始化Nextjs时,应用程序需要4-5分钟加载。遥测脚本在前5秒内加载,因此此问题可能与Nextjs或节点有关。这与不带节点的调用相比,需要模块的30秒加载时间。
无节点时需要模块:

"dev": "env-cmd -f environments/.env.development next dev",

具有节点所需模块:

"dev": "env-cmd -f environments/.env.development node --require ./tracing.js ./node_modules/next/dist/bin/next dev",

此实现基于ross-hagan's blog about instrument-nextjs-opentelemetry
定制服务器的替代方案
我最初使用一个完全独立的tracing.js脚本,其中包含start.js脚本的内容,但没有startServer调用。
这将遥测SDK的启动与服务器分离开来,然后您可以在启动Next应用程序之前使用node --require(-r)加载到模块中,从而保留Next.js内置的启动行为。
在您的npm中,运行package.json中的dev脚本,如下所示:
节点-r跟踪. js./节点模块/.bin/下一个开发
我放弃了这个方法,因为我在Dockerfile中运行node命令时遇到了一些挫折,因为这是为Google Kubernetes Engine运行时设计的。
看看这样做是否对您有效,因为Next.js自定义服务器附带了一些文档中记录的后果!
我尝试了两个单独的tracing.js,但在减少加载时间方面没有成功。
tracing.js由开放遥测提供:

/* tracing.js */

// Require dependencies
const opentelemetry = require("@opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");
const { diag, DiagConsoleLogger, DiagLogLevel } = require('@opentelemetry/api');

// For troubleshooting, set the log level to DiagLogLevel.DEBUG
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);

const sdk = new opentelemetry.NodeSDK({
  traceExporter: new opentelemetry.tracing.ConsoleSpanExporter(),
  instrumentations: [getNodeAutoInstrumentations()]
});

sdk.start()

以及为jaeger定制的tracing.js

const process = require('process');
const opentelemetry = require('@opentelemetry/sdk-node');
const {
  getNodeAutoInstrumentations,
} = require('@opentelemetry/auto-instrumentations-node');
const { Resource } = require('@opentelemetry/resources');
const {
  SemanticResourceAttributes,
} = require('@opentelemetry/semantic-conventions');
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');

const hostName = process.env.OTEL_TRACE_HOST || 'localhost';

const options = {
  tags: [],
  endpoint: `http://${hostName}:1234/api/traces`,
};
const traceExporter = new JaegerExporter(options);

// configure the SDK to export telemetry data to the console
// enable all auto-instrumentations from the meta package
const sdk = new opentelemetry.NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'my_app',
  }),
  traceExporter,
  instrumentations: [
    getNodeAutoInstrumentations({
      // Each of the auto-instrumentations
      // can have config set here or you can
      // npm install each individually and not use the auto-instruments
      '@opentelemetry/instrumentation-http': {
        ignoreIncomingPaths: [
          // Pattern match to filter endpoints
          // that you really want to stop altogether
          '/ping',

          // You can filter conditionally
          // Next.js gets a little too chatty
          // if you trace all the incoming requests
          ...(process.env.NODE_ENV !== 'production'
            ? [/^\/_next\/static.*/]
            : []),
        ],

        // This gives your request spans a more meaningful name
        // than `HTTP GET`
        requestHook: (span, request) => {
          span.setAttributes({
            name: `${request.method} ${request.url || request.path}`,
          });
        },

        // Re-assign the root span's attributes
        startIncomingSpanHook: (request) => {
          return {
            name: `${request.method} ${request.url || request.path}`,
            'request.path': request.url || request.path,
          };
        },
      },
    }),
  ],
});

// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk
  .start()
  .then(() => console.log('Tracing initialized'))
  .catch((error) =>
    console.log('Error initializing tracing and starting server', error)
  );

// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
  sdk
    .shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error) => console.log('Error terminating tracing', error))
    .finally(() => process.exit(0));
});

另外,先构建然后提供服务也不会加快加载时间。

lh80um4z

lh80um4z1#

查看您是否遇到了此处报告的问题[@opentelemetry/instrumentation] require performance grows linearly with each instrumentation plugin。在此问题中,有一个错误导致仪器重复层叠在其自身之上。他们已经修复了此问题。
另请参见此answer

相关问题