jquery - Saving JavaScript `console.log` to global variable or file - Stack Overflow

I want to access console.log data programmatically and so I need to implement a console.log which store

I want to access console.log data programmatically and so I need to implement a console.log which stores its data in a global variable or file.

Can anyone tell me how to do this?

I want to access console.log data programmatically and so I need to implement a console.log which stores its data in a global variable or file.

Can anyone tell me how to do this?

Share Improve this question edited May 29, 2017 at 20:12 Badacadabra 8,5357 gold badges31 silver badges54 bronze badges asked Feb 3, 2015 at 6:01 Query21Query21 2002 silver badges10 bronze badges 1
  • You want a logger kind of stuff? Also have a look @ Log Level - Minimal lightweight simple logging for JavaScript. loglevel replaces console.log() and friends with level-based logging and filtering, with none of console's downsides. – Shubh Commented Feb 3, 2015 at 6:07
Add a ment  | 

1 Answer 1

Reset to default 5

EDIT 2

Do use a library like loglevel

See the answers below to understand how you can implement something like this by yourself.

original answer:

Do something like:

var myLogs = [];
(function () {
  var log = console.log;
  console.log = function () {
    var args = Array.prototype.slice.call(arguments)
    log.apply(this, args );
    myLogs.push(args);
  };
}());

The gloabl variable myLogs will contain your log data.

You may want to adopt the code to your needs. Maybe you want to make one string out of the args array.

EDIT

If you want to have console.log, console.error, console.warn, console.info and store the log level:

var logData = [];
(function () {
    var log = console.log,
        error = console.error,
        warn = console.warn,
        info = console.info;

    console.log = function () {
        var args = Array.prototype.slice.call(arguments)
        log.apply(this, args );
        logData.push({level: "log", arguments: args});
    };
    console.error = function () {
        var args = Array.prototype.slice.call(arguments)
        error.apply(this, args );
        logData.push({level: "error", arguments: args});
    };
    console.warn = function () {
        var args = Array.prototype.slice.call(arguments)
        warn.apply(this, args );
        logData.push({level: "warn", arguments: args});
    };
    console.info = function () {
        var args = Array.prototype.slice.call(arguments)
        info.apply(this, args );
        logData.push({level: "info", arguments: args});
    };
}());

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745459690a4628648.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信