npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rng-logger

v13.0.1

Published

Angular Reactive Logging framework

Downloads

13

Readme

Coverage Status

RNgLogger

The Reactive Angular Logging framework you wanted!

RNgLogger is a logging API that abstract the log stream from the actual log handler, allowing supporting multiple log targets at the same time within your Angular Application.

Easily switch between platforms (browser, server) with different logging handlers using the same API.

This library does not enforce to adhere to any rigid system, you're free to react and interact with logs your way.

Straightforward replace for console usage!

From console.info("message") To LoggerFactory().info("message")

Features

  • Simple logger interface as a reduced set of window.console
  • Opt-in replacement for your un-wanted console.log statements
  • Configurable level filtering and Log retention
  • RX.JS based log stream handler allow multiple targets at the same time (console, FileSystem, Http Endpoints etc...)
  • Angular Platform Logger allow to use the logger interface by Injection and via LoggerFactory() as most of the Logging frameworks
  • No operation Logger (NOP) is provided by default when the logger it's not provided or cannot be resolved. (can be configured to throw error)
  • Logger can be used anywhere, libraries included, and when the application does not register it's just a NOP implementation
  • Typescript decorators for contextual logging hooks
  • Straightforward testing
  • A built-in window.console handler for Platform browser apps!

Getting started

RNgLogger is an Angular platform tool, to use it you must register the required providers at platform level.

NPM install:

npm i rng-logger

Register the platform Logger

In your Angular application entry (usually main.ts file), add the RNgPlatformLogger factory call.

import {LogLevel, PLATFORM_CONSOLE_LOGGER, RNgPlatformLogger} from "rng-logger";

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic(
    RNgPlatformLogger(), // platForm
).bootstrapModule(AppModule)
  .catch(err => console.error(err));

RNgPlatformLogger is a factory that returns the providers required for the platform, and accept a configuration if needed.

To Change the default configuration, you can apply like this:

import {LogLevel, PLATFORM_CONSOLE_LOGGER, RNgPlatformLogger} from "rng-logger";

RNgPlatformLogger({
      level: environment.production ? LogLevel.ERROR : LogLevel.TRACE, // log level
      maxBuffer: 100, // max items to retain
      nonResolvedStrategy: "ERROR" // strategy when Logger is not resolved
})

Register a handler or create your own

A handler is an object that subscribe to the logger stream to produce an effect, for instance logging with the console.

To use the provided console logger (browser only), just add the provider to the platform:

import {LogLevel, PLATFORM_CONSOLE_LOGGER, RNgPlatformLogger} from "rng-logger";

platformBrowserDynamic([
    ...RNgPlatformLogger(),
    PLATFORM_CONSOLE_LOGGER // PLATORM CONSOLE LOGGER 
  ]
).bootstrapModule(AppModule)
  .catch(err => console.error(err));

PLATFORM_CONSOLE_LOGGER uses window.console to output the log stream.

You can supply multiple Handlers via PLATFORM_INITIALIZER (by registering at platform creation) or APP_INITIALIZER (in App modules). Also, creating an instance of the handler in the module instantiation is possible, not recommended tough.

An example function of a log handler is like this:

export function myHttpLogHandler(handler: LogStreamHandler, httpClient: HttpClient) {
  return () => {
    handler.last$()
      .pipe(switchMap(e => {
        return httpClient.post(`/api/log-service/${e.time.getTime()}`, {event: e.message, data: e.options})
      }))
      .subscribe(next => {})
  }
}

export const MY_HTTP_LOG_HANDLER: StaticProvider = {
  provide: APP_INITIALIZER,
  multi: true,
  useFactory: myHttpLogHandler,
  deps: [LogStreamHandler, HttpClient]
};

@NgModule({
  providers: [
    MY_HTTP_LOG_HANDLER
  ]
})
export class MyAppModule {}

Using the logger

RNgLogger can be used via injection or by using the LoggerFactory.

The factory is a quite common pattern if you come from SLF4J, Log4j and many others.

The factory can return the root logger (Platform) directly when used with no-args, or an injector logger by providing the injector.

Example of the Platform logger factory:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  private readonly logger: Logger = LoggerFactory(); // get platform logger
  constructor() {}
  ngOnInit(): void {
    this.logger.info("App started");
  }
}

Example of injected logger:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  constructor(private logger: Logger) {}
  ngOnInit(): void {
    this.logger.info("App started");
  }
}

Example of logger factory via Injector:

@Directive({
  selector: 'my-directive',
})
export class MyDirective implements OnInit{
  constructor(private viewRef: ViewContainerRef) {}
  ngOnInit(): void {
    LoggerFactory(this.viewRef.injector).warn("Injector factory")
  }
}

Using decorators

RNgLogger comes with handy decorators to allow your Components or Services methods to being logged when called.

The @Log decorator can be applied to class methods, and the log output takes care of including the originating class, method, arguments and custom message.

Example of using @Log in component methods

export class MyLoggedComponent implements OnInit{
  private toggle = false;
  constructor(){}

  @Log()
  ngOnInit(): void {}

  @Log({
    message: "Toggled!",
    level: LogLevel.INFO
  })
  toggle() {
    this.toggle = !this.toggle;
  }

  @Log({
    level: LogLevel.WARN
  })
  warning(message: MessageObject, scopes: Scope[]): void {}

}

These @Log decorated methods will emit logs messages in the format below for the appropriate level:

MyLoggedComponent::ngOnInit

MyLoggedComponent::toggle Toggled!

MyLoggedComponent::warning  {...}, [...] // values not represented here

For libraries creators

When creating a library only want to add RngLoggerModule as an import to use the Logger interface. It's then the consumer of your library to decide if, when and how to log your library. If you provide rng-logger as a logging dependency, make sure your readme contains the link to this documentation to allow the user to configure the logger.

Versions

rng-logger major version follows to the Angular major version, if there's no target for the release just open an issue.

Known Limitations

  • LoggerFactory cannot be referenced as a static member because the Angular Platform is not available and any call to getPlatform will return null.
    • use private readonly logger: Logger = LoggerFactory(); and not private static readonly logger: Logger = LoggerFactory();