Skip to content

Comments

Implement structured logging package (log/slog)#15

Draft
Copilot wants to merge 4 commits intomainfrom
copilot/implement-structured-logging-package
Draft

Implement structured logging package (log/slog)#15
Copilot wants to merge 4 commits intomainfrom
copilot/implement-structured-logging-package

Conversation

Copy link
Contributor

Copilot AI commented Nov 10, 2025

Description

Adds a lightweight structured logging package inspired by Go's log/slog, providing levels, handlers, formatters, and context propagation without external dependencies.

Related Issue

Closes #(issue number not provided in context)

Changes

Core Types

  • Level enum (Debug/Info/Warn/Error) with filtering support
  • LogRecord interface capturing timestamp, level, message, key-value pairs, and optional errors
  • Logger class with debug()/info()/warn()/error() methods
  • with(fields) for immutable context propagation
  • withGroup(name) for hierarchical key prefixes

Handlers & Formatters

  • ConsoleHandler - routes to console.log/error based on level
  • FileHandler - async file appending with Deno APIs
  • TextFormatter - human-readable: ISO LEVEL message key=val ...
  • JSONFormatter - machine-readable single-line JSON
  • Deterministic output via sorted keys for testing

API Surface

  • Export path: @okudai/golikejs/log/slog
  • Key-value args support object, tuple ["k", v], and mixed forms
  • Errors captured with stack traces
  • ISO 8601 timestamps

Example

import { Logger, ConsoleHandler, JSONFormatter, Level } from "@okudai/golikejs/log/slog";

const logger = new Logger(
  new ConsoleHandler({ level: Level.Info, formatter: new JSONFormatter() })
);

const reqLogger = logger.with({ requestId: "abc-123" });
reqLogger.info("Request started", { method: "GET", path: "/api/users" });
// {"timestamp":"2024-01-01T12:00:00.000Z","level":"INFO","message":"Request started","method":"GET","path":"/api/users","requestId":"abc-123"}

const dbLogger = logger.withGroup("db");
dbLogger.info("Query executed", { table: "users", rows: 42 });
// Keys prefixed: db.table, db.rows

Testing

  • Comprehensive unit test suite (14 test cases) covering formatters, handlers, context propagation, level filtering, and nested groups
  • Manual verification via example.ts demonstrating all features
  • Type checking, formatting, and linting validated
  • CodeQL security scan passed (0 alerts)

Checklist

  • Comments added for complex logic
  • Documentation updated if needed
  • Tests added/updated
Original prompt

This section details on the original issue you should resolve

<issue_title>[FEATURE] Implement structured logging package similar to Go's log/slog</issue_title>
<issue_description>## Overview
Implement a lightweight, structured logging package for Go inspired by the standard library's log/slog. The package should provide levels, handlers, context/key-value support, formatters (text/JSON), and pluggable output targets.

Motivation & Benefits

  • Provide consistent structured logging across the project without adding heavy external dependencies.
  • Improve observability by producing machine-readable logs (JSON) for aggregation and analysis.
  • Offer an API familiar to users of log/slog while allowing project-specific extensions and lightweight defaults.

Use Case

  • Server applications: include request IDs and user metadata from context for each log entry.
  • CLI tools and batch jobs: emit readable text logs in development and JSON logs in production.
  • Tests: enable deterministic text format for snapshots and compare output.

Proposed Solution (include Next Steps)

  • Core design:
    • Logger with methods (Debug/Info/Warn/Error) and With/WithGroup for context propagation.
    • Record/Entry type storing timestamp, level, message, and key/value pairs.
    • Handler interface with configurable Formatter and output (io.Writer, files, network).
    • Formatter implementations: simple text and JSON.
    • Level type with basic filtering.
  • Implementation plan:
    1. Draft API surface and small usage examples (log creation, With, Handlers).
    2. Implement core types (Level, Record, Logger) and a basic text handler.
    3. Add JSON formatter and handler options.
    4. Add context integration (context.Context) and With/Groups.
    5. Write unit tests, benchmarks, and examples; document migration from log/slog.
  • Deliverables: package code, tests, examples, README with usage and migration notes.

