86 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-12-14 00:59:12 +01:00
'use strict';
const Sentry = require('@sentry/node');
const defaultSettings = require('../config/settings.json');
2020-12-14 17:50:19 +01:00
const createSentryService = () => {
let isReady = false;
let instance = null;
let settings = {};
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
return {
/**
* Initialize Sentry service
*/
init() {
// Make sure there isn't a Sentry instance already running
if (instance != null) {
strapi.log.warn('Sentry has already been initialized');
return;
}
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
// Retrieve user settings and merge them with the default ones
settings = {
...defaultSettings,
...strapi.plugins.sentry.config,
};
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
try {
// Don't init Sentry if no DSN was provided
if (settings.dsn) {
Sentry.init({
dsn: settings.dsn,
environment: strapi.config.environment,
});
// Store the successfully initialized Sentry instance
instance = Sentry;
isReady = true;
} else {
strapi.log.info('strapi-plugin-sentry is disabled because no Sentry DSN was provided');
}
} catch (error) {
strapi.log.warn('Could not set up Sentry, make sure you entered a valid DSN');
2020-12-14 00:59:12 +01:00
}
2020-12-14 17:50:19 +01:00
},
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
/**
* Expose Sentry instance through a getter
* @returns {Sentry}
*/
getInstance() {
return instance;
},
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
/**
* Callback to [configure an instance of Sentry's scope]{@link https://docs.sentry.io/platforms/node/enriching-events/scopes/#configuring-the-scope}
* @callback configureScope
* @param {Sentry.scope} scope
* @param {Sentry=} instance An initialized Sentry instance
*/
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
/**
* Higher level method to send exception events to Sentry
* @param {Error} error An error object
* @param {configureScope=} configureScope
*/
sendError(error, configureScope) {
// Make sure Sentry is ready
if (!isReady) {
strapi.log.warn("Sentry wasn't properly initialized, cannot send event");
return;
}
2020-12-14 00:59:12 +01:00
2020-12-14 17:50:19 +01:00
instance.withScope(scope => {
// Configure the Sentry scope using the provided callback
if (configureScope && settings.sendMetadata) {
2020-12-14 17:50:19 +01:00
configureScope(scope, instance);
}
// Actually send the Error to Sentry
instance.captureException(error);
});
},
};
2020-12-14 00:59:12 +01:00
};
2020-12-14 17:50:19 +01:00
module.exports = createSentryService();