TypeScript Logging Category Style
This package provides the "category style" flavor for the `typescript-logging` library, enabling hierarchical and topological logging structures. It allows applications to create a tree of loggers, where each `Category` can have child categories, facilitating fine-grained control over logging levels and output for specific application modules or concerns. For instance, a "Performance" category can have subcategories, and logging can be enabled/disabled at any level of this hierarchy. The current stable version is 2.2.0, with frequent minor and patch releases, typically driven by feature additions (like file logging support in 2.2.0 via `typescript-logging-node-channel`) or bug fixes. It differentiates itself by offering this unique tree-based categorization over other flat logging approaches, built specifically for TypeScript projects to leverage its type system.
Common errors
-
Error: Cannot find module 'typescript-logging' or 'typescript-logging-category-style'
cause One of the required packages (`typescript-logging` or `typescript-logging-category-style`) is not installed.fixRun `npm install --save typescript-logging typescript-logging-category-style` to install both packages. -
TypeError: (0 , typescript_logging_1.CategoryProvider).createProvider is not a function
cause This error typically occurs when trying to use CommonJS `require()` syntax with an ES Module, or if the module is not correctly imported/transpiled in your environment (e.g., Node.js without proper ESM setup or bundler issues).fixEnsure you are using ES Module `import` syntax (`import { CategoryProvider } from 'typescript-logging-category-style';`) and that your project is configured for ESM, especially in Node.js environments (e.g., `"type": "module"` in `package.json`). -
No log messages appear in the console/output.
cause The configured log level for a `CategoryProvider` or individual `Category` is too high, or no appender is configured to process the log events.fixCheck the `level` option in `CategoryProvider.createProvider` (e.g., `level: LogLevel.Debug`). Ensure at least one appender is configured for your `CategoryProvider` or globally in `typescript-logging` to output logs (e.g., a console appender).
Warnings
- breaking Upgrading from `typescript-logging` version 1.x to 2.x involves significant changes. The API for configuration and category creation has evolved. Review the official migration guide for specific details.
- gotcha This package (`typescript-logging-category-style`) is a 'flavor' and requires the core `typescript-logging` package as a peer dependency. Forgetting to install `typescript-logging` will lead to runtime errors.
- gotcha The `LogLevel.Off` enum member was introduced in version 2.1.0. If you are using `LogLevel.Off` (e.g., for disabling a logger) and targeting an older version or have mixed versions, it might not be recognized or behave as expected.
Install
-
npm install typescript-logging-category-style -
yarn add typescript-logging-category-style -
pnpm add typescript-logging-category-style
Imports
- LogLevel
import { LogLevel } from 'typescript-logging-category-style';import { LogLevel } from 'typescript-logging'; - CategoryProvider
const { CategoryProvider } = require('typescript-logging-category-style');import { CategoryProvider } from 'typescript-logging-category-style'; - Category
import { Category } from 'typescript-logging';import { Category } from 'typescript-logging-category-style';
Quickstart
import {LogLevel} from "typescript-logging";
import {CategoryProvider, Category} from "typescript-logging-category-style";
// --- Configuration (LogConfig.ts logic) ---
const provider = CategoryProvider.createProvider("ExampleProvider", {
level: LogLevel.Debug,
// Optional: Add a simple appender for console output if not already configured globally
// appenders: { default: { type: 'console' } }
});
// Create some root categories for this example
const rootModel = provider.getCategory("model");
const rootService = provider.getCategory("service");
const rootMain = provider.getCategory("main");
// --- Model (Account.ts logic) ---
const modelLog = rootModel.getChildCategory("Account");
interface Account {
name: string;
}
function createAccount(name: string): Account {
modelLog.debug(() => `Creating new account with name '${name}'.`);
return {name};
}
// --- Service (AccountService.ts logic) ---
const serviceLog = rootService.getChildCategory("AccountService");
// Mock function for demonstration
async function someExternalApiCall(): Promise<void> {
return new Promise(resolve => setTimeout(resolve, 50)); // Simulate async work
}
async function saveAccount(account: Account) {
serviceLog.debug(() => `Will save account '${account.name}'.`);
try {
await someExternalApiCall();
serviceLog.info(() => `Account '${account.name}' saved successfully.`);
}
catch (e) {
serviceLog.error(() => `Failed to save account '${account.name}'.`, e);
throw e;
}
}
// --- Main Application Logic (Main.ts logic) ---
(async () => {
rootMain.info(() => "Application starting...");
const newAccount = createAccount("JaneDoe");
try {
await saveAccount(newAccount);
} catch (error) {
rootMain.error(() => "Error during account operations.", error);
}
rootMain.info(() => "Application finished.");
})();