Skip to content

Instantly share code, notes, and snippets.

@fredriccliver
Created August 17, 2023 12:52
Show Gist options
  • Save fredriccliver/3c0915ff8bf8b4783f7e05dfdb9429c1 to your computer and use it in GitHub Desktop.
Save fredriccliver/3c0915ff8bf8b4783f7e05dfdb9429c1 to your computer and use it in GitHub Desktop.
// logger.ts
export function logError(message: string, ...optionalParams: any[]): void {
try {
// Get the caller function
const caller = logError.caller?.name || 'anonymous';
// Extract filename from the stack trace
const stack = new Error().stack || '';
const fileMatch = stack.split('\n')[2]?.match(/(?:http:\/\/|https:\/\/|file:\/\/\/).*?\/(.*?)(?:\?|:)/) || [];
const file = fileMatch[1] || 'unknown-file';
// Prepend the file and method name to the message
console.error(`[${file} -> ${caller}] ${message}`, ...optionalParams);
} catch (err) {
console.error(message, ...optionalParams);
}
}
// ExampleComponent.tsx
import React from 'react';
import { logError } from './logger';
class ExampleComponent extends React.Component {
someMethod() {
// some logic here...
logError('This is a critical issue!');
}
render() {
return <div onClick={this.someMethod}>Click Me!</div>;
}
}
export default ExampleComponent;
// webpack.config.js
module.exports = {
// ...
devtool: 'source-map',
// ...
};
// This is a custom error log example
[ExampleComponent.tsx -> someMethod] This is a critical issue!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment