@bonniernews/logger

中文文档
0.0.13发布于 2025/10/15MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2.1万

Some simple functions to use Trace Context for correlating logs

原始使用文档
文档目录4 节
  1. Usage
  2. Interface
  3. Logger
  4. attachTrace

@bonniernews/logger

Bonnier News logger library, that makes it easier to unify logging. It is pre-configured for GCP and includes tracing capabilities for Express servers.

npm install @bonniernews/logger

Usage

Here is an example server with log tracing enabled.

import {
  getTraceparent,
  middleware,
  logger as buildLogger
} from "@bonniernews/logger";
import express from "express";

const logger = buildLogger();
const app = express();

// This middleware will create a request context and
// automatically decorate all logs with tracing data:
app.use(middleware());

app.get("/", async (req, res) => {
  logger.info("Hello, world!");

  // Propagate traceparent to other services
  const response = await fetch("https://some.other.service.bn.nr/some/endpoint", {
    headers: { traceparent: getTraceparent() },
  });

  ...
});

The middleware should be put as early as possible, since only logs after this middleware will get the tracing data. The middleware will lookup the active project ID from GCP. Alternatively, you can set the GCP_PROJECT environment variable for this purpose.

Use the getTraceparent function to pass tracing headers to downstream services. Use getTraceId if you only want to know the current trace-id.

If you want to decorate logs with custom data, use the exported decorateLogs function. In order to use this, the middleware needs to be installed first.

Interface

The library have these named exports:

  • logger: Used to create a logger, see below.
  • middleware: A middleware to install a request context store that is used to decorate logs with automatic tracing. This middleware enables the use of decorateLogs, getLoggingData, getTraceparent and getTraceId.
  • attachTrace: If you have a separate script or function, without using an express middleware, where you want to use the logging lib you can use attachTrace.
  • decorateLogs: Function to add data to the request context.
  • getLoggingData: Returns decorated data fields together with trace information.
  • getTraceparent: Returns traceparent header value - to be used for requests to downstream services.
  • getTraceId: Returns the traceId value - useful if you want to add it to an API error response.
  • createTraceparent: Utility function to generate a traceparent header value.

Logger

Options

This library uses the Pino logger, and instances are created using the same options. In most cases this is not needed, and you can use the defaults:

  • Uses info as the minimum log level
  • JSON logging with severity and message fields for non-local environments - in line with GCP structured logging standards
  • Pretty logging enabled for local development and test environments

Log Levels

The logger has the following levels, with their corresponding GCP severity mapping:

Log levelGCP severity
traceDEBUG
debugDEBUG
infoINFO
warnWARNING
errorERROR
fatalCRITICAL

Log messages

Here are a few examples on how to use the logger:

import { logger } from "@bonniernews/logger";

const log = logger({ level: "debug" });

log.debug("This is just a message");

log.info("This is how to use %s strings: %d", "template", 123);

log.info({ any: { additional: "data" } }, "I'm attaching relevant data");

const error = new Error("Oops!");

// This will set error.message as the log message,
// and add a serialized error object under the `err` key:
log.warn(error);

// The `err` key is special, and triggers error serialization:
log.error({ err: error }, "This message takes precedence over err.message");

attachTrace

Example

import { attachTrace } from "@bonniernews/logger";

const getTrace = () => new Promise((resolve) => resolve(getTraceId()));
const runScript = async function (param1, param2) {
  const output = [param1, param2];
  output.push(getTraceId());
  const trace = await getTrace(); // The trace is available since this is invoked from a trace context.
  output.push(trace);
  return output;
};

const runWithTrace = await attachTrace(runScript);
const res1 = await runWithTrace(1, 2); // Will execute runScript with parameters 1, 2
const res2 = await runWithTrace(3, 4); // Will execute runScript with parameters 3, 4

Tracing

If you want to decorate logs with tracing fields for incoming requests, use the library's middleware, which will use Node async hooks to store and decorate all logs using the standardized traceparent header.

版本与发布记录

@bonniernews/logger 共发布 13 个版本,首次发布于 2024/10/31;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.13latest2025/10/151.1 年前
0.0.13-alpha.1next2025/09/041.2 年前
0.0.13-alpha.02025/08/221.2 年前
0.0.122025/04/301.5 年前
0.0.12-alpha.0alpha2025/04/291.5 年前
0.0.112025/01/141.8 年前

关于 @bonniernews/logger 的常见问题

@bonniernews/logger 是什么?

Some simple functions to use Trace Context for correlating logs

如何安装 @bonniernews/logger?

在项目目录运行 npm install @bonniernews/logger,或使用 pnpm add / yarn add / bun add。

@bonniernews/logger 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bonniernews/logger 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bonniernews/logger 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bonniernews/logger 可以商用吗?

@bonniernews/logger 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bonniernews/logger 的下载量有多少?

根据 npm 官方下载统计,@bonniernews/logger 在 2026/10/09 – 2026/11/07 这 30 天内被下载 20,806 次,日均约 694 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bonniernews/logger 还在维护吗?

最新版本 0.0.13 发布于 2025/10/15(1.1 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/10/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。