Created
August 17, 2023 12:52
-
-
Save fredriccliver/3c0915ff8bf8b4783f7e05dfdb9429c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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