-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
class Logger { | ||
constructor() { | ||
if (!Logger.instance) { | ||
this.logs = []; | ||
Logger.instance = this; | ||
} | ||
return Logger.instance; | ||
} | ||
|
||
getLogs() { | ||
return this.logs; | ||
} | ||
|
||
log(message, data = null, level = "LOG") { | ||
const timestamp = new Date().toISOString(); | ||
const origin = this.getCallSite(); | ||
const logMessage = `[${timestamp}] [${level}] [${origin}]: ${message}`; | ||
|
||
if (data) { | ||
this.logs.push({ message: logMessage, data }); | ||
console.log(logMessage, data); | ||
} else { | ||
this.logs.push(logMessage); | ||
console.log(logMessage); | ||
} | ||
} | ||
|
||
// Utilize log method for different levels to avoid code duplication | ||
debug(message, data = null) { | ||
this.log(message, data, "DEBUG"); | ||
} | ||
|
||
info(message, data = null) { | ||
this.log(message, data, "INFO"); | ||
} | ||
|
||
warn(message, data = null) { | ||
this.log(message, data, "WARN"); | ||
} | ||
|
||
error(message, data = null) { | ||
this.log(message, data, "ERROR"); | ||
} | ||
|
||
// Helper method to capture the call site | ||
getCallSite() { | ||
const err = new Error(); | ||
Error.captureStackTrace(err, this.getCallSite); | ||
const stack = err.stack.split("\n")[3]; // Adjust this value as needed | ||
// Extract and format call site from stack trace | ||
return stack.trim().replace(/^at\s+/g, ""); | ||
} | ||
} | ||
|
||
const instance = new Logger(); | ||
Object.freeze(instance); | ||
|
||
export default instance; |