CodeSampleX

샘플

hono 4.13.7: logger

검증된 샘플 — npm hono 4.13.7: logger. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: createAppWithCustomLogger and createAppWithDefaultLogger…

sha256:de0ed8eb77195a99234eb7befb8002444d8175fb56e9aadd235be6c58a543e95

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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);
  }
);

오리진 시더

익명