Skip to content

Instantly share code, notes, and snippets.

@jlcarvalho
Created July 28, 2015 20:07
Show Gist options
  • Save jlcarvalho/718e73b927d639928e5d to your computer and use it in GitHub Desktop.
Save jlcarvalho/718e73b927d639928e5d to your computer and use it in GitHub Desktop.
var app = angular.module('logger', ['pouchdb']);
/**
* @author: Jean Lucas de Carvalho
*
* Serviço que abstrai configurações do pouchDB e retorna uma instância
* do pouchDB
*
* TODO: permitir múltiplas instâncias do banco local e do remoto
*/
app.factory('DB', ['pouchDB', function(pouchDB){
var localDB = pouchDB('httpCache', {auto_compaction: true}),
remoteDB = pouchDB('http://localhost:5984/myremotedb');
localDB.replicate.to(remoteDB, {
live: true,
filter: function (doc) {
return doc.tipo === 'exception' || doc.tipo === 'error';
}
}).on('error', function (err) {
console.dir(err);
});
return localDB;
}]);
/**
* @author: Jean Lucas de Carvalho
*
* Container do angular para o método pintStackTrace() do stackTrace.js
*/
app.factory("traceService", function() {
return ({
print: printStackTrace
});
});
/**
* @author: Jean Lucas de Carvalho
*
* Serviço de Logging de Exceções que sobrescreve o $exceptionHandler padrão do Angular
* mantendo o comportamento padrão (imprime log no console), mas também insere os erros
* no PouchDB após gerar o stacktrace.
*/
app.factory("$exceptionHandler", ["$injector",
function($injector) {
var $log, $window, traceService, DB;
function error(exception, cause) {
$log = $log || $injector.get('$log');
$window = $window || $injector.get('$window');
traceService = traceService || $injector.get('traceService');
DB = DB || $injector.get('DB');
// preserve the default behaviour which will log the error
// to the console, and allow the application to continue running.
$log.error.apply($log, arguments);
// now try to log the error to the server side.
try{
// use our traceService to generate a stack trace
var stackTrace = traceService.print({e: exception});
// use AJAX (in this example jQuery) and NOT
// an angular service such as $http
DB.post({
url: $window.location.href,
message: exception,
tipo: "exception",
stackTrace: stackTrace,
cause: ( cause || "")
});
} catch (loggingError){
$log.warn("Error server-side logging failed");
$log.log(loggingError);
}
} return(error);
}]);
/**
* @author: Jean Lucas de Carvalho
*
* Serviço que implementa logging para o desenvolvedor acessar,
* pode ser usado no MessageService
*/
app.factory("applicationLoggingService", ["$log","$window","DB",
function($log, $window, DB){
function handle(message, tipo, args){
return DB.post({
url: $window.location.href,
message: message,
tipo: tipo
});
}
return({
error: function(message){
return handle(message, 'error', arguments);
},
debug: function(message){
return handle(message, 'error', arguments);
}
});
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment