Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/create-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"test:generator": "cross-env NODE_ENV=e2e vitest run --config=vitest.generator.config.ts"
},
"dependencies": {
"@kintone/logger": "workspace:^",
"@inquirer/prompts": "^5.5.0",
"chalk": "^4.1.2",
"glob": "^10.4.5",
Expand Down
14 changes: 3 additions & 11 deletions packages/create-plugin/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
"use strict";
import { logger } from "@kintone/logger";

/**
* Print logs
* @param texts
*/
export const printLog = (...texts: string[]) => {
texts.forEach((t) => console.log(t));
texts.forEach((t) => logger.info(t));
};

/**
* Print errors
* @param errors
*/
export const printError = (...errors: string[]) => {
errors.forEach((e) => console.error(e));
errors.forEach((e) => logger.error(e));
};
5 changes: 4 additions & 1 deletion packages/create-plugin/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
]
},
"include": ["src/**/*.ts"],
"exclude": ["**/__tests__/**", "**/*.test.ts", "**/*.spec.ts", "vitest.config.ts"]
"exclude": ["**/__tests__/**", "**/*.test.ts", "**/*.spec.ts", "vitest.config.ts"],
"references": [
{ "path": "../logger" }
]
}
1 change: 1 addition & 0 deletions packages/dts-gen/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"test:ci": "cross-env NODE_OPTIONS=--experimental-vm-modules vitest run"
},
"dependencies": {
"@kintone/logger": "workspace:^",
"@cybozu/eslint-config": "^24.3.0",
"axios": "^1.12.2",
"commander": "^12.1.0",
Expand Down
4 changes: 3 additions & 1 deletion packages/dts-gen/src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { logger } from "@kintone/logger";

export const log = (message: string) => {
console.log(message);
logger.info(message);
};
5 changes: 4 additions & 1 deletion packages/dts-gen/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@
"outDir": "./dist",
"rootDir": "./src",
"strict": false // TODO enable strict mode
}
},
"references": [
{ "path": "../logger" }
]
}
5 changes: 5 additions & 0 deletions packages/logger/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
lib/
vitest.config.js
vitest.config.d.ts
vitest.config.js.map
167 changes: 167 additions & 0 deletions packages/logger/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# CLAUDE.md - @kintone/logger

This file provides guidance to Claude Code when working with the logger package.

## Package Overview

`@kintone/logger` is a lightweight logging utility designed for kintone CLI tools. It provides structured logging with level-based filtering and customizable output.

## Architecture

### Core Components

1. **StandardLogger** (`src/logger.ts`)
- Main logger implementation
- Handles log level filtering
- Formats messages with timestamps
- Supports custom printers

2. **Types** (`src/types.ts`)
- Logger interface
- Log level definitions
- Type exports

3. **Public API** (`src/index.ts`)
- `logger`: Pre-configured logger instance
- `StandardLogger`: Class for custom instances
- `LOG_CONFIG_LEVELS`: Array of valid log levels (for CLI choices)
- `LogConfigLevel`: Type for log configuration

## Development Guidelines

### File Structure

```
src/
├── index.ts # Public API exports
├── logger.ts # StandardLogger implementation
└── types.ts # Type definitions
```

### Code Style

- Use TypeScript strict mode
- No runtime dependencies (keep it lightweight)
- Prefer composition over inheritance
- Keep methods focused and single-purpose

### Testing

Run tests with:
```bash
pnpm test
```

Test coverage should include:
- All log levels (trace, debug, info, warn, error, fatal)
- Log level filtering logic
- Message formatting
- Custom printer support
- Error object handling

### Building

Build the package:
```bash
pnpm build
```

This compiles TypeScript to JavaScript in the `lib/` directory.

### Linting

```bash
pnpm lint # Check for issues
pnpm fix # Auto-fix issues
```

## Implementation Notes

### Log Level Filtering

The logger uses a numeric ordering system to determine which messages to print:

```typescript
// LEVEL_ORDER is generated from LOG_CONFIG_LEVELS
const LEVEL_ORDER = LOG_CONFIG_LEVELS.reduce(
(acc, level, index) => {
acc[level] = index;
return acc;
},
{} as Record<LogConfigLevel, number>,
);

// Level filtering uses simple numeric comparison
private isPrintable(event: LogEvent): boolean {
if (this.logConfigLevel === "none") return false;
return LEVEL_ORDER[event.level] >= LEVEL_ORDER[this.logConfigLevel];
}
```

This approach is more efficient than the matrix-based approach, using O(1) object lookup instead of array operations.

### Message Formatting

