TypeScript Logging Log4TS Style
typescript-logging-log4ts-style is a logging library for TypeScript projects, providing a Log4TS-inspired flavor built upon the `typescript-logging` core. It allows developers to create hierarchical loggers based on unique names, often corresponding to namespaces or logical groups (e.g., 'service.Account'). The library emphasizes structured output and dynamic control over logging levels. The current stable version is 2.2.0, with regular updates incorporating new features like file logging and rollover support as seen in version 2.2.0. It differentiates itself by offering a familiar log4j-like API and configuration patterns, making it approachable for developers accustomed to enterprise logging solutions, while integrating seamlessly into modern TypeScript environments. Its modular design as a 'flavor' allows users to choose the logging style that best fits their project's needs.
Common errors
-
Cannot find module 'typescript-logging-log4ts-style' or its corresponding type declarations.
cause The package was not installed or installed incorrectly, or TypeScript cannot locate its types.fixEnsure both `typescript-logging` and `typescript-logging-log4ts-style` are installed: `npm install --save typescript-logging typescript-logging-log4ts-style`. -
TypeError: Cannot read properties of undefined (reading 'getLogger')
cause The `log4TSProvider` was not initialized or imported correctly, leading to an attempt to call a method on an `undefined` object.fixVerify that `Log4TSProvider.createProvider` is called before any `getLogger` calls, and that the provider object is correctly exported and imported across modules. -
Logging statements (e.g., `log.debug()`) are not appearing in the console or output.
cause The configured `LogLevel` for the provider or a specific group is set too high (e.g., `LogLevel.Error`), effectively filtering out lower-level messages.fixAdjust the `level` property in your `Log4TSProvider` configuration (e.g., to `LogLevel.Debug` or `LogLevel.Trace`) and ensure group expressions match your logger names. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use CommonJS `require()` syntax in an ESM project, or trying to import an ESM-only library with `require()`.fixUse ES Module `import` syntax (e.g., `import { Log4TSProvider } from 'typescript-logging-log4ts-style';`) and ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`).
Warnings
- breaking Major architectural changes occurred between version 1.x and 2.x of `typescript-logging`. Code written for 1.x is not directly compatible with 2.x and requires a migration.
- gotcha The `typescript-logging-log4ts-style` package is an add-on 'flavor' and requires the core `typescript-logging` package to be installed as a separate dependency.
- gotcha The `LogLevel.Off` enumeration was introduced in version 2.1.0. While minor, there is a small chance this could affect existing code if custom log level handling or comparisons were in place.
- gotcha To enable file logging and rollover support, the separate `typescript-logging-node-channel` package must be installed and configured in addition to the core and style packages.
Install
-
npm install typescript-logging-log4ts-style -
yarn add typescript-logging-log4ts-style -
pnpm add typescript-logging-log4ts-style
Imports
- Log4TSProvider
const Log4TSProvider = require('typescript-logging-log4ts-style');import { Log4TSProvider } from 'typescript-logging-log4ts-style'; - LogLevel
import { LogLevel } from 'typescript-logging-log4ts-style';import { LogLevel } from 'typescript-logging'; - Logger
import { Logger } from 'typescript-logging';
Quickstart
/*--- config/LogConfig.ts ---*/
import { LogLevel } from "typescript-logging";
import { Log4TSProvider } from "typescript-logging-log4ts-style";
export const log4TSProvider = Log4TSProvider.createProvider("AwesomeLog4TSProvider", {
level: LogLevel.Debug,
groups: [{
expression: new RegExp(".+")
}]
});
/*--- model/Account.ts ---*/
import { log4TSProvider } from "../config/LogConfig";
const log = log4TSProvider.getLogger("model.Account");
export interface Account {
name: string;
}
export function createAccount(name: string): Account {
log.debug(() => `Creating new account with name '${name}'.`);
return {name};
}
/*--- service/AccountService.ts ---*/
import { log4TSProvider } from "../config/LogConfig";
import { Account } from "../model/Account";
const log = log4TSProvider.getLogger("service.AccountService");
async function someUpdateHere() {
return new Promise(resolve => setTimeout(resolve, 100)); // Simulate async operation
}
export async function saveAccount(account: Account) {
log.debug(() => `Will save account '${account.name}'.`);
try {
await someUpdateHere();
}
catch (e) {
log.error(() => `Failed to save account '${account.name}'.`, e);
throw e;
}
}
/*--- Main.ts ---*/
import { log4TSProvider } from "../config/LogConfig";
import { createAccount } from "./model/Account";
import { saveAccount } from "./service/AccountService"; // Corrected import path
const log = log4TSProvider.getLogger("main");
/* Create an account and save it - log on success/error */
const account = createAccount("My Account");
saveAccount(account)
.then(() => {
log.debug("Successfully created account.", account.name);
})
.catch(e => {
log.error("Ooops...", e);
});