How to: Extend the Aurelia Logger with additional methods

戏子无情 提交于 2019-12-23 05:36:33

问题


Foremost I am following this example on implementing and customizing the aurelia-logger.

This approach only works fine. Any changes to the existing methods in the custom appender work fine. However if I change the CustomLogAppender.js to

export class CustomLogAppender {
  constructor(){}
  debug(logger, message, ...rest){
    console.debug(`DEBUG [${logger.id}] ${message}`, ...rest);
  }
  info(logger, message, ...rest){
    console.info(`INFO [${logger.id}] ${message}`, ...rest);
  }
  warn(logger, message, ...rest){
    console.warn(`WARN [${logger.id}] ${message}`, ...rest); 
  }
  error(logger, message, ...rest){
    console.error(`ERROR [${logger.id}] ${message}`, ...rest);
  }
  newMethod(logger, message, ...rest){
    //whatever
  }
}

Then logger.newMethod(“send error to backend”); is not a defined method when called in a view-model. I am trying to write additional logging methods that can send warns, info, errs, etc to the back-end for database logging should i deem it necessary but am having trouble adding these methods to the aurelia-logger. Any guidance would be appreciated.


回答1:


If you are following the example from the URL, the following lines are relevant for your: https://github.com/aurelia/logging/blob/21d92e79a5f924b25b1eae0648af5a7a0ab44527/src/index.js#L96-L115

As you can see, it creates a logger, which only has the default methods, i.e. what you get returned is not exactly your logger. What you need to do is enhance the existing methods (in there, you can use your custom methods).

See the following appender as an example:

import { inject } from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
import {Logger} from 'aurelia-logging';

@inject(HttpClient)
export class ServerLogAppender {
    constructor(http) {
        this.http = http;
    }

    debug(logger, message, ...rest) {
        this.sendToServer(logger, message, ...rest);
    }

    info(logger, message,...rest){
        this.sendToServer(logger, message,...rest);
    }

    warn(logger, message,...rest){
        this.sendToServer(logger, message,...rest);
    }

    error(logger, message,...rest){
        this.sendToServer(logger, message,...rest);
    }

    sendToServer(logger, message,...rest){
        this.http.post('myerrorhandler', {
            url: window.location.href,
            source: logger.id,
            message: message,
            additional: rest.join('\r\n')
        });
    }
}

As you can see, the default methods (debug, info, warn, error) use the custom method sendToServer().



来源:https://stackoverflow.com/questions/41448108/how-to-extend-the-aurelia-logger-with-additional-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!