/how-to-log-the-global-console/cover.jpg

How to log the global console

Motivation

Sometimes we need to use whatever is getting logged in our console within our frontend or we might even need to send this log message to a server. Currently we donโ€™t have an event like window.onLog which enables us to get whatever is being logged on our console. We can only โ€œseeโ€ whatever we log ourselves.

Implementation

To use this we need something that logs first. This can be anything. We will use a simple fetch:

js
try {
const response = await fetch('https://not-working-api.example.com')
} catch (error) {
console.error(error)
}

This not working API will fail without a doubt. So we catch the error and log it ourselves. To utilize the stuff we just logged we will overwrite the browsers default behavior:

js
// all of this code should be called once only.
// whatever is being triggered should not trigger another console method, to avoid recursive calling
const oldwarn = console.warn;
console.warn = function() {
oldwarn(...arguments);
dispatchLoggingEvent(Array.from(arguments).join(''));
}
const olderror = console.error;
console.error = function() {
olderror(...arguments);
dispatchLoggingEvent(Array.from(arguments).join(''));
}

Here we have overwritten it for console.error and console.warn. Inside these functions we can do whatever we want. We should return the corresponding old function though, to keep the default behavior working. We can create a custom event to more easily use our logged data in other parts of our application.

js
/**
* @function dispatchLoggingEvent
* @description Event which can be called to react to logging.
* @param content
*/
export const dispatchLoggingEvent = (
content: string,
): void => {
const event = new CustomEvent('logging', {
detail: {
content,
},
});
window.dispatchEvent(event);
// do some other logic
};

Wrapping Up

Thatโ€™s all there is to it. Itโ€™s the best we might be able to do currently, because we donโ€™t have a way to โ€œhookโ€ into the browsers own console logging directly. This helps a lot for debugging on mobile devices, because you can simply add whatever you log to your templates and you donโ€™t need to have any special hardware for this.