### Project Setup and Dependency Installation Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md Commands to create a new Vite project with React 19, install core dependencies, @oxog/codeshine for syntax highlighting, Tailwind CSS v4, and initialize shadcn/ui. ```bash # Inside package root mkdir website && cd website # Create Vite project with React 19 npm create vite@latest . -- --template react-ts # Install core dependencies npm install react@^19 react-dom@^19 npm install react-router-dom@^7 npm install lucide-react # Install @oxog/codeshine for syntax highlighting npm install @oxog/codeshine # Install Tailwind CSS v4 npm install tailwindcss @tailwindcss/vite # Install shadcn/ui (follow shadcn setup for v4) npx shadcn@latest init ``` -------------------------------- ### Quick Start Logger Creation Source: https://github.com/ersinkoc/log/blob/main/llms.txt Initialize a basic logger and log an informational message. This is the simplest way to get started with the library. ```typescript import { createLogger } from '@oxog/log'; const log = createLogger(); log.info('Hello, world!'); ``` -------------------------------- ### Install, Build, and Use Logger Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION_SUMMARY.md Install dependencies, build the package, and import/use the logger. This process works despite a known build warning. ```bash # Install dependencies npm install # Build the package (works despite warning) npm run build # Import and use import { createLogger } from './dist/index.js'; const log = createLogger(); log.info('Hello, @oxog/log!'); ``` -------------------------------- ### Quick Start Logger Initialization and Usage Source: https://github.com/ersinkoc/log/blob/main/examples/01-basic/README.md Initialize a logger with a name and log an informational message. This snippet shows basic setup and logging. ```typescript import { createLogger } from '@oxog/log'; const log = createLogger({ name: 'my-app' }); log.info('Hello, world!'); log.info({ userId: 123 }, 'User logged in'); ``` -------------------------------- ### Run Basic Examples with tsx Source: https://github.com/ersinkoc/log/blob/main/examples/01-basic/README.md Run the basic examples using tsx. This is the recommended way to execute the TypeScript examples. ```bash npx tsx examples/01-basic/minimal.ts ``` ```bash npx tsx examples/01-basic/log-levels.ts ``` ```bash npx tsx examples/01-basic/with-options.ts ``` -------------------------------- ### Quick Start: Create and Use Logger Source: https://github.com/ersinkoc/log/blob/main/README.md Demonstrates how to create a logger, perform simple logging, log with structured data, and create child loggers with context. ```typescript import { createLogger } from '@oxog/log'; const log = createLogger({ name: 'my-app' }); // Simple logging log.info('Server started'); // Structured logging with data log.info({ port: 3000, env: 'production' }, 'Listening'); // Child loggers with context const dbLog = log.child({ module: 'database' }); dbLog.info('Connected to database'); ``` -------------------------------- ### Install @oxog/log Package Source: https://github.com/ersinkoc/log/blob/main/examples/01-basic/README.md Install the @oxog/log package using npm. ```bash npm install @oxog/log ``` -------------------------------- ### Swappable Plugin Design Example Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Illustrates the swappable plugin architecture by showing how to use an in-house console transport and how an external elastic transport could be used as a drop-in replacement with the same interface. ```typescript // Today (in-house plugin) import { consoleTransport } from '@oxog/log/transports'; log.use(consoleTransport()); // Tomorrow (external package - drop-in replacement) import { elasticTransport } from '@oxog/log-elastic'; log.use(elasticTransport()); // Same interface! ``` -------------------------------- ### Create Logger Instance with Plugins Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Demonstrates how to create a logger instance using `createLogger` and integrating various core and optional plugins from the @oxog ecosystem. This setup includes essential plugins like levels, formatter, timestamp, context, and redaction, with options for source tracking and custom plugins. ```typescript // src/logger.ts import { createKernel } from '@oxog/plugin'; import { pigmentPlugin } from '@oxog/pigment/plugins'; import { createEmitter } from '@oxog/emitter'; import type { Plugin } from '@oxog/types'; import { levelsPlugin, formatterPlugin, /* ... */ } from './plugins/core'; import { consoleTransport } from './transports/console'; export function createLogger(options: LoggerOptions = {}): Logger { // Create emitter for log events const emitter = createEmitter(); // Create kernel using @oxog/plugin const kernel = createKernel({ context: { level: parseLevel(options.level ?? 'info'), format: options.format ?? 'auto', colors: options.colors ?? true, transports: options.transports ?? [consoleTransport()], redactPaths: options.redact ?? [], bindings: {}, pigment: null!, // Set by pigmentPlugin emitter, } }); // Use pigment for colors kernel.use(pigmentPlugin({ enabled: options.colors })); // Register core plugins kernel.use(levelsPlugin); kernel.use(formatterPlugin); kernel.use(timestampPlugin); kernel.use(contextPlugin); kernel.use(redactionPlugin); if (options.source) { kernel.use(sourcePlugin); } kernel.use(bufferPlugin(options.buffer)); // Register optional plugins if (options.plugins) { for (const plugin of options.plugins) { kernel.use(plugin); } } // Initialize kernel kernel.init(); // Create logger interface return createLoggerInterface(kernel); } ``` -------------------------------- ### Example localStorage Log Entry Format Source: https://github.com/ersinkoc/log/blob/main/docs/SPECIFICATION.md Illustrates the structure of a log entry stored in localStorage, including level, timestamp, message, and metadata. ```json { "entries": [ { "level": 30, "levelName": "info", "time": 1705294800000, "msg": "message", ... } ], "metadata": { "created": 1705294800000, "version": "1.0.0" } } ``` -------------------------------- ### GitHub Workflow for Website Deployment Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md This workflow deploys the website to GitHub Pages. It checks out the code, sets up Node.js, installs dependencies, runs tests and builds the project, configures GitHub Pages, and uploads the build artifact for deployment. ```yaml name: Deploy Website on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' cache: 'npm' - run: npm ci - run: npm run test:coverage - run: npm run build - working-directory: ./website run: npm ci && npm run build - uses: actions/configure-pages@v4 - uses: actions/upload-pages-artifact@v3 with: path: './website/dist' deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest needs: build steps: - uses: actions/deploy-pages@v4 id: deployment ``` -------------------------------- ### Environment Detection Logic Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Example code for detecting the runtime environment (Node.js or browser) and development status. ```typescript // Automatic environment detection const isNode = typeof process !== 'undefined' && process.versions?.node; const isBrowser = typeof window !== 'undefined'; // NODE_ENV detection for format: 'auto' const isDev = process.env.NODE_ENV !== 'production'; ``` -------------------------------- ### Browser Logging Example Source: https://github.com/ersinkoc/log/blob/main/README.md Demonstrates basic logger usage in a browser environment, including logging messages and creating child loggers. Child loggers use console.group for better organization. ```typescript import { createLogger } from '@oxog/log'; const log = createLogger(); log.info('Hello from browser!'); log.warn('Careful!'); log.error('Something went wrong'); // Child loggers use console.group const child = log.child({ component: 'Auth' }); child.info('Checking token'); ``` -------------------------------- ### Create Logger with Options Source: https://github.com/ersinkoc/log/blob/main/llms.txt Create a logger instance with custom name and log level. Use this to configure the logger's behavior from the start. ```typescript const log = createLogger({ name: 'my-app', level: 'debug' }); ``` -------------------------------- ### Plugin System Integration Source: https://github.com/ersinkoc/log/blob/main/llms.txt Add custom functionality or modify log entries using plugins. This example shows how to integrate redaction and source location plugins. ```typescript import { redactPlugin, sourcePlugin } from '@oxog/log'; const log = createLogger({ plugins: [redactPlugin(['apiKey']), sourcePlugin()] }); ``` -------------------------------- ### GitHub Workflow for npm Package Publishing Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md This workflow publishes the npm package to the npm registry when a new version tag is pushed. It includes steps for checking out code, setting up Node.js, installing dependencies, running tests and builds, and finally publishing the package. ```yaml name: Publish to npm on: push: tags: ['v*'] permissions: contents: read id-token: write jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' registry-url: 'https://registry.npmjs.org' - run: npm ci - run: npm run test:coverage - run: npm run build - run: npm publish --provenance --access public env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ``` -------------------------------- ### Logger Interface - Timing Source: https://github.com/ersinkoc/log/blob/main/docs/SPECIFICATION.md Methods for measuring the duration of operations. Use `time` to start a timer and `timeEnd` to stop and log it. ```typescript time(label: string): void timeEnd(label: string): void startTimer(label: string): () => void ``` -------------------------------- ### Create and Configure Logger Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Demonstrates creating a logger with zero configuration for sensible defaults or with extensive options for fine-grained control over name, level, format, transports, redaction, source inclusion, timestamps, performance, and context. ```typescript import { createLogger } from '@oxog/log'; // Zero-config (sensible defaults) const log = createLogger(); // Full configuration const log = createLogger({ // Identity name: 'my-app', // Level filtering level: 'info', // Minimum level to output // Output format format: 'auto', // 'json' | 'pretty' | 'auto' // Transports transports: [ consoleTransport({ colors: true }), fileTransport({ path: './app.log' }), ], // Features redact: ['password', 'token'], source: true, timestamp: true, // Performance sync: { fatal: true, error: true }, buffer: { size: 100, flushInterval: 1000 }, // Context context: { env: 'production', version: '1.0.0' }, }); // Usage log.info('Server started'); log.info({ port: 3000 }, 'Listening'); log.error(new Error('Connection failed'), 'Database error'); // Child logger const dbLog = log.child({ module: 'database' }); // Correlation const reqLog = log.withCorrelation(generateId()); // Timing log.time('operation'); await doWork(); log.timeEnd('operation'); // Graceful shutdown await log.flush(); await log.destroy(); ``` -------------------------------- ### Standard Log Plugin Interface Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Defines the contract for all plugins used with @oxog/log. It includes methods for installation, initialization, destruction, and error handling. ```typescript /** * Standard plugin interface for @oxog/log. * All plugins (internal and external) must implement this. */ interface LogPlugin { /** Unique plugin identifier (kebab-case) */ name: string; /** Semantic version */ version: string; /** Plugin dependencies by name */ dependencies?: string[]; /** Called when plugin is registered */ install: (kernel: LogKernel) => void; /** Called after ALL plugins are installed */ onInit?: (context: TContext) => void | Promise; /** Called when plugin is unregistered */ onDestroy?: () => void | Promise; /** Called when an error occurs */ onError?: (error: Error) => void; } ``` -------------------------------- ### CNAME File Configuration Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md Create a CNAME file in the public directory to specify the package name for deployment. ```plaintext {package-name}.oxog.dev ``` -------------------------------- ### Theme Management Initialization Source: https://github.com/ersinkoc/log/blob/main/website/index.html Initializes the website theme based on local storage or user's system preference. Adds the 'light' or 'dark' class to the document element. ```javascript (function() { var theme = localStorage.getItem('theme'); if (!theme) { theme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; } document.documentElement.classList.add(theme); })(); ``` -------------------------------- ### Oxog Log Project Structure Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Overview of the directory layout for the Oxog Log project. This structure organizes source code, tests, examples, and configuration. ```tree log/ ├── .github/workflows/ │ ├── deploy.yml │ └── publish.yml ├── src/ │ ├── index.ts │ ├── logger.ts │ ├── entry.ts │ ├── levels.ts │ ├── types.ts │ ├── formatters/ │ │ ├── index.ts │ │ ├── json.ts │ │ └── pretty.ts │ ├── transports/ │ │ ├── index.ts │ │ ├── console.ts │ │ ├── file.ts │ │ ├── stream.ts │ │ ├── http.ts │ │ └── localStorage.ts │ └── plugins/ │ ├── index.ts │ ├── core/ │ ├── optional/ │ └── ecosystem/ ├── tests/ │ ├── unit/ │ │ ├── logger.test.ts │ │ ├── entry.test.ts │ │ ├── levels.test.ts │ │ ├── formatters/ │ │ ├── transports/ │ │ └── plugins/ │ ├── integration/ │ │ ├── child-loggers.test.ts │ │ ├── multi-transport.test.ts │ │ ├── ecosystem.test.ts │ │ └── browser.test.ts │ └── fixtures/ ├── examples/ │ ├── 01-basic/ │ ├── 02-structured/ │ ├── 03-child-loggers/ │ ├── 04-transports/ │ ├── 05-colors/ │ ├── 06-redaction/ │ ├── 07-source-location/ │ ├── 08-correlation/ │ ├── 09-timing/ │ ├── 10-events/ │ ├── 11-browser/ │ ├── 12-file-rotation/ │ ├── 13-http-batch/ │ ├── 14-custom-transport/ │ └── 15-real-world/ ├── website/ │ ├── public/CNAME │ └── src/ ├── llms.txt ├── SPECIFICATION.md ├── IMPLEMENTATION.md ├── TASKS.md ├── README.md ├── package.json ├── tsconfig.json ├── tsup.config.ts ├── vitest.config.ts ├── .prettierrc ├── eslint.config.js └── .gitignore ``` -------------------------------- ### Logger Interface - Level Management Source: https://github.com/ersinkoc/log/blob/main/docs/SPECIFICATION.md Control and query the logging level. You can set the level, get the current level, and check if a specific level is enabled. ```typescript setLevel(level: LogLevel): void getLevel(): LogLevel isLevelEnabled(level: LogLevel): boolean ``` -------------------------------- ### Project Dependencies and Scripts (package.json) Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md Defines project name, version, scripts for development, building, previewing, and linting, along with production and development dependencies. ```json { "name": "{{REPO_NAME}}-website", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -b && vite build", "preview": "vite preview", "lint": "eslint ." }, "dependencies": { "@oxog/codeshine": "^1.0.0", "lucide-react": "^0.460.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-router-dom": "^7.0.0" }, "devDependencies": { "@eslint/js": "^9.15.0", "@tailwindcss/vite": "^4.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", "eslint": "^9.15.0", "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.14", "globals": "^15.12.0", "tailwindcss": "^4.0.0", "typescript": "~5.6.0", "typescript-eslint": "^8.15.0", "vite": "^6.0.0" } } ``` -------------------------------- ### Run Full Test Suite and Coverage Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION_SUMMARY.md Execute the complete test suite and generate a test coverage report to ensure all functionalities are working as expected. ```bash npm test npm run test:coverage ``` -------------------------------- ### Create Logger with @oxog/plugin Kernel Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Demonstrates how to create a logger instance using the `@oxog/plugin` kernel, integrating color formatting with `@oxog/pigment` and registering custom log plugins. ```typescript import { createKernel } from '@oxog/plugin'; import { pigmentPlugin } from '@oxog/pigment/plugins'; import type { Plugin } from '@oxog/types'; export function createLogger(options?: LoggerOptions) { const kernel = createKernel({ context: { /* log-specific context */ } }); // Use pigment for colors kernel.use(pigmentPlugin()); // Register log plugins kernel.use(levelsPlugin); kernel.use(formatterPlugin); // ... return kernel; } ``` -------------------------------- ### Define and Use a Custom Plugin Source: https://github.com/ersinkoc/log/blob/main/README.md Shows how to create and register a custom plugin with the logger. Custom plugins allow extending logging functionality. ```typescript import type { Plugin } from '@oxog/types'; const myPlugin: Plugin = { name: 'myPlugin', version: '1.0.0', install(kernel) { // Custom logic } }; log.use(myPlugin); ``` -------------------------------- ### Theme Toggle Component Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md A UI component to switch between light and dark themes. It uses the useTheme hook to get the current theme and toggle it. Ensure this component is rendered within a ThemeProvider. ```tsx // src/components/common/ThemeToggle.tsx import { Moon, Sun } from 'lucide-react'; import { useTheme } from '@/hooks/useTheme'; import { Button } from '@/components/ui/button'; export function ThemeToggle() { const { resolvedTheme, setTheme } = useTheme(); return ( ); } ``` -------------------------------- ### Multiple Output Formats (JSON and Pretty) Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Demonstrates configuring different output formats for logs. Supports automatic detection based on `NODE_ENV`, explicit JSON, or pretty-printed output. ```typescript // Auto-detect based on NODE_ENV const log = createLogger({ format: 'auto' }); // Explicit JSON const log = createLogger({ format: 'json' }); // {"level":30,"time":1234567890,"msg":"Hello"} // Explicit Pretty const log = createLogger({ format: 'pretty' }); // [2024-01-15 14:30:22] INFO Hello ``` -------------------------------- ### Define a Custom Transport Plugin Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Implement a custom transport plugin by extending the @oxog/plugin interface. This example shows how to add a new transport that sends log entries to a service and listens for log events. ```typescript import type { Plugin } from '@oxog/types'; import { definePlugin } from '@oxog/plugin'; interface LogContext { level: LogLevel; format: Format; transports: Transport[]; // ... } // Define a transport plugin export const myTransportPlugin = definePlugin((options) => ({ name: 'my-transport', version: '1.0.0', install(kernel) { const ctx = kernel.getContext(); // Add transport ctx.transports.push({ name: 'my-transport', write: (entry) => { // Send log entry somewhere sendToService(entry); } }); // Listen to log events kernel.on('log', (entry) => { // Process entry }); }, async onDestroy() { // Cleanup, flush buffers await flushPendingLogs(); } })); ``` -------------------------------- ### Importing and Using Logger Plugin Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Demonstrates how to import and use the `loggerPlugin` from the `@oxog/log/plugins` package within another @oxog package. ```typescript // In another @oxog package import { loggerPlugin } from '@oxog/log/plugins'; kernel.use(loggerPlugin({ level: 'debug' })); ``` -------------------------------- ### Output Formats Source: https://github.com/ersinkoc/log/blob/main/README.md Illustrates configuring different output formats for logs, including JSON, pretty-printed, and auto-detection. ```typescript // Structured JSON (production) const jsonLog = createLogger({ format: 'json' }); // Human-readable (development) const prettyLog = createLogger({ format: 'pretty' }); // Auto-detect based on environment const autoLog = createLogger({ format: 'auto' }); ``` -------------------------------- ### Implement Timing Plugin Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION.md This plugin initializes a map in the kernel's context to store timing information. Use this to measure the duration of operations. ```typescript export function timingPlugin(): LogPlugin { return { name: 'timing', version: '1.0.0', install(kernel) { kernel.context.timings = new Map(); } }; } ``` -------------------------------- ### Multiple Transports Configuration Source: https://github.com/ersinkoc/log/blob/main/README.md Demonstrates setting up multiple transports, such as console and file logging, for a single logger instance. ```typescript import { createLogger, consoleTransport, fileTransport } from '@oxog/log'; const log = createLogger({ transports: [ consoleTransport({ colors: true }), fileTransport({ path: './logs/app.log', rotate: '1d', maxFiles: 7 }) ] }); ``` -------------------------------- ### Log Build File Structure Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION.md Overview of the generated distribution file structure for the log package. Includes main entry points, plugin and transport modules, and type definitions for both ESM and CJS. ```text dist/ ├── index.js # ESM main ├── index.cjs # CJS main ├── index.d.ts # ESM types ├── index.d.cts # CJS types ├── plugins/ │ ├── index.js │ ├── index.cjs │ ├── index.d.ts │ └── index.d.cts ├── transports/ │ ├── index.js │ ├── index.cjs │ ├── index.d.ts │ └── index.d.cts └── *.js.map # Source maps ``` -------------------------------- ### Using Console Transport Plugin Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Demonstrates how to use the built-in console transport plugin with the @oxog/log library. ```typescript import { consoleTransport } from '@oxog/log/transports'; log.use(consoleTransport()); ``` -------------------------------- ### Create a Logger Instance Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Instantiate a logger with default settings or custom configurations for level, format, colors, and timestamps. Supports adding multiple transports for diverse output destinations. ```typescript import { createLogger } from '@oxog/log'; // Simple usage (sensible defaults) const log = createLogger(); log.info('Hello world'); // With configuration const log = createLogger({ level: 'debug', format: 'pretty', // 'json' | 'pretty' | 'auto' colors: true, timestamp: true, }); // With transports import { consoleTransport, fileTransport } from '@oxog/log/transports'; const log = createLogger({ transports: [ consoleTransport({ colors: true }), fileTransport({ path: './logs/app.log' }) ] }); ``` -------------------------------- ### Log Levels Source: https://github.com/ersinkoc/log/blob/main/README.md Demonstrates how to use different log levels for varying message severities. ```typescript log.trace('Detailed debugging'); // 10 log.debug('Debug information'); // 20 log.info('Informational'); // 30 log.warn('Warning'); // 40 log.error('Error occurred'); // 50 log.fatal('Fatal error'); // 60 ``` -------------------------------- ### Create Logger with Plugins Source: https://github.com/ersinkoc/log/blob/main/README.md Initializes a logger with built-in redaction and source plugins. Use this to configure global logging behavior. ```typescript import { createLogger, redactPlugin, sourcePlugin } from '@oxog/log'; const log = createLogger({ plugins: [ redactPlugin(['apiKey', 'secret']), sourcePlugin() ] }); ``` -------------------------------- ### Multiple Format Options Source: https://github.com/ersinkoc/log/blob/main/llms.txt Create loggers with different output formats: 'json', 'pretty', or 'auto' (detects TTY). Choose the format that best suits your environment. ```typescript const jsonLog = createLogger({ format: 'json' }); const prettyLog = createLogger({ format: 'pretty' }); const autoLog = createLogger({ format: 'auto' }); ``` -------------------------------- ### Footer with Author Credit Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md Implements a footer with author credit, GitHub and npm links, version, and license information. Requires 'lucide-react' icons and constants for repository and package details. ```tsx // src/components/layout/Footer.tsx import { Heart, Github, Package } from 'lucide-react'; import { PACKAGE_NAME, GITHUB_REPO, NPM_PACKAGE, VERSION } from '@/lib/constants'; export function Footer() { return (
{/* Made with love */}
Made with{' '} {' '} by{' '} Ersin KOÇ
{/* Links */} {/* Version & License */}
v{VERSION} MIT License
); } ``` -------------------------------- ### tsup Build Configuration Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION.md Configures the tsup build process for multiple entry points, output formats, and build optimizations. ```typescript import { defineConfig } from 'tsup'; export default defineConfig({ entry: { index: 'src/index.ts', 'plugins/index': 'src/plugins/index.ts', 'transports/index': 'src/transports/index.ts', }, format: ['esm', 'cjs'], dts: true, splitting: false, sourcemap: true, clean: true, external: [], treeshake: true, minify: false, }); ``` -------------------------------- ### Plugins Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Provides access to the log plugin system. ```APIDOC ## Plugins ### Description This section details the available plugins for extending logger functionality. ### Exports - **logPlugin**: Exports the log plugin. ``` -------------------------------- ### Header with GitHub Star Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md Renders a sticky header with navigation links, a logo, a GitHub star button, npm link, GitHub link, and a theme toggle. Ensure necessary components like ThemeToggle and icons from 'lucide-react' are imported. ```tsx // src/components/layout/Header.tsx import { Github, Star, Menu, Package } from 'lucide-react'; import { Link } from 'react-router-dom'; import { ThemeToggle } from '@/components/common/ThemeToggle'; import { Button } from '@/components/ui/button'; import { PACKAGE_NAME, GITHUB_REPO, NPM_PACKAGE } from '@/lib/constants'; export function Header() { return (
{/* Logo */} {PACKAGE_NAME} {/* Navigation */} {/* Right side */}
{/* GitHub Star Button */} Star {/* npm link */} {/* GitHub link */} {/* Theme toggle */}
); } ``` -------------------------------- ### Structured Logging with Metadata Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Shows how to attach metadata objects to log entries for richer context. The output includes the metadata alongside the message. ```typescript log.info({ userId: 123, action: 'login' }, 'User logged in'); // Output: {"level":30,"time":1234567890,"userId":123,"action":"login","msg":"User logged in"} ``` -------------------------------- ### Performance Timing with `startTimer` Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md An alternative method for performance timing using `log.startTimer`, which returns a function to be called upon completion to log the duration. ```typescript // Or with labels const end = log.startTimer('api-call'); await fetch('/api/data'); end(); // Automatically logs duration ``` -------------------------------- ### Import Pigment and Pigment Plugin from @oxog/pigment Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Import the pigment utility for terminal coloring and its associated plugin from the @oxog/pigment package. ```typescript import { pigment } from '@oxog/pigment'; import { pigmentPlugin } from '@oxog/pigment/plugins'; ``` -------------------------------- ### Swapping Log Plugins Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION.md Demonstrates how to replace the default redact plugin with a custom one from an external package. Ensure the external package implements the same interface for seamless migration. ```typescript // Internal plugin import { redactPlugin } from '@oxog/log/plugins'; log.use(redactPlugin(['password', 'token'])); // External package (drop-in replacement) import { advancedRedact } from '@oxog/redact'; log.use(advancedRedact({ fields: ['password', 'token'], strategy: 'hash', // Additional features! })); ``` -------------------------------- ### createLogger Source: https://github.com/ersinkoc/log/blob/main/docs/SPECIFICATION.md Creates a new logger instance with optional configuration options. ```APIDOC ## createLogger ### Description Creates a new logger instance with optional configuration options. ### Signature ```typescript createLogger(options?: LoggerOptions): Logger ``` ### Parameters #### Options - **options** (LoggerOptions) - Optional - Configuration options for the logger. ``` -------------------------------- ### Logger Methods Source: https://github.com/ersinkoc/log/blob/main/README.md Provides a comprehensive set of methods for logging, context management, timing, plugin handling, lifecycle control, and level management. ```APIDOC ## Logger Methods ### Logging - `trace(msg)` / `trace(obj, msg)` - Trace level - `debug(msg)` / `debug(obj, msg)` - Debug level - `info(msg)` / `info(obj, msg)` - Info level - `warn(msg)` / `warn(obj, msg)` - Warn level - `error(msg)` / `error(obj, msg)` / `error(err, msg)` - Error level - `fatal(msg)` / `fatal(obj, msg)` / `fatal(err, msg)` - Fatal level ### Context - `child(context)` - Create child logger with additional context - `withCorrelation(id)` - Create logger with correlation ID ### Timing - `time(label)` - Start a timer - `timeEnd(label)` - End timer and log duration - `startTimer(label)` - Returns stop function ### Plugin Management - `use(plugin)` - Register plugin - `unregister(name)` - Unregister plugin - `hasPlugin(name)` - Check if plugin exists - `listPlugins()` - List all plugins ### Lifecycle - `flush()` - Flush buffered logs - `close()` - Cleanup and close transports ### Level Management - `setLevel(level)` - Set minimum level - `getLevel()` - Get current level - `isLevelEnabled(level)` - Check if level is enabled ``` -------------------------------- ### Source Location Source: https://github.com/ersinkoc/log/blob/main/README.md Shows how to enable logging of the source file and line number for easier debugging. ```typescript const log = createLogger({ source: true }); log.info('Debug me'); // Output: {"level":30,"file":"server.ts","line":42,"msg":"Debug me"} ``` -------------------------------- ### Factory Function and Default Instance Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Provides methods to create a new logger instance with custom options or use the default singleton instance. ```APIDOC ## Factory Function and Default Instance ### Description This section describes how to create and access logger instances. ### Factory Function - **createLogger(options?: LoggerOptions): Logger** Factory function to create a new logger instance with optional configuration. ### Default Instance - **log: Logger** The default singleton logger instance. ``` -------------------------------- ### Import Kernel and Plugin Factories from @oxog/plugin Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Import the kernel factory and plugin definition helper from the @oxog/plugin package to manage the micro-kernel architecture. ```typescript import { createKernel, definePlugin } from '@oxog/plugin'; ``` -------------------------------- ### Performance Timing with `time` and `timeEnd` Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Shows how to measure the duration of operations using `log.time` and `log.timeEnd`. The output includes the duration in milliseconds. ```typescript log.time('db-query'); await database.query('SELECT * FROM users'); log.timeEnd('db-query'); // Output: {"level":30,"msg":"db-query","duration":45,"unit":"ms"} ``` -------------------------------- ### File Transport Configuration Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Set up the file transport to log to a file with features like daily rotation, size limits, and compression. ```typescript // File transport import { fileTransport } from '@oxog/log/transports'; fileTransport({ path: './logs/app.log', rotate: '1d', // Daily rotation maxSize: '10MB', // Max file size maxFiles: 7, // Keep 7 files compress: true, // Gzip old files }); ``` -------------------------------- ### Using External Colorify Plugin (Future) Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Illustrates a future scenario where an external plugin, like '@oxog/colorify', can be used as a drop-in replacement for internal plugins, maintaining the same interface. ```typescript import { colorify } from '@oxog/colorify'; log.use(colorify()); ``` -------------------------------- ### HTML Structure with SEO Meta Tags Source: https://github.com/ersinkoc/log/blob/main/docs/website-spec.md This snippet shows a basic HTML5 document structure including essential meta tags for SEO, Open Graph, and Twitter cards. Replace placeholders like {{PACKAGE_NAME}} with your specific content. ```html {{PACKAGE_NAME}} - {{SHORT_DESCRIPTION}}
``` -------------------------------- ### Browser Support - LocalStorage Persistence Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Demonstrates using `localStorageTransport` to persist specific log levels (e.g., errors) in the browser's local storage. ```typescript import { localStorageTransport } from '@oxog/log/transports'; log.use(localStorageTransport({ key: 'app-logs', maxSize: '1MB', levels: ['error', 'fatal'], // Only persist errors })); ``` -------------------------------- ### Implement Buffer Plugin Source: https://github.com/ersinkoc/log/blob/main/docs/IMPLEMENTATION.md This plugin buffers log entries and flushes them based on interval or size limits. It can also write logs directly if configured for synchronous operation. The plugin manages a buffer and a flush timer. ```typescript export function bufferPlugin(options: BufferOptions): LogPlugin { let buffer: LogEntry[] = []; let flushTimer: ReturnType | null = null; return { name: 'buffer', version: '1.0.0', install(kernel) { const flush = async () => { if (buffer.length === 0) return; const entries = [...buffer]; buffer = []; for (const transport of kernel.context.transports.values()) { if (transport.flush) { await transport.flush(); } } }; if (options.flushInterval) { flushTimer = setInterval(flush, options.flushInterval); } kernel.on('log', async (entry: LogEntry) => { const sync = kernel.context.config.sync[entry.levelName] ?? false; if (sync) { // Write directly for (const transport of kernel.context.transports.values()) { await transport.write(entry); } } else { // Buffer buffer.push(entry); if (buffer.length >= (options.size || 100)) { await flush(); } } }); }, async onDestroy() { if (flushTimer) { clearInterval(flushTimer); } // Final flush if (buffer.length > 0) { for (const entry of buffer) { // Final flush logic } } } }; } ``` -------------------------------- ### Enable Colored Output with @oxog/pigment Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt-v2.md Configure the logger to use pretty formatting with colors enabled, leveraging the @oxog/pigment library for visually appealing log output. Supports semantic colors like 'success'. ```typescript import { createLogger } from '@oxog/log'; const log = createLogger({ format: 'pretty', colors: true // Uses @oxog/pigment }); log.info('Info message'); // Blue log.warn('Warning'); // Yellow log.error('Error!'); // Red log.debug('Debug'); // Gray log.success('Done!'); // Green (via semantic colors) ``` -------------------------------- ### LocalStorage Transport Configuration (Browser) Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Configure the localStorage transport for logging in browser environments, with options for key, size limits, and log levels. ```typescript // localStorage transport (browser) import { localStorageTransport } from '@oxog/log/transports'; localStorageTransport({ key: 'app-logs', maxSize: '1MB', levels: ['error', 'fatal'], }); ``` -------------------------------- ### LoggerOptions Interface Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Defines the configuration options available for creating a logger instance. Includes settings for name, level, format, transports, redaction, source, timestamp, performance, and context. ```typescript /** * Logger configuration options. * * @example * ```typescript * const log = createLogger({ * name: 'my-app', * level: 'debug', * format: 'pretty', * }); * ``` */ export interface LoggerOptions { /** * Logger name, included in all entries. * @default 'app' */ name?: string; /** * Minimum log level to output. * @default 'info' */ level?: LogLevel; /** * Output format. * - 'json': Structured JSON (production) * - 'pretty': Human-readable (development) * - 'auto': Based on NODE_ENV * @default 'auto' */ format?: 'json' | 'pretty' | 'auto'; /** * Output transports. * @default [consoleTransport()] */ transports?: Transport[]; /** * Fields to redact from output. * Supports dot notation for nested paths. * @example ['password', 'user.token'] */ redact?: string[]; /** * Include source file and line number. * @default false */ source?: boolean; /** * Include ISO 8601 timestamp. * @default true */ timestamp?: boolean; /** * Sync/async mode per level. * @default { fatal: true, error: true } */ sync?: Partial>; /** * Buffer configuration for async logging. */ buffer?: BufferOptions; /** * Static context added to all entries. */ context?: Record; /** * Initial plugins to load. */ plugins?: LogPlugin[]; } ``` -------------------------------- ### Buffer Options Interface Source: https://github.com/ersinkoc/log/blob/main/docs/SPECIFICATION.md Configuration options for log buffering, specifying buffer size and flush interval. ```typescript interface BufferOptions { size?: number; flushInterval?: number; } ``` -------------------------------- ### Package Dependencies (JSON) Source: https://github.com/ersinkoc/log/blob/main/docs/oxog-log-prompt.md Specifies that the @oxog/log package has zero runtime dependencies and no external packages, adhering to its foundation package role. ```json { "dependencies": {} } ``` -------------------------------- ### Source Location Configuration Source: https://github.com/ersinkoc/log/blob/main/llms.txt Enable logging of the source file and line number where the log message originated. Useful for debugging. ```typescript const log = createLogger({ source: true }); log.info('Debug me'); // Output: {"level":30,"file":"app.ts","line":42,"msg":"Debug me"} ``` -------------------------------- ### Sync Logging Configuration Source: https://github.com/ersinkoc/log/blob/main/llms.txt Configure synchronous logging for critical levels like 'fatal' and 'error'. This ensures these logs are written before the process exits. ```typescript // Fatal/error logs are sync by default - written before process.exit() const log = createLogger({ sync: { fatal: true, error: true } }); ```