Skip to content

Instantly share code, notes, and snippets.

@Kobe
Created June 23, 2018 11:39
Show Gist options
  • Save Kobe/f356f005e8c705a32470c936a97d7463 to your computer and use it in GitHub Desktop.
Save Kobe/f356f005e8c705a32470c936a97d7463 to your computer and use it in GitHub Desktop.
logging via Ajax endpoint
import Location from './location.es6';
import { isJQueryAvailable } from './lib.es6';
export const LOG_LEVEL_DEBUG = 'DEBUG'; // eslint-disable-line no-unused-vars
export const LOG_LEVEL_INFO = 'INFO'; // eslint-disable-line no-unused-vars
export const LOG_LEVEL_WARN = 'WARN';
export const LOG_LEVEL_ERROR = 'ERROR'; // eslint-disable-line no-unused-vars
export const LOG_LEVEL_OFF = 'OFF'; // eslint-disable-line no-unused-vars
const INTERNAL_LOGGING_URL = '/clientLogger';
export class Logger {
/**
* @param {string} message
* @param {string} logger
* @param {string} level
* @param {string[]} history
* @return {Promise}
*/
static log(message, logger = 'ClientLogger', level = LOG_LEVEL_WARN, history = []) {
let browserHistory = history;
if (history.length === 0) {
const currentLocation = Location.get(window);
browserHistory = [currentLocation];
}
return new Promise((resolve) => {
if (isJQueryAvailable) {
$.ajax({
method: 'POST',
url: INTERNAL_LOGGING_URL,
data: JSON.stringify({
message, logger, level, browserHistory
}),
contentType: 'application/json'
})
.always(() => {
resolve();
});
} else {
fetch(INTERNAL_LOGGING_URL, {
method: 'POST',
url: INTERNAL_LOGGING_URL,
body: JSON.stringify({
message, logger, level, browserHistory
}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(() => {
resolve();
});
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment