TypeScript Logging Log4TS Style

2.2.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a Log4TSProvider, configuring log levels and groups, creating named loggers, and using them across different modules for debugging and error logging.

/*--- 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);
  });

view raw JSON →