Skip to content

Instantly share code, notes, and snippets.

@danew
Created October 24, 2019 20:36
Show Gist options
  • Save danew/e590a63797eba00fc3047e7d92e2ab8c to your computer and use it in GitHub Desktop.
Save danew/e590a63797eba00fc3047e7d92e2ab8c to your computer and use it in GitHub Desktop.
Simple logger for browser
import axios from 'axios';
let active = true;
const save = (message, level = 'info') => {
if (process.env.NODE_ENV !== 'production') {
if (active) {
axios.post('http://localhost:9999/log', { level, message }).catch(() => {
active = false;
});
} else {
console.info(message);
}
}
};
export const log = (...args) => {
const date = new Date();
const pad = (num, amt = 2) => (num + '').padStart(amt, '0');
const time = `${pad(date.getHours())}:${pad(date.getMinutes())}.${pad(date.getSeconds())}.${pad(
date.getMilliseconds(),
3
)}`;
const data = args.map(d => (typeof args !== 'string' ? JSON.stringify(d) : d));
const message = `${time} @ ${data.join(' | ')}`;
save(message);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment