# @alterior/logging

> Configurable context-aware logging

Latest version **3.16.4** (published 2026-07-27) · MIT license · 0 weekly downloads

## Install

```sh
npm install @alterior/logging
pnpm add @alterior/logging
yarn add @alterior/logging
bun add @alterior/logging
```

## Health

**Score 60/100 (C)** — status: active.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 3.16.4 |
| Published | 2026-07-27 |
| First published | 2019-02-28 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=10 |
| Dependencies | 5 |
| Unpacked size | 213.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 16 |
| Author | The Alterior Project |
| Maintainers | rezonant |
| Keywords | logging, configurable, DI, zone |

## Links

- npm: https://www.npmjs.com/package/@alterior/logging
- Repository: https://github.com/alterior-mvc/alterior
- Homepage: https://github.com/alterior-mvc/alterior/blob/main/packages/logging/README.md
- Issues: https://github.com/alterior-mvc/alterior/issues
- npm.io page: https://npm.io/package/@alterior/logging

## Dependencies (5)

- [rxjs](https://npm.io/package/rxjs.md) ^7.8.0
- [@alterior/di](https://npm.io/package/@alterior/di.md) ^3.16.4
- [@alterior/common](https://npm.io/package/@alterior/common.md) ^3.16.4
- [@alterior/runtime](https://npm.io/package/@alterior/runtime.md) ^3.16.4
- [@alterior/annotations](https://npm.io/package/@alterior/annotations.md) ^3.16.4

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 3.16.4 (latest) — 2026-07-27
- 3.16.3 — 2026-07-22
- 3.16.2 — 2026-05-21
- 3.16.1 — 2026-05-21
- 3.16.0 — 2026-05-14
- 3.15.0 — 2026-02-22
- 3.14.3 — 2026-02-22
- 3.14.2 — 2026-02-22
- 3.14.1 — 2026-02-13
- 3.14.0 — 2026-01-25
- 3.13.4 — 2026-01-18
- 3.13.3 — 2026-01-18
- 3.11.1 — 2024-07-15
- 3.11.0 — 2024-07-15
- 3.10.0 — 2024-07-13
- … 67 more at https://npm.io/package/@alterior/logging/versions

## README

# @alterior/logging

[![Version](https://img.shields.io/npm/v/@alterior/logging.svg)](https://www.npmjs.com/package/@alterior/logging)

## Overview

Provides a dependency-injected logger with support for pluggable listeners and log context tracking using `Zone.js`

## Installation

```
npm install @alterior/logging
```

## Usage 

This module is intended to be used as part of an Alterior application. Several of the higher level first-party Alterior modules use this logger already, so it is a natural fit.

The module provides a `Logger` injectable when `LoggingModule` is imported into your Alterior application:

```typescript
@Module({
    imports: [ LoggingModule ]
})
export class MyEntryModule { }
```

Once the module is imported, you can inject `Logger` into your services, controllers, tasks, etc:

```typescript
import { Logger } from '@alterior/logging';
// ...

@Controller('/foo')
export class MyController {
    constructor(
        private logger : Logger
    ) {
    }

    @Get('/')
    get() {
        this.logger.info('Hello, world!');
    }
}

// [2019-03-05T00:12:44Z] [source="MyController"] info: Hello, world!
```

## Subloggers (Source Labels)

You may wish to specifically mark logs which came from a particular class (or any other programmatic unit):

```typescript

import { Logger } from '@alterior/logging';
// ...

@Injectable()
export class MyService {
    constructor(
        logger : Logger
    ) {
        this.logger = logger.withSource(this)
    }

    private logger : Logger;

    doSomething() {
        this.logger.info('Hello, world!');
    }
}

// [2019-03-05T00:12:44Z] [source="MyService"] info: Hello, world!
```

As you can see, `withSource(object)` will use the object's constructor name as the source label. You can also pass a string to set the source label to any string you wish.

## Context tracking

This library also provides "context tracking" using `Zone.js`. When using context tracking, logs which occur inside a code block will be specially marked, even if the code is asynchronous or delayed.

```typescript
logger.withContext({ myContextData: 123 }, `The data is 123`, () => {
    setTimeout(() => logger.info(`Hello, world!`), 1000);
});

// [2019-03-05T00:12:44Z] [context="The data is 123"] info: Hello, world!
```

This is the mechanism that allows `@alterior/web-server` and `@alterior/tasks` to include the current request trace inside logs generated by reusable services. This results in logs that are easier to follow,
especially when there is heavy concurrency within a single log file (ie web servers, task runners):

```
[2019-03-05T00:12:44Z] [source="MyService" context="GET /foo | 1443c985-c4be-47f7-9e9c-941c21913def"] info: Hello, world!
[2019-03-05T00:12:44Z] [source="MyService" context="TaskWorker | MyBackgroundWorker"] info: Hello, world!
```

## Configuration

To configure the module, import it into your entry module and specify options in the call to `configure()`:

```typescript
@Module({
    imports: [ LoggingModule.configure({ /* ... */ }) ]
})
export class MyEntryModule { }
```

### `listeners`

"Listeners" are responsible for reporting logs in one way or another. By default a sensibly-configured `ConsoleLogger` is used. If you wish to customize the format, you'll need to specify your own instance of `ConsoleLogger`. If an empty set of listeners is specified, logs will effectively be dropped, and the logger itself becomes a no-op.

## Log Objects

Log messages are passed to listeners as objects conforming to the `LogMessage` interface:

```typescript
export interface LogMessage {
    message : string;
    context : any;
    contextLabel : string;
    sourceLabel : string;
    severity : LogSeverity;
    date : Date;
}
```

It is the responsibility of the listener to decide how to format these log message objects. Some listeners may not format the object at all (for instance: recording logs to a collection in an object store like MongoDB).

## Log Formatting

Some built-in loggers use `LogFormatter` to handle transforming a log object into a string suitable for use on a screen, log file, etc. `LogFormatter` accepts a format string to determine how to transform the log message object into a string. Bare text is treated literally, and the fields of the `LogMessage` can be referenced by surrounding the name of the field with '%'. The default format for builtin listeners is:

```
%date% [source="%sourceLabel%" context="%contextLabel%"] %severity%: %message%
```

## Available Listeners

### `new ConsoleLogger(formatString)`

Outputs the log to the console using `console.log()` and friends. Accepts a format string suitable for use with `LogFormatter`.

### `new FileLogger(formatString, filename)`

Writes logs to the specified file. Accepts a format string suitable for use with `LogFormatter`.

## Execution Tracing

This library also provides `@Trace()`, a way to trace execution of one or more class methods 
automatically. When used outside of an Alterior application's execution context, tracing is 
always enabled. Within an Alterior app, you will have to specify `tracing: true` on the 
configuration for `LoggingModule` in order for `@Trace()` to be effective.

The log messages generated by `@Trace()` will be output using `Logger.current`. By default 
this will print to the console, but this can be changed by configuring `LoggerModule` in your
application, or by simply constructing a new `Logger` and executing your code using `logger.run()`.

---
_Source: https://npm.io/package/@alterior/logging · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
