将Winston日志添加到Nuxt3

huangapple go评论98阅读模式
英文:

Add Winston Logging to Nuxt3

问题

Winston是一个我们想要在我们的Nuxt3应用程序中使用的日志记录框架,但是Nuxt中的Winston包仍然只适用于Nuxt2。关于使这个特定组合的工具工作的文档很有限。

我尝试了引入Nuxt Winston包(https://www.npmjs.com/package/nuxt-winston-log),但并没有如预期那样工作。

请注意,这仅适用于Nuxt的SSR功能(“服务器端渲染”)。我并不试图让Winston从客户端记录日志。

英文:

Winston is a logging framework that we want to use in our Nuxt3 application, but the Winston package from Nuxt is still only available for Nuxt2. There is sparse documentation on getting this particular combination of tools working.

I tried pulling in the Nuxt Winston package anyway (https://www.npmjs.com/package/nuxt-winston-log), but that did not work as expected.

Note that this is only for logging in Nuxt's SSR functionality ("server-side rendering"). I'm not trying to get Winston to log from the client side.

答案1

得分: 2

Step 1

运行 yarn add winston

Step 2

创建一个服务器端插件。在文件名前面加上00.,因为插件按字母顺序加载,您可能希望在其他插件中使用日志记录。以.server.ts结尾,以便它只在服务器端运行;Winston 不适用于客户端。
文件名:plugins/00.logging.server.ts

import { defineNuxtPlugin } from "#app";
import winston from "winston";

export default defineNuxtPlugin(() => {
  const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(winston.format.printf((event) => {
      return `${JSON.stringify({ ...event, timestamp: new Date().toISOString() }, null, 4)}\n`;
    })),
    defaultMeta: { service: 'myappname' },
    transports: [
      new winston.transports.Console()
    ],
  });

  return {
    provide: {
      logger
    }
  }
});

Step 3 (Optional)

为了方便使用,以便可以从前端和后端都调用单个日志记录函数,构建一些可组合函数。
文件名:composables/logging.ts

export function logServerError(err: any, message?: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("error", message, err);
  } else {
    console.error("We Have Encountered an ERROR: ", err);
  }
}

export function logServerWarn(message: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("warn", message);
  } else {
    console.warn(message);
  }
}

export function logServerInfo(message: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("info", message);
  } else {
    console.info(message);
  }
}

Step 4 (If you did Step 3)

使用日志记录器。文件名:plugins/50.myplugin.js

export default defineNuxtPlugin(async (nuxtApp) => {

  // do stuff to setup my app

  // do more stuff

  logServerInfo("Plugin operations complete");
});

Notes

  • 可能会收到关于对 nuxtApp.$logger.log 的 TS 警告。在所有这些复杂操作之后,我只是添加了 // @ts-ignore 并继续进行。
  • 插件的文件名如果您的其他插件不需要日志记录,则无关紧要。
  • 您必须从插件本身提供日志记录器,而不是 logger.log 函数。
  • 如果您想要不同的输出(例如输出到文件而不是控制台),请参考 Winston 文档:https://github.com/winstonjs/winston
英文:

So in this case, we just want to use Winston directly:

Step 1

Run yarn add winston

Step 2

Create a server-side plugin. Prefix the file with 00. since plugins are loaded in alphabetical order, and you'll likely want your logging available in your other plugins. Suffix with .server.ts so that this only tries to run on the server side; Winston isn't meant for use on client side.
Filename: plugins/00.logging.server.ts

import { defineNuxtPlugin } from "#app";
import winston from "winston";

export default defineNuxtPlugin(() => {
  const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(winston.format.printf((event) => {
      return `${JSON.stringify({ ...event, timestamp: new Date().toISOString() }, null, 4)}\n`;
    })),
    defaultMeta: { service: 'myappname' },
    transports: [
      new winston.transports.Console()
    ],
  });

  return {
    provide: {
      logger
    }
  }
});

Step 3 (Optional)

For ease of use and so that a single logging function can be called from both the frontend and the backend, build some composables.
Filename: composables/logging.ts

export function logServerError(err: any, message?: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("error", message, err);
  } else {
    console.error("We Have Encountered an ERROR: ", err);
  }
}

export function logServerWarn(message: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("warn", message);
  } else {
    console.warn(message);
  }
}

export function logServerInfo(message: string) {
  const nuxtApp = useNuxtApp();
  if (process?.server && nuxtApp.$logger) {
    nuxtApp.$logger.log("info", message);
  } else {
    console.info(message);
  }
}

Step 4 (If you did Step 3)

Use the logger. Filename: plugins/50.myplugin.js

export default defineNuxtPlugin(async (nuxtApp) => {

  // do stuff to setup my app

  // do more stuff

  logServerInfo("Plugin operations complete");
});

Notes

  • You might get TS warnings on the references to nuxtApp.$logger.log. After all this rigamarole, I just put // @ts-ignore and moved on.
  • The filename of the plugin doesn't matter if none of your other plugins needs logging.
  • You have to provide the logger itself from the plugin, not the logger.log function
  • If you want different output (say to a file instead of the console), reference the Winston documentation: https://github.com/winstonjs/winston

答案2

得分: 0

你链接的这个包与Nuxt2兼容,但没有列出Nuxt3作为兼容的框架。此外,已经有3年没有提交了。我在该包的问题中找到了一个与此相关的问题,官方反馈表示需要进行一些重构:https://github.com/aaronransley/nuxt-winston-log/issues/10

我建议你要么在那个帖子中发表评论,要么分支该项目并自行添加兼容性。你也可以联系作者,看是否可以与他们合作创建一个Nuxt3版本。

英文:

The package you've linked to is compatible with Nuxt2 and doesn't list Nuxt3 as a compatible framework. In addition, there's been no commits for 3+ years. I found an issue on that package addressing this very thing with official feedback saying it would require some reworking: https://github.com/aaronransley/nuxt-winston-log/issues/10

I would recommend either commenting in that thread, or forking the project and adding compatibility yourself. You may also want to contact the author about contributing with them towards a Nuxt3 version.

答案3

得分: 0

在这种情况下,我们可以尝试使用 nuxt3-winston-log

nuxt3-winston-log 是一个用于在 Nuxt 3.x 应用程序中添加基于 winston 的日志记录的 Nuxt 模块。它非常简单易用,只需使用 console.log 和 console.error 来记录所有内容。

步骤 1
安装 npm 包

yarn add nuxt3-winston-log

步骤 2
编辑你的 nuxt.config.js 文件以添加模块

{
  modules: ["nuxt3-winston-log"];
}

步骤 3
根据需要使用 nuxt3WinstonLog 键更改选项

我们可以在 nuxt3-winston-log 中查看更多详细信息。

英文:

in this case , we can try nuxt3-winston-log

nuxt3-winston-log is a Nuxt 3.x modules to add winston-powered logging to your Nuxt application . it is very simple to use , just use console.log and console.error to log everythings .

Step 1
Install npm package

yarn add nuxt3-winston-log

Step 2
Edit your nuxt.config.js file to add module

{
  modules: ["nuxt3-winston-log"];
}

Step 3
Change options using the nuxt3WinstonLog key as needed

we can see more details in nuxt3-winston-log

huangapple
  • 本文由 发表于 2023年7月14日 02:12:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定