настроить prerender.io для вывода только сообщений об ошибках из PhantomJS

Мне удалось включить ведение журнала для prerender.io для браузера PhantomJS с помощью плагина logger. Однако я хотел бы, чтобы регистрировались только сообщения об ошибках. Плагин logger регистрирует только все. На основе следующих страниц:

http://phantomjs.org/api/webpage/handler/on-error.html http://phantomjs.org/api/phantom/handler/on-error.html

PhantomJS должен иметь событие onError, которое запускается при возникновении ошибки. Прежде чем пытаться создать плагин, я попытался временно обновить server.js prerender.io, чтобы привязать его к событию onError. Я обновил обе функции server.createPage, как показано ниже, для присоединения к page.onError и даже попробовал page.set('onError'), аналогично коду, найденному в logger.js.

server.createPage = function(req, res) {
    var _this = this;

    if(!this.phantom) {
        setTimeout(function(){
            _this.createPage(req, res);
        }, 50);
    } else {
        req.prerender.phantomId = this.phantom.id;
        this.phantom.createPage(function(page){
            req.prerender.page = page;
            console.log("registering onError for page");
            page.onError = function(msg, trace) {
                                                              var msgStack = ['PAGE PHANTOM ERROR OCCURRED: ' + msg];
                                                              msgStack.push('----------------------------------');
                                                              if (trace && trace.length) {
                                                                msgStack.push('TRACE:');
                                                                trace.forEach(function(t) {
                                                                  msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
                                                                });
                                                              }
                                                              msgStack.push('==================================');
                                                              console.log(msgStack.join('\n'));
                                                            };

            page.set('onError', function(msg, trace) {
                                                              var msgStack = ['PAGE2 PHANTOM ERROR OCCURRED: ' + msg];
                                                              msgStack.push('----------------------------------');
                                                              if (trace && trace.length) {
                                                                msgStack.push('TRACE:');
                                                                trace.forEach(function(t) {
                                                                  msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
                                                                });
                                                              }
                                                              msgStack.push('==================================');
                                                              console.log(msgStack.join('\n'));
                                                            });                                                         



            _this.onPhantomPageCreate(req, res);
        });
    }
};

Я также обновил метод server.onPhantomCreate(), чтобы присоединить его к общему phantom.onError, как показано ниже:

server.onPhantomCreate = function(phantom) {
    util.log('started phantom');
    this.phantom = phantom;
    this.phantom.id = Math.random().toString(36);
    console.log("Registering phantom.onError");
    phantom.onError = function(msg, trace) {
                                                              var msgStack = ['PHANTOM ERROR OCCURRED: ' + msg];
                                                              msgStack.push('----------------------------------');
                                                              if (trace && trace.length) {
                                                                msgStack.push('TRACE:');
                                                                trace.forEach(function(t) {
                                                                  msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
                                                                });
                                                              }
                                                              msgStack.push('==================================');
                                                              console.log(msgStack.join('\n'));
                                                            };
    phantom.set('onError', function(msg, trace) {
                                                              var msgStack = ['PHANTOM ERROR OCCURRED: ' + msg];
                                                              msgStack.push('----------------------------------');
                                                              if (trace && trace.length) {
                                                                msgStack.push('TRACE:');
                                                                trace.forEach(function(t) {
                                                                  msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
                                                                });
                                                              }
                                                              msgStack.push('==================================');
                                                              console.log(msgStack.join('\n'));
                                                            });


};

Однако ничего не регистрируется. Любые идеи, почему это?


person Karl Cassar    schedule 04.02.2016    source источник


Ответы (1)


Вы можете передать функции onStdout и onStderr с помощью объекта параметров пререндеринга:

var server = prerender({
    workers: 1,
    iterations: 50,
    onStdout: function(data) {
        console.log(data);
    },
    onStderr: function(data) {
        console.log(data);
    }
});

Вы не можете поместить onError в фантом напрямую, потому что это не настоящий экземпляр фантома, это конвейер узла к реальному экземпляру фантома.

person Prerender.io    schedule 05.02.2016
comment
Это выдает ошибку dest.on is not a function от phridge. - person Vitalii Zurian; 07.02.2018
comment
Извините, это, вероятно, работало только на старой версии нашего кода. Попробуйте использовать наш новый рендеринг Chrome на нашем последнем сервере Prerender! - person Prerender.io; 08.02.2018
comment
Я размещаю Prerender на экземпляре AWS EC. В любом случае спасибо за отличный продукт! :) - person Vitalii Zurian; 09.02.2018