CodeSampleX

サンプル

hono 4.13.7: logger

検証済みサンプル — npm hono 4.13.7: logger. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: createAppWithCustomLogger and createAppWithDefaultLogger…

sha256:de0ed8eb77195a99234eb7befb8002444d8175fb56e9aadd235be6c58a543e95

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

ケース

HOW
ゴール
verify logger in pkg:npm/hono@4.13.7
パッケージ
シンボル
  • logger
作成日
2026-09-06T04:18:54Z

コントラクト

  1. createAppWithCustomLogger and createAppWithDefaultLogger configure Hono applications with logger middleware
  2. logger export is a callable function returning a Hono middleware handler function
  3. logger middleware captures incoming HTTP request method and path using the incoming prefix
  4. logger middleware captures outgoing HTTP response status code and elapsed time using the outgoing prefix
  5. logger middleware invokes custom print callback on incoming and outgoing request lifecycle events
  6. logger middleware records accurate status codes for successful, created, not found, and internal server error responses
  7. logger middleware with default print handler completes the request-response lifecycle without errors

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify logger in pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - logger

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:4fffeee674307a3d1a736a05f01bba6b2c275f9ad1e1062e7d555465cdcf03cf","contract":["createAppWithCustomLogger and createAppWithDefaultLogger configure Hono applications with logger middleware","logger export is a callable function returning a Hono middleware handler function","logger middleware captures incoming HTTP request method and path using the incoming prefix","logger middleware captures outgoing HTTP response status code and elapsed time using the outgoing prefix","logger middleware invokes custom print callback on incoming and outgoing request lifecycle events","logger middleware records accurate status codes for successful, created, not found, and internal server error responses","logger middleware with default print handler completes the request-response lifecycle without errors"],"goal":"verify logger in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["logger"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["logger"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-logger",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-logger",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-logger",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for logger in hono@4.13.7",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify logger in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "logger"
  ]
}
src/index.js
'use strict';

const { Hono } = require('hono');
const { logger } = require('hono/logger');

/**
 * Creates a Hono app configured with a custom logger callback.
 *
 * @param {Function} printFn - Custom logging function (message: string) => void
 * @returns {Hono}
 */
function createAppWithCustomLogger(printFn) {
  const app = new Hono();

  app.use('*', logger(printFn));

  app.get('/api/hello', (c) => {
    return c.json({ message: 'hello world' });
  });

  app.post('/api/items', async (c) => {
    const body = await c.req.json().catch(() => ({}));
    return c.json({ success: true, item: body }, 201);
  });

  app.get('/api/error', (c) => {
    return c.text('internal error', 500);
  });

  return app;
}

/**
 * Creates a Hono app configured with default logger (console.log).
 *
 * @returns {Hono}
 */
function createAppWithDefaultLogger() {
  const app = new Hono();
  app.use('*', logger());

  app.get('/api/ping', (c) => {
    return c.text('pong');
  });

  return app;
}

module.exports = {
  createAppWithCustomLogger,
  createAppWithDefaultLogger,
  Hono,
  logger
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createAppWithCustomLogger,
  createAppWithDefaultLogger,
  Hono,
  logger
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof createAppWithCustomLogger, 'function', 'createAppWithCustomLogger must be a function');
  assert.equal(typeof createAppWithDefaultLogger, 'function', 'createAppWithDefaultLogger must be a function');
  assert.equal(typeof Hono, 'function', 'Hono export must be a function');
  assert.equal(typeof logger, 'function', 'logger export must be a function');

  // 2. logger() returns a middleware handler function
  const middleware = logger();
  assert.equal(typeof middleware, 'function', 'logger() must return a middleware handler function');

  // 3. Custom logger records incoming and outgoing logs for GET /api/hello (200 OK)
  const logs = [];
  const customPrint = (str) => logs.push(str);
  const app = createAppWithCustomLogger(customPrint);

  const resHello = await app.fetch(new Request('http://localhost/api/hello'));
  assert.equal(resHello.status, 200, 'GET /api/hello should return 200');
  const bodyHello = await resHello.json();
  assert.deepEqual(bodyHello, { message: 'hello world' });

  assert.equal(logs.length, 2, 'Two log messages should be recorded: incoming and outgoing');
  // Incoming log format: "<-- GET /api/hello"
  assert.ok(logs[0].startsWith('<--'), 'First message should be incoming prefix <--');
  assert.ok(logs[0].includes('GET'), 'Incoming log should include method GET');
  assert.ok(logs[0].includes('/api/hello'), 'Incoming log should include pathname /api/hello');

  // Outgoing log format: "--> GET /api/hello 200 <time>"
  assert.ok(logs[1].startsWith('-->'), 'Second message should be outgoing prefix -->');
  assert.ok(logs[1].includes('GET'), 'Outgoing log should include method GET');
  assert.ok(logs[1].includes('/api/hello'), 'Outgoing log should include pathname /api/hello');
  assert.ok(logs[1].includes('200'), 'Outgoing log should include status 200');

  // 4. Custom logger records POST /api/items (201 Created)
  logs.length = 0;
  const resPost = await app.fetch(
    new Request('http://localhost/api/items', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ item: 'notebook' })
    })
  );
  assert.equal(resPost.status, 201, 'POST /api/items should return 201');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for POST');
  assert.ok(logs[0].includes('POST'), 'Incoming log should include method POST');
  assert.ok(logs[0].includes('/api/items'), 'Incoming log should include pathname /api/items');
  assert.ok(logs[1].includes('POST'), 'Outgoing log should include method POST');
  assert.ok(logs[1].includes('201'), 'Outgoing log should include status 201');

  // 5. Custom logger records 500 error response
  logs.length = 0;
  const resErr = await app.fetch(new Request('http://localhost/api/error'));
  assert.equal(resErr.status, 500, 'GET /api/error should return 500');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for 500');
  assert.ok(logs[1].includes('500'), 'Outgoing log should include status 500');

  // 6. Custom logger records 404 not found response
  logs.length = 0;
  const resNotFound = await app.fetch(new Request('http://localhost/api/nonexistent'));
  assert.equal(resNotFound.status, 404, 'Unknown route should return 404');
  assert.equal(logs.length, 2, 'Two log messages should be recorded for 404');
  assert.ok(logs[1].includes('404'), 'Outgoing log should include status 404');

  // 7. Default logger works without errors
  const defaultApp = createAppWithDefaultLogger();
  const resPing = await defaultApp.fetch(new Request('http://localhost/api/ping'));
  assert.equal(resPing.status, 200, 'GET /api/ping should return 200 with default logger');
  const textPing = await resPing.text();
  assert.equal(textPing, 'pong');
}

testAll().then(
  () => {
    console.log('Contract assertions passed successfully');
    process.exit(0);
  },
  (err) => {
    console.error('Contract failed:', err);
    process.exit(1);
  }
);

オリジンシーダー

匿名