Skip to content
32 changes: 27 additions & 5 deletions lib/log.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,42 @@
const {createLogger, format, transports} = require('winston')
const util = require('util')

module.exports = (file) => {
const logger = createLogger({
format: format.combine(
format.timestamp({format:'YYYY-MM-DD HH:mm:ss'}),
format.label({
label: file
label: file.split(/(\\|\/)/g).pop()
}),
format.colorize(),
format.printf(
info => `${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
)
format.printf((info) => {
return `${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
})
),
transports : [
new transports.Console()
]
})
return logger

const processArgs = (args) => {
const mappedArgs = args.map((e) => {
if (e instanceof Error) return e.toString()
return e
})
return util.format('%j', mappedArgs)
}

const obj = {
info: (...args) => {
logger.info(processArgs(args))
},
warn: (...args) => {
logger.warn(processArgs(args))
},
error: (...args) => {
logger.error(processArgs(args))
}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should add some test to your logger.

return obj
}
37 changes: 36 additions & 1 deletion lib/log.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
const winston = require('winston')
winston.createLogger = jest.fn()
const util = require('util')

winston.createLogger = jest.fn().mockReturnValue({
info: () => {},
warn: () => {},
error: () => {}
})

winston.format = {
combine: () => {},
timestamp: () => {},
label: () => {},
colorize: () => {},
printf: jest.fn()
}

util.format = jest.fn()

describe('Testing log.js', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('should call util.format everytime when log.xxx is called', () => {
const logger = require('./log')(__filename)
logger.info('message', [0,1,2])
logger.warn('message', {obj: () => {}})
logger.error('message', new Error('error message'))
expect(util.format).toHaveBeenCalled()
})
it('should call winston.createLogger when log is required', () => {
const logger = require('./log')(__filename)
expect(winston.createLogger).toHaveBeenCalled()
})
it('should return log string correctly', () => {
const logger = require('./log')(__filename)
const argInPrintf = winston.format.printf.mock.calls[0][0]
const testData = {
timestamp: "2020-04-30 22:43:00",
level: "info",
label: "log.test.js",
message: "message"
}
expect(argInPrintf(testData)).toBe("2020-04-30 22:43:00 info [log.test.js]: message")
})
})