Skip to content

Commit

Permalink
enable ability to debug
Browse files Browse the repository at this point in the history
  • Loading branch information
hiro5id committed Dec 10, 2019
1 parent e78a7f8 commit b2dcbee
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 7 deletions.
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@
"dependencies": {
"app-root-path": "^3.0.0",
"callsites": "^3.1.0",
"json-stringify-safe": "^5.0.1",
"winston": "^3.2.1"
},
"devDependencies": {
"@types/app-root-path": "^1.2.4",
"@types/chai": "^4.2.3",
"@types/json-stringify-safe": "^5.0.0",
"@types/mocha": "^5.2.7",
"@types/node": "^12.7.7",
"@types/rimraf": "^2.0.2",
Expand Down
30 changes: 27 additions & 3 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* tslint:disable:object-literal-sort-keys */
import appRootPath from 'app-root-path';
import callsites from 'callsites';
import stringify from 'json-stringify-safe';
import * as w from 'winston';
import { ErrorWithContext } from './error-with-context';
import { formatStackTrace } from './format-stack-trace';
import { ToOneLine } from './to-one-line';

// tslint:disable-next-line:no-var-requires
/* tslint:disable:no-conditional-assignment */

Expand Down Expand Up @@ -153,7 +155,7 @@ export function FormatErrorObject(object: any) {
returnData.message = '<no-error-message-was-passed-to-console-log>';
}

const jsonString = JSON.stringify(returnData);
const jsonString = stringify(returnData);

// strip ansi colors
return jsonString.replace(/\\u001B\[\d*m/gim, '');
Expand Down Expand Up @@ -210,7 +212,15 @@ function ifEverythingFailsLogger(functionName: string, err: Error) {
}
}

export function LoggerAdaptToConsole(logLevel: LOG_LEVEL = LOG_LEVEL.info) {
let logParams!: { logLevel: LOG_LEVEL; debugString: boolean };

export function LoggerAdaptToConsole(options?: { logLevel?: LOG_LEVEL; debugString?: boolean }) {
const defaultOptions = {
logLevel: LOG_LEVEL.info,
debugString: false,
};

logParams = { ...defaultOptions, ...options };
if (consoleErrorBackup == null) {
consoleErrorBackup = console.error;
}
Expand Down Expand Up @@ -273,7 +283,7 @@ export function LoggerAdaptToConsole(logLevel: LOG_LEVEL = LOG_LEVEL.info) {
void logUsingWinston(args, LOG_LEVEL.info);
};

Logger.level = logLevel;
Logger.level = logParams.logLevel;
}

function filterNullOrUndefinedParameters(args: any): number {
Expand Down Expand Up @@ -339,6 +349,20 @@ function getCallingFilename(): string | null {
}

export async function logUsingWinston(args: any[], level: LOG_LEVEL) {
// log debug logging if needed
try {
if (logParams.debugString) {
const argsStringArray = args.map(m => JSON.stringify(m, Object.getOwnPropertyNames(m)));
let argsString = `[${argsStringArray.join(',')}]`;
if (!argsString) {
argsString = '';
}
args.push({ _loggerDebug: argsString });
}
} catch (err) {
args.push({ _loggerDebug: `err ${err.message}` });
}

// Discover calling filename
try {
const name = getCallingFilename();
Expand Down
25 changes: 21 additions & 4 deletions test/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ describe('logger', () => {
it('console.debug works', () => {
const backupLevel = GetLogLevel();
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole(LOG_LEVEL.debug);
LoggerAdaptToConsole({logLevel:LOG_LEVEL.debug});

try {
console.debug('this is a message', {'extra-context': 'hello'});
Expand All @@ -158,7 +158,7 @@ describe('logger', () => {
it('console.silly works', () => {
const backupLevel = GetLogLevel();
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole(LOG_LEVEL.silly);
LoggerAdaptToConsole({logLevel:LOG_LEVEL.silly});

try {
console.silly('this is a message', {'extra-context': 'hello'});
Expand All @@ -176,7 +176,7 @@ describe('logger', () => {
it('console.warn works with log level info', () => {
const backupLevel = GetLogLevel();
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole(LOG_LEVEL.info);
LoggerAdaptToConsole({logLevel:LOG_LEVEL.info});

try {
console.warn('this is a message', {'extra-context': 'hello'});
Expand All @@ -194,7 +194,7 @@ describe('logger', () => {
it('console.warn is not shown with log level error', () => {
const backupLevel = GetLogLevel();
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole(LOG_LEVEL.error);
LoggerAdaptToConsole({logLevel:LOG_LEVEL.error});

try {
console.warn('this is a message', {'extra-context': 'hello'});
Expand Down Expand Up @@ -427,6 +427,23 @@ describe('logger', () => {
expect(testObj.message).eql("error-message");
});

it('log with debug shows debug line', async () => {
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole({debugString:true});

console.log(new Error('error-message'), 'test string');

restoreStdOut(originalWrite);
LoggerRestoreConsole();

console.log(outputText[0]);
const testObj = JSON.parse(outputText[0]);
expect(testObj.level).eql("error");
expect(testObj.filename).include("/test/logger.test");
expect(testObj.message).eql("test string - error-message");
expect(testObj._loggerDebug).contains("\"test string\"");
expect(testObj._loggerDebug).contains("\"stack\":\"Error: error-message");
});

it('console.log logs as info when explicitly provided with level parameter that is not recognized', async () => {
const {originalWrite, outputText} = overrideStdOut();
Expand Down

0 comments on commit b2dcbee

Please sign in to comment.