Skip to content

Commit

Permalink
feat: add try-catch block to custom logger for js files (#267)
Browse files Browse the repository at this point in the history
* feat: add try-catch block to custom logger for js files

JavaScript files will not throw any error when the wrong argument signature is passed into logger invocations. Add try catch block as a defensive measure at least until the application is 100% typescript, to prevent possible errors from being thrown due to the wrong type

* fix(logger): add stricter shape checks

* fix: use correct parameters in info logging

Co-authored-by: Antariksh Mahajan <[email protected]>

Co-authored-by: Antariksh Mahajan <[email protected]>
  • Loading branch information
karrui and mantariksh authored Sep 3, 2020
1 parent 246daa8 commit d19a105
Showing 1 changed file with 40 additions and 10 deletions.
50 changes: 40 additions & 10 deletions src/config/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import hasAnsi from 'has-ansi'
import { isEmpty } from 'lodash'
import omit from 'lodash/omit'
import logform from 'logform'
import path from 'path'
Expand Down Expand Up @@ -185,23 +186,52 @@ const getModuleLabel = (callingModule: NodeModule) => {
/**
* Overrides the given winston logger with a new signature, so as to enforce a
* log format.
* TODO(#42): Remove try catch blocks when application is 100% TypeScript.
* @param logger the logger to override
*/
const createCustomLogger = (logger: Logger) => {
return {
info: ({ message, meta }: Omit<CustomLoggerParams, 'error'>) =>
logger.info(message, { meta }),
warn: ({ message, meta, error }: CustomLoggerParams) => {
if (error) {
return logger.warn(message, { meta }, error)
info: (params: Omit<CustomLoggerParams, 'error'>) => {
try {
const { message, meta } = params
// Not the expected shape, throw to catch block.
if (!message || isEmpty(meta)) {
throw new Error('Wrong shape')
}
return logger.info(message, { meta })
} catch {
return logger.info(params)
}
return logger.warn(message, { meta })
},
error: ({ message, meta, error }: CustomLoggerParams) => {
if (error) {
return logger.error(message, { meta }, error)
warn: (params: CustomLoggerParams) => {
try {
const { message, meta, error } = params
// Not the expected shape, throw to catch block.
if (!message || isEmpty(meta)) {
throw new Error('Wrong shape')
}
if (error) {
return logger.warn(message, { meta }, error)
}
return logger.warn(message, { meta })
} catch {
return logger.warn(params)
}
},
error: (params: CustomLoggerParams) => {
try {
const { message, meta, error } = params
// Not the expected shape, throw to catch block.
if (!message || isEmpty(meta)) {
throw new Error('Wrong shape')
}
if (error) {
return logger.error(message, { meta }, error)
}
return logger.error(message, { meta })
} catch {
return logger.error(params)
}
return logger.error(message, { meta })
},
}
}
Expand Down

0 comments on commit d19a105

Please sign in to comment.