Implementing Log Services in Angularjs

Source: Internet
Author: User
Tags print format

This experience uses ANGULARJS to customize a logging service.

In Angularjs, some of the service's formulations are:

var app = Angular.module (' app ', []); App.provider (function() {...}); App.service (function() {}); App.factory (function() {});

Equivalent to:

function ($provide) {    $provide. Provider (function() {...})}]) App. Config ([function($provide) {    $provide. Service (function() {...})}]) App. Config ([function($provide) {    $provide. Factory ()} (function() { ...});}])

In fact, $provider. Service () and $provider.factory () can also be implemented by $provider.provider () in an injected manner.

function ($provide) {    $provide. Service (function() {        this. Name = "";          this. Author = "";    })}])

The above is equivalent to:

function ($provide, $injector) {    $provide. Provider (function() {       this  function($injector) {        return $injector. Instantiate () (function() {             this. Name = "";             this. Author = "";     });})

Above, that is, the service itself is a provider that can be initialized by $injector to a service.

In the same vein, we write factory:

function ($provide) {    $provide. Factory (function() {        return {name: ', Author: '} ;    })}])

The above is equivalent to:

App. Config ([' $provide ', ' $injector ',function($provide, $injector) {    $provide. Provider (  function() {        thisfunction($injector) {            return $ Injector.invoke (function() {                return {name: ', Author: '}})}    ) }])

Create your own provider

function () {    var color = ' red ';          This function (newcolor) {        = newcolor;    }         function () {        return  color;    }})

We can make some settings in config using Appcolor, the custom provider method.

function (appcolorprovider) {    appcolorprovider.setcolor (' green ');}])

Then inject the Appcolor service into the run.

App.run ([' Appcolor ', Funciton (appcolor) {    console.log (appcolor);}])
Create a log service



Suppose you need the following log format:

<timestamp>-<context>::<method name> (' <message> ')
<timestamp>-<context>: <message>

Create a class about the log:

varLogger =function(context) { This. Context =context;} Logger.getinstance=function(context) {return NewLogger (context);}//AlternativeLogger.supplant =function(str, o) {returnStr.replace (/\{([^{}]*) \}/g,function(A, b) {varR =O[b]; return typeofr = = = ' String ' | |typeofr = = = ' Number '?r:a; })}//format TimeLogger.getformattedtimestamp =Funciton (date) {returnLogger.supplant (' {0}:{1}:{2}:{3} ', [Date.gethours (), Date.getminutes (), Date.getseconds (), Date.getmilleseconds ()]);} Logger.prototype={_log:function(ORIGINALFN, args) {varnow = Logger.getformattedtimestamp (NewDate ()); varMessage = "', Supplantdate = []; Switch(args.length) {//print format:<timestamp>-<context>: <message>             Case1: Message= Logger.supplant ("{0}-{1}:{2}", [Now, This. Context, Args[0]]);  Break;  Case3:                //print Format:<timestamp>-<context>::<method name> (' <message> ')                //The first parameter is a method name                //The second argument is a message                //The third parameter is the objectSupplantdata = args[2]; Message= Logger.supplant ("{0}-{1}::{1} (\ ' {3}\ ')", [Now, This. Context, Args[0], args[1]]);  Break;  Case2:                //Detecting the second parameter type                if(typeofARGS[1] = = = ' String ') {Message= Logger.supplant ("{0}-{1}::{2} (\ ' {3}\ ')", [Now, This. Context, Args[0], args[1]]); } Else{sup;antdata= Args[1]; Message= Logger.supplant ("{0}-{1}:{2}", [Now, This. context.args[0]])                }                 Break; } $log [Originalfn].call (NULL, logger.supplant (message, suppantdata)); }, log:function(){         This. _log (' log ', arguments); }, Info:function(){         This. _log (' info ', arguments); }, warn:function(){         This. _log (' Warn ', arguments); }, Debug:function(){         This. _log (' Debug ', argments); }, Error:function(){         This. _log (' ERROR ', arguments); }};

We may use this log class as follows:

// example is the name of a class or file or module var logger = logger.getinstance (' Example '); Logger.log (' This is a alog '); Logger.warn (' warn ', ' This was a worn '); Logger.error (' This is a {0} ' error {1} ', [' big ', ' hello ']);

The complete code is as follows:

App.provider (' Logger ', [function(){    varIsEnabled =true;  This. Enabled =function(_isenabled) {isenabled= !!_isenabled; }         This. $get = [' $log ',function($log) {varLogger =function(context) { This. Context =context; } logger.getinstance=function(context) {return NewLogger (context); }    //AlternativeLogger.supplant =function(str, o) {returnStr.replace (/\{([^{}]*) \}/g,function(A, b) {varR =O[b]; return typeofr = = = ' String ' | |typeofr = = = ' Number '?r:a; })    }    //format TimeLogger.getformattedtimestamp =Funciton (date) {returnLogger.supplant (' {0}:{1}:{2}:{3} ', [Date.gethours (), Date.getminutes (), Date.getseconds (), Date.getmillesecon    DS ()]); } Logger.prototype={_log:function(ORIGINALFN, args) {if(!isenabled) {                return; }                    varnow = Logger.getformattedtimestamp (NewDate ()); varMessage = "', Supplantdate = []; Switch(args.length) {//print format:<timestamp>-<context>: <message>                 Case1: Message= Logger.supplant ("{0}-{1}:{2}", [Now, This. Context, Args[0]]);  Break;  Case3:                    //print Format:<timestamp>-<context>::<method name> (' <message> ')                    //The first parameter is a method name                    //The second argument is a message                    //The third parameter is the objectSupplantdata = args[2]; Message= Logger.supplant ("{0}-{1}::{1} (\ ' {3}\ ')", [Now, This. Context, Args[0], args[1]]);  Break;  Case2:                    //Detecting the second parameter type                    if(typeofARGS[1] = = = ' String ') {Message= Logger.supplant ("{0}-{1}::{2} (\ ' {3}\ ')", [Now, This. Context, Args[0], args[1]]); } Else{sup;antdata= Args[1]; Message= Logger.supplant ("{0}-{1}:{2}", [Now, This. context.args[0]])                    }                     Break; } $log [Originalfn].call (NULL, logger.supplant (message, suppantdata)); }, log:function(){             This. _log (' log ', arguments); }, Info:function(){             This. _log (' info ', arguments); }, warn:function(){             This. _log (' Warn ', arguments); }, Debug:function(){             This. _log (' Debug ', argments); }, Error:function(){             This. _log (' ERROR ', arguments);                    }    }; returnLogger; }]}])

The custom logger is turned off globally.

function (loggerprovider) {    loogerprovider.enabled (false);}])


Reference: http://www.webdeveasy.com/service-providers-in-angularjs-and-logger-implementation/

Implementing Log Services in Angularjs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.