Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions api-extractor/js-utils.api.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,30 @@
"name": "",
"preserveMemberOrder": false,
"members": [
{
"kind": "Function",
"canonicalReference": "@asl-19/js-utils!addTimestampsToConsoleMethods:function(1)",
"docComment": "/**\n * Add timestamps to console.log, console.info, console.warn, and console.error messages.\n *\n * If a message already starts with a timestamp (in the format added by this function), another timestamp will not be added.\n *\n * @public\n */\n",
"excerptTokens": [
{
"kind": "Content",
"text": "addTimestampsToConsoleMethods: () => "
},
{
"kind": "Content",
"text": "void"
}
],
"fileUrlPath": "dist/addTimestampsToConsoleMethods.d.ts",
"returnTypeTokenRange": {
"startIndex": 1,
"endIndex": 2
},
"releaseTag": "Public",
"overloadIndex": 1,
"parameters": [],
"name": "addTimestampsToConsoleMethods"
},
{
"kind": "Function",
"canonicalReference": "@asl-19/js-utils!asType:function(1)",
Expand Down
3 changes: 3 additions & 0 deletions api-extractor/js-utils.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

import { ParsedUrlQuery } from 'querystring';

// @public
export const addTimestampsToConsoleMethods: () => void;

// @public
export const asType: <T>(value: T) => T;

Expand Down
19 changes: 19 additions & 0 deletions docs/js-utils.addtimestampstoconsolemethods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [@asl-19/js-utils](./js-utils.md) &gt; [addTimestampsToConsoleMethods](./js-utils.addtimestampstoconsolemethods.md)

## addTimestampsToConsoleMethods() function

Add timestamps to console.log, console.info, console.warn, and console.error messages.

If a message already starts with a timestamp (in the format added by this function), another timestamp will not be added.

**Signature:**

```typescript
addTimestampsToConsoleMethods: () => void
```
**Returns:**

void

13 changes: 13 additions & 0 deletions docs/js-utils.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ Description
</th></tr></thead>
<tbody><tr><td>

[addTimestampsToConsoleMethods()](./js-utils.addtimestampstoconsolemethods.md)


</td><td>

Add timestamps to console.log, console.info, console.warn, and console.error messages.

If a message already starts with a timestamp (in the format added by this function), another timestamp will not be added.


</td></tr>
<tr><td>

[asType(value)](./js-utils.astype.md)


Expand Down
102 changes: 102 additions & 0 deletions src/addTimestampsToConsoleMethods.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// eslint-disable-next-line no-console
const originalConsoleLog = console.log;
const originalConsoleInfo = console.info;
const originalConsoleWarn = console.warn;
const originalConsoleError = console.error;

const datePartsRegExp =
/(?<date>\d\d\d\d-\d\d-\d\d)T(?<hoursMinutesSeconds>\d\d:\d\d:\d\d)/;

/**
* Matches strings that start with a date stamp like "[2025-01-01 01:23:45"
*
* (Note the lack of trailing square bracket since serverLog can include URL
* path after the timestamp but before the closing square bracket).
*/
const startsWithDateStampRegExp = /^\[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/;

const getFormattedCurrentDateTimePrefix = () => {
const date = new Date();

const datePartsMatch = datePartsRegExp.exec(date.toISOString());

return datePartsMatch &&
typeof datePartsMatch.groups === "object" &&
typeof datePartsMatch.groups.date === "string" &&
typeof datePartsMatch.groups.hoursMinutesSeconds === "string"
? `[${datePartsMatch.groups.date} ${datePartsMatch.groups.hoursMinutesSeconds}]`
: "[????-??-?? ??:??:??]"; // This shouldn't ever happen!
};

/**
* TypeScript verification that the regex pattern matches the timestamp format.
* This ensures that startsWithDateStampRegExp will correctly identify timestamps
* generated by both addTimestampsToConsoleMethods and serverLog.
*/

// Runtime verification that the regex matches the actual format
const _testTimestampFormat = getFormattedCurrentDateTimePrefix();
if (!startsWithDateStampRegExp.test(_testTimestampFormat)) {
throw new Error(
"startsWithDateStampRegExp does not match the date format produced by getFormattedCurrentDateTimePrefix/serverLog",
);
}

/**
* @param {{
* args: Array<any>;
* consoleMethod: typeof console.log }
* } params}
* @returns void
*/
const callConsoleMethodWithTimestampPrefixIfNotAlreadyTimestamped = ({
args,
consoleMethod,
}: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: Array<any>;
consoleMethod: typeof console.log;
}) => {
if (typeof args[0] === "string" && startsWithDateStampRegExp.test(args[0])) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
consoleMethod(...args);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
consoleMethod(getFormattedCurrentDateTimePrefix(), ...args);
}
};

/**
*
* Add timestamps to console.log, console.info, console.warn, and console.error
* messages.
*
* If a message already starts with a timestamp (in the format added by this
* function), another timestamp will not be added.
* @public
*/
const addTimestampsToConsoleMethods = () => {
// eslint-disable-next-line no-console
console.log = (...args) =>
callConsoleMethodWithTimestampPrefixIfNotAlreadyTimestamped({
args,
consoleMethod: originalConsoleLog,
});
console.info = (...args) =>
callConsoleMethodWithTimestampPrefixIfNotAlreadyTimestamped({
args,
consoleMethod: originalConsoleInfo,
});
console.warn = (...args) =>
callConsoleMethodWithTimestampPrefixIfNotAlreadyTimestamped({
args,
consoleMethod: originalConsoleWarn,
});
console.error = (...args) =>
callConsoleMethodWithTimestampPrefixIfNotAlreadyTimestamped({
args,
consoleMethod: originalConsoleError,
});
};

export default addTimestampsToConsoleMethods;
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* @packageDocumentation
*/

export { default as addTimestampsToConsoleMethods } from "./addTimestampsToConsoleMethods.js";
export { default as asType } from "./asType.js";
export { default as cleanUrlQueryString } from "./cleanUrlQueryString.js";
export { default as constructUrl } from "./constructUrl.js";
Expand Down