- Timestamps use ISO 8601 format
- Log levels are displayed in uppercase (using `event.level.toUpperCase()`)
- Multi-line messages are split and prefixed individually
- Error objects are converted to strings using `.toString()`
- All other values use `String(value)`

### Custom Printers

The default printer is `console.error`, but custom printers can be provided:

```typescript
const logger = new StandardLogger({
printer: (message) => {
// Custom logic (e.g., write to file, send to logging service)
}
});
```

## Common Tasks

### Adding a New Log Level

1. Add the new level to `LOG_CONFIG_LEVELS` array in `src/types.ts`
2. `LogConfigLevel` type will be automatically updated (derived from array)
3. `LogEventLevel` type will be automatically updated (uses `Exclude<LogConfigLevel, "none">`)
4. Add method to `Logger` interface
5. Add method to `StandardLogger` class
6. `LEVEL_ORDER` will be automatically updated (generated from `LOG_CONFIG_LEVELS`)
7. Add tests for the new level

Note: Most type definitions are derived from `LOG_CONFIG_LEVELS` as the single source of truth, so changes propagate automatically.

### Modifying Message Format

Edit the `format()` method in `src/logger.ts`. Keep in mind:
- The format is used by CLI tools that parse output
- Changes may affect downstream consumers
- Maintain backwards compatibility when possible

The current format uses `toUpperCase()` to convert log levels to uppercase for display, while keeping the internal representation lowercase for consistency with CLI options.

## Dependencies

This package has ZERO runtime dependencies to keep it lightweight. Only dev dependencies are:
- `vitest` - Testing framework
- `rimraf` - Clean build artifacts

## Publishing

This package is currently private (`"private": true` in package.json). If it needs to be published:

1. Remove `"private": true`
2. Ensure version follows semver
3. Run `pnpm build` and `pnpm test`
4. Publish with `npm publish` (configured for public access)

## Related Packages

This logger is designed to be used by:
- `cli-kintone` - CSV import/export CLI
- Other kintone CLI tools in the monorepo

When making changes, consider the impact on these consumers.
118 changes: 118 additions & 0 deletions packages/logger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# @kintone/logger

Logger utility for kintone CLI tools.

## Features

- **6 log levels**: trace, debug, info, warn, error, fatal
- **Configurable log level filtering**: Control which messages are printed
- **Timestamp support**: All messages include ISO 8601 timestamps
- **Custom printer support**: Use custom output functions instead of console.error
- **TypeScript support**: Full type definitions included

## Installation

```bash
npm install @kintone/logger
# or
pnpm add @kintone/logger
```

## Usage

### Basic Usage

```typescript
import { logger } from "@kintone/logger";

logger.info("Application started");
logger.warn("This is a warning");
logger.error(new Error("Something went wrong"));
```

### Custom Logger Instance

```typescript
import { StandardLogger } from "@kintone/logger";

const customLogger = new StandardLogger({
logConfigLevel: "debug",
printer: (message) => {
// Custom output logic
console.log(message);
},
});

customLogger.debug("Debug message");
customLogger.info("Info message");
```

### Dynamic Log Level Configuration

```typescript
import { logger } from "@kintone/logger";

// Set log level to only show warnings and above
logger.setLogConfigLevel("warn");

logger.info("This won't be printed");
logger.warn("This will be printed");
logger.error("This will be printed");

// Disable all logging
logger.setLogConfigLevel("none");
```

## API Reference

### Logger Interface

```typescript
interface Logger {
trace: (message: unknown) => void;
debug: (message: unknown) => void;
info: (message: unknown) => void;
warn: (message: unknown) => void;
error: (message: unknown) => void;
fatal: (message: unknown) => void;
}
```

### StandardLogger Constructor Options

```typescript
new StandardLogger({
logConfigLevel?: "trace" | "debug" | "info" | "warn" | "error" | "fatal" | "none";
printer?: (data: unknown) => void;
});
```

### Log Levels

Log levels control which messages are printed based on severity:

- `trace`: Most verbose - prints all messages
- `debug`: Debug and above
- `info`: Info and above (default)
- `warn`: Warnings and above
- `error`: Errors and above
- `fatal`: Only fatal errors
- `none`: No output

## Output Format

All log messages are formatted with timestamp and level:

```
[2024-01-15T12:34:56.789Z] INFO: Application started
[2024-01-15T12:34:57.123Z] WARN: Low memory warning
[2024-01-15T12:34:58.456Z] ERROR: Failed to connect
```

## License

MIT

## Author

Cybozu, Inc.
Loading
Loading