tslog: Universal TypeScript Logger
tslog is an extensible logging library designed for both Node.js and browser environments, written in TypeScript. Currently stable at version 4.10.2, it maintains an active release cadence with frequent updates and bug fixes, often addressing compatibility and build issues. Key differentiators include its universal compatibility (Node.js, Browsers, Deno, Bun), full TypeScript support with native source map integration for accurate stack traces, and flexible output options (pretty or JSON). It also handles circular structures, supports sub-loggers, allows object and error interpolation, and features masking for sensitive data, making it suitable for a wide range of application logging needs. The library has zero external dependencies, promoting a lightweight footprint.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\path\to\node_modules\tslog\dist\index.js not supported.
cause Attempting to `require()` an ESM module (`tslog`) in a CommonJS context without proper interoperability settings or when the project is configured for ESM.fixFor ESM projects, use `import { Logger } from 'tslog';`. For CJS projects that need to import an ESM module, you might need to use dynamic `import()` or configure `esModuleInterop: true` in `tsconfig.json` and adjust runtime environment if `type: module` is present in the dependency but not in your project. Alternatively, ensure Node.js is run in a CJS context for CJS bundle of tslog by explicitly calling `node dist/index.cjs` after compilation. -
TypeError: tslog.Logger is not a constructor
cause This usually occurs in a browser environment when the `tslog` script has been loaded via a `<script>` tag, but the `Logger` class is attempted to be imported as an ESM module, or `tslog` global isn't correctly exposed.fixIf loading `tslog` via a `<script>` tag, access `Logger` through the global `tslog` object: `const logger = new tslog.Logger();`. If using a build tool, ensure it correctly handles ESM imports for browser environments. -
Log messages show incorrect file names or line numbers in stack traces (e.g., pointing to `tslog` internal files or transpiled JS).
cause Source map support is not correctly configured or enabled, preventing `tslog` from mapping back to your original TypeScript source code.fixEnsure `"sourceMap": true` is set in your `tsconfig.json`. When running your Node.js application, include the `--enable-source-maps` flag: `node --enable-source-maps dist/your-app.js`. For `ts-node`, use `--loader ts-node/esm` (ESM) or `--require ts-node/register` (CJS) with `--enable-source-maps`.
Warnings
- breaking In `v4.10.0`, the `transportFormatted` override function signature changed. It now receives `logMeta` as the fourth argument. Implementations that previously read `settings` from the fourth position need adjustment. Pass five parameters to also receive `settings`.
- breaking As of `v4.10.0`, deprecated runtime entry points under `src/runtime/**` and related browser mappings have been removed. Direct imports from these paths will no longer work.
- gotcha For accurate stack traces with TypeScript in Node.js, it is crucial to enable source maps. This requires configuring `sourceMap: true` in `tsconfig.json` and running Node.js with the `--enable-source-maps` flag.
- gotcha When using `tslog` in a Node.js project, especially with TypeScript, it's recommended to set `"type": "module"` in your `package.json` for native ESM support. This affects how imports are resolved and how CommonJS modules interoperate.
- gotcha By default, `tslog` is optimized for developer experience, which includes settings that might impact performance in production. For optimal production performance, review and adjust settings like `hideLogPositionForProduction`.
Install
-
npm install tslog -
yarn add tslog -
pnpm add tslog
Imports
- Logger
const { Logger } = require('tslog');import { Logger } from 'tslog'; - ILogObj
import type { ILogObj } from 'tslog';import { ILogObj } from 'tslog'; - tslog (browser global)
import { Logger } from 'tslog'; // in browser script tag without build toolconst logger = new tslog.Logger();
Quickstart
import { Logger, ILogObj } from "tslog";
// Create a new logger instance with optional configuration
const log: Logger<ILogObj> = new Logger({
name: "myAppLogger",
minLevel: 3, // info and above
prettyLogTemplate: "{{logLevelName}} {{name}} " // Customize output template
});
// Log various messages
log.silly("This is a silly message and will not show with minLevel 3.");
log.trace("Tracing code execution.");
log.debug("Debugging a variable: ", { userId: 123, data: "test" });
log.info("Application started successfully.");
log.warn("Deprecated feature in use.");
log.error("An unexpected error occurred.", new Error("File not found"));
log.fatal("Critical system failure!");
// Example of a child logger for a specific module
const userModuleLog = log.getChildLogger({ name: "UserModule" });
userModuleLog.info("User 'admin' logged in.");