开发者

Is it possible to write a JavaScript log class like this?

I want to write some log class that can be used like the following code.

// short-hand for logging.
log('log message', [other parameter]);

// full path for writing log.
log.write('log message', [other parameter]);

// print all log
log.print([optional parameter]);

Moreover, it must able to be written as fluent pattern.

log.write('log message').print();

Finally, it should be resetted by using the following code.

log = new log();

T开发者_StackOverflow社区hanks,


Let's implement it as a normal object first, then add some other syntaxes after:

var log = {};

log.write = function() {
    // stuff...
    return this;
};

log.print = function() {
    // stuff...
    return this;
};

log.reset = function() {
    // stuff
    return this;
};

As function is also an object, it can have properties, so you can replace var log = {};, with a function that redirects to log.write instead.

function log() {
    return log.write.apply(log, arguments);
}

Finally, for the self-reset syntax, you can detect for a new instance, but instead of creating a new object, you reset the log and hand the same object back!

So now the log function will look like this:

function log() {
    if (this instanceof log) {
        return log.reset.apply(log, arguments);
    }
    return log.write.apply(log, arguments);
}

You can look at jsFiddle to see that it works. Warning: lot of alert()s on that page!


var Logger = function(msg,p){
    this.msg = typeof msg != 'undefined' ? msg : '';
    this.p = typeof p != 'undefined' ? p : '';
}
Logger.prototype = {
    write : function(msg,p){
       this.msg = typeof msg != 'undefined' ? msg : '';
       this.p = typeof p != 'undefined' ? p : '';
    },
    print : function(p){
        this.p = typeof p == 'undefined' ? this.p : p;
        if(this.p)
            alert(this.msg);
        else 
            console.log(this.msg);
        return this;
    },
    reset : function(){
        return new Logger();
    }
}

function log(msg,p){
    return new Logger(msg,p).print();
}

And then you can use :

log("alert me",true);
log("log me in console!");
log().write("a msg",false).print();
var l = log();
l.write().print().reset();


Doesn't console.log in firebug serve the purpose of logging? Though, one can write their own logger implementation. But the question is when should the logger to be used? Implementation similar like you have proposed could be useful in javascript running in server side like Rhino

But i have written some code, pls try this

<html>
<head>

<script>
  var log = function() {    

    var p_this = this;


    this.write = function(p_msg){
        p_this.msg = p_msg;
        return this.write;
    },

    this.write.print = function(){
        alert(p_this.msg);
    }


  };
 var log1 = new log();
 log1.write('test_message').print();

</script>

</head>

<body>
</body>

</html>

This may be helpful. This a conceptual code for the pattern u are looking for. You have to modify this or improve this. You may provide the logic for resetting and all.


You could try this glorious masterpiece:

var log = (function(out){
  var msgs = [];

  function log(msg){
    if (typeof msg == 'string'){
    msgs.push(msg);
    return log;}
  else{
    msgs = [];
    return log;}}

  log.write = function(msg){
    log(msg);
    return log;};

  log.print = function(){
    for(var i=0, l=msgs.length; i<l; i++){
      out(msgs[i]);}};
  return log;})(function(s){console.log(s);});

The real output function is injected at the end. You should test for console.log to exist, and use an alternative otherwise (I do not know what you would prefer).

I tried the following things:

log('First message');
log.write('Second message')('Third message').write('Fourth message');
log.write('Fifth message').print();
log.print(); // Prints all messages again.

log = new log(); // Reset.
log('Lonely!').print(); // Prints only 'Lonely!'.

Beware: log(); or log(undefined); (with undefined undefined) will reset the thing as well, while new log('Foobar'); will add the message 'Foobar'. But this was not in your test cases, so I ignored it.

This is also possible:

(new log()).write('Message');
(new log())('Message');
(new log()).print(); // Prints empty log.


Try to look at JSLog javascript logging framework:

https://github.com/dingyonglaw/JSLog

It supports all browser, and also firebug-lite;

==============
Example Usage:
==============

Logging:
--------

// Register a module logger, p is now logger for 'App.Login'
var p = JSLog.Register('App.Login');

// Log something, and it will display "[App.Login] something" in your console;
p.log('something');

// You can do something as usual:
p.warn('warning!');
p.info('info msg');


Log Level:
----------
The Logger comes with 5 level of logging access: 1-5
which coresponding to: 'error', 'warn', 'info', 'debug', 'log'

// You can set your level like this, to display only info message in console
p.SetLevel(3);

// You can get your current logging level with:
p.GetLevel();


Logging History:
----------------
The logger records your logs and you can Dump it later!

// Dump by Module Name
JSLog.Dump('App.Login');

// Dump all modules in nested view
JSLog.Dump();

// Selective Dump by filtering module name:
JSLog.SetFilter('module-name');
JSLog.Dump();  // Will exclude 'module-name' module

// Clear filter by module name:
JSLog.UnsetFilter('module-name');

// Get assigned filters
JSLog.GetFilter();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