Alternatives Considered

  • Adopt existing libraries: zap, zerolog, logrus — faster launch but increases dependency surface.
  • Use Go's built-in log/slog (requires Go version constraints) — simplest if project can require compatible Go version.

Related issues

None

Checklist

  • I have searched existing issues
  • I have read relevant documentation
  • I can contribute to this feature</issue_description>

<agent_instructions>Revised Copilot prompt (Deno-targeted, tests placed alongside sources as *_test.ts):

Implement a small TypeScript structured-logging package inspired by Go's log/slog. Context: use the repository ISSUE (.github/ISSUE_TEMPLATE/feature.yml) and refer to https://pkg.go.dev/log/slog for API guidance. Target runtime: Deno (no external deps). Place files under src/log/slog and export public API from src/log/slog/mod.ts.

Files to create:

  • src/log/slog/level.ts
  • src/log/slog/logger.ts
  • src/log/slog/handler.ts
  • src/log/slog/formatter.ts
  • src/log/slog/mod.ts
  • src/log/slog/slog_test.ts <-- tests implemented in same directory, filename pattern *_test.ts (Deno.test style)

Requirements (same as before, concise):

  • Level enum: Debug, Info, Warn, Error + helpers.
  • Record: timestamp (ISO string), level, message, keys (plain object), optional error.
  • Logger:
    • constructor(handler: Handler)
    • debug/info/warn/error(message: string, ...args: KV[] | Error?)
    • with(fields) and withGroup(name) -> derived Logger (do not mutate parent)
    • internal log merges context + KV args into new object and calls handler.handle(record)
    • Accept KV forms: object ({k:v}), tuple ["k", v], alternating "k", v; Error allowed as final arg.
  • Handler interface: handle(record): Promise | void
    • Handlers have minimum level and ignore lower-level records.
    • Built-ins:
      • ConsoleHandler: uses Formatter, writes to console.log / console.error.
      • FileHandler: append to file using Deno APIs (compact).
    • Prefer async handle implementations.
  • Formatters:
    • TextFormatter: "ISO LEVEL message key=val ..." with keys sorted.
    • JSONFormatter: one JSON object per line with timestamp, level, message and keys (keys sorted).
  • Deterministic ordering: sort keys for stable outputs/tests.
  • Exports from mod.ts: Logger, Level, ConsoleHandler, FileHandler, JSONFormatter, TextFormatter, default logger factory.
  • Include short doc comments and a usage example in mod.ts top comment:
    const root = new Logger(new ConsoleHandler({ level: Level.Info, formatter: new JSONFormatter() }));
    const reqLogger = root.with({ requestId: "abc" });
    reqLogger.info("started", ["user", 123], ["size", 42]);
    reqLogger.error("failed", new Error("boom"));

Tests (minimal, Deno.test style in src/log/slog/slog_test.ts):

    1. JSONFormatter emits a single-line JSON containing ISO timestamp, level, message and provided keys (keys sorted).
    1. with() merges context keys into emitted record without mutating parent.
    1. Handler level filtering ignores records below the configured level.
  • Keep assertions deterministic (sorted keys, ISO rege...

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI and others added 3 commits November 10, 2025 13:04
Co-authored-by: OkutaniDaichi0106 <132345842+OkutaniDaichi0106@users.noreply.github.com>
Co-authored-by: OkutaniDaichi0106 <132345842+OkutaniDaichi0106@users.noreply.github.com>
Co-authored-by: OkutaniDaichi0106 <132345842+OkutaniDaichi0106@users.noreply.github.com>
Copilot AI changed the title [WIP] Implement structured logging package similar to Go's log/slog Implement structured logging package (log/slog) Nov 10, 2025
Copilot AI requested a review from okdaichi November 10, 2025 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Implement structured logging package similar to Go's log/slog

2 participants