无法确定“pino-pretty”的传输目标

我正在尝试使用 pino 库,但出现错误

我的代码

我创建了一个 logger.js 文件并从 node_module 导入了 pino 并添加了 pino-pretty 的传输。

logger.js

   import pino from "pino";
    const logger = pino({
      transport: {
        target: "pino-pretty",
        options: {
          colorize: true,
        },
      },
    });
    export default logger;

我创建了一个数据库文件并从记录器文件中导入了 pino 并使用 info 函数来显示我的错误。

数据库.js

import mongoose from "mongoose";
import logger from "./logger";
const DB_CONNECTION_STRING =
  process.env.DB_CONNECTION_STRING ||
  "mongodb://localhost:27017/*******";
try {
    await mongoose.connect(DB_CONNECTION_STRING);
    logger.info("Connect to database");
  } catch (e) {
    logger.error(e, "Failed to connect to database. Goodbye");
    process.exit(1);
  }

enter image description here

stack overflow unable to determine transport target for "pino-pretty"
原文答案

答案:

作者头像

如果你没有安装它,你必须安装 pino-pretty

npm i pino-pretty
作者头像

您的 package.json 中可能缺少 pino-pretty ,您是否尝试将其添加为依赖项?

作者头像

最好的方法似乎是通过管道输出到 CLI 工具来使用它。

所以不要在你的项目中导入它,并将它添加到你的 npm 脚本中:

  "scripts": {
    (...)
    "dev": "nodemon --watch src/* --exec 'node src/index.js | pino-pretty'",
    "start": "node src/index.js"
  }
作者头像

检查环境变量。它必须是分期或生产。 SENTRY_ENVIRONMENT 左右检查。我有同样的错误。

enter image description here

import pino, { Logger } from 'pino';
import dotenv from "dotenv";
import { createWriteStream } from "pino-sentry";

dotenv.config();

function prodLogger():Logger {
    const stream = createWriteStream({ dsn: process.env.SENTRY_DSN, serverName: process.env.TENANT_NAME});

    return pino({}, stream);
}

function devLogger(): Logger {
    return pino({
        timestamp: true,
        transport: {
            target: 'pino-pretty',
            options: {
                colorize: true,
                destination: 2,
                sync: process.env.SENTRY_ENVIRONMENT === 'testing',
            },
        },
    });
}

function logger(): Logger {
    return ['production', 'staging',"develop"].includes(process.env.SENTRY_ENVIRONMENT ?? '')
        ? prodLogger()
        : devLogger();
}

export default logger();
作者头像

You can use it as a stream if it doesn't work with the transport option:

import pino from "pino";
import pretty from "pino-pretty";

const stream = pretty({
  levelFirst: true,
  colorize: true,
  ignore: "time,hostname,pid",
});

const logger = pino(
  {
    name: "MyLogger",
    level: process.env.NODE_ENV === "developement" ? "debug" : "info",
  },
  stream
);

export default logger;

More details in the docs: https://github.com/pinojs/pino-pretty#usage-as-a-stream