Angular2 Logging [closed]

2020-05-25 07:55发布

I am looking to introduce logging to an angular2 app and want to check any good libraries or approaches you could recommend on this.

Requirements for logging are:

  • Will have options configure logging like info, warn, error, debug and verbose.
  • Will be able to keep logs into local storage and then after a certain interval sync the logs to a server end point
  • Will be able to support Json format and have control over the log format

Requirement below would be nice to have and any experience on working with web worker that you can share would be appreciated.

  • Would be nice to have the logging function build as a web-worker so away from browser thread and we could potentially use app cache as temporary storage?

Any advice on this would be much appreciated.

3条回答
淡お忘
2楼-- · 2020-05-25 08:19

You can use ngx-logger

NGX Logger is a simple logging module for angular (currently supports angular 4.3+). It allows "pretty print" to the console, as well as allowing log messages to be POSTed to a URL for server-side logging.

Installation

npm install --save ngx-logger

Once installed you need to import our main module:

import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';

The only remaining part is to list the imported module in your application module, passing in a config to intialize the logger.

@NgModule({
  declarations: [AppComponent, ...],
  imports: [LoggerModule.forRoot({serverLoggingUrl: '/api/logs', level: NgxLoggerLevel.DEBUG, serverLogLevel: NgxLoggerLevel.ERROR}), ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Usage

To use the Logger, you will need import it locally, then call one of the logging functions

import { Component } from '@angular/core';
import { NGXLogger } from 'ngx-logger';

@Component({
  selector: 'your-component',
  templateUrl: './your.component.html',
  styleUrls: ['your.component.less'],
  providers: [NGXLogger]
})
export class YourComponent {
    constructor(private logger: NGXLogger) {
        this.logger.debug('Your log message goes here');
        this.logger.debug('Multiple', 'Argument', 'support');
    };
}

Config Options

serverLogLevel - Only sends logs to the server for the level specified or higher (OFF disables the logger for the server) serverLoggingUrl - URL to POST logs level: The app will only log message for that level or higher (OFF disables the logger for the client) enableDarkTheme: Sets the default color to white instead of black TRACE|DEBUG|INFO|LOG|WARN|ERROR|OFF Server Side Logging

If serverLogginUrl exists, NGX Logger will attempt to POST that log to the server.

Payload Example {level: 'DEBUG', message: 'Your log message goes here'}

You can read the documentation as well for the same. https://www.npmjs.com/package/ngx-logger

查看更多
女痞
3楼-- · 2020-05-25 08:37

angular2-logger A simpler Log4j inspired logger module for Angular 2.

1) Install the npm module.

npm install --save angular2-logger

2) Add the angular2-logger library to your app. If you are following the Angular 2's Quickstart Guide it should be something like this:

In systemjs.config.js:

    // map tells the System loader where to look for things
 var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs',
    'angular2-logger':            'node_modules/angular2-logger' // ADD THIS
 };

 //packages tells the System loader how to load when no filename and/or no extension
 var packages = {
    'app':                        { main: 'main.ts',  defaultExtension: 'ts' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
    'angular2-logger':            { defaultExtension: 'js' }, // AND THIS
 };

3) Setup the Provider. In app.module.ts:

import { NgModule }      from '@angular/core';
 import { BrowserModule } from '@angular/platform-browser';
 import { AppComponent }  from './app.component';
 import { Logger } from "angular2-logger/core"; // ADD THIS

 @NgModule({
     imports:      [ BrowserModule ],
     declarations: [ AppComponent ],
     bootstrap:    [ AppComponent ],
     providers:    [ Logger ] // AND THIS
 })
 export class AppModule { }

4) Inject the logger into your objects and use it.

@Component({
    ...
 })
 export class AppComponent(){
    constructor( private _logger: Logger ){
        this._logger.error('This is a priority level 1 error message...');
        this._logger.warn('This is a priority level 2 warning message...');
        this._logger.info('This is a priority level 3 warning message...');
        this._logger.debug('This is a priority level 4 debug message...');
        this._logger.log('This is a priority level 5 log message...');
    }
 }

In order to see all of the messages you just need to change the logger message hierarchy level, you can do so:

logger.level = logger.Level.LOG; // same as: logger.level = 5;   

Or using one of the predefined configuration providers:

import {LOG_LOGGER_PROVIDERS} from "angular2-logger/core";

  @NgModule({
      ...
      providers:    [ LOG_LOGGER_PROVIDERS ]
  })
  export class AppModule { }

The available Providers are:

  ERROR_LOGGER_PROVIDERS
  WARN_LOGGER_PROVIDERS
  INFO_LOGGER_PROVIDERS
  DEBUG_LOGGER_PROVIDERS
  LOG_LOGGER_PROVIDERS
  OFF_LOGGER_PROVIDERS
查看更多
家丑人穷心不美
4楼-- · 2020-05-25 08:41

I think JSNLog partly matches your requirements (I am the author of JSNLog).

JSNLog consists of a client side library jsnlog.js and a server side component. The client side library sends log items to the server side component in AJAX requests. Once on the server, the log items are stored in your server side log. The .Net 4.x version uses Common.Logging, to support Log4Net, NLog, Elmah and Serilog logs. The .Net Core version supports the Core logging framework.

Matching JSNLog features with your requirements:

Will have options configure logging like info, warn, error, debug and verbose.

JSNLog supports Log4Net severity levels: Trace, Debug, Info, Warn, Error, Fatal. Additionally, you can use numeric severity levels, giving you as many severity levels as you want.

Will be able to keep logs into local storage and then after a certain interval sync the logs to a server end point

JSNLog allows you to batch a configurable number of log items in each message to the server. It also supports setting a maximum time that any message sits in the buffer before being sent.

Additionally, JSNLog lets you store log items of low severity in client side memory, and only send them to the server when a high severity log item is sent. For example, you can log Trace events in case an exception happens, and only send them to the server when an exception does happen and logs a Fatal event.

Will be able to support Json format and have control over the log format

JSNLog allows you to log JSON objects. If you use Serilog on the server, you can store these objects as objects rather than strings. Also, you can set an event handler on jsnlog.js that allows you to modify the outgoing log item.

Would be nice to have the logging function build as a web-worker ...

JSNLog isn't a web worker.

查看更多
登录 后发表回答