diff --git a/lib/log.js b/lib/log.js index a6ae987a..cb379c57 100644 --- a/lib/log.js +++ b/lib/log.js @@ -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)) + } + } + + return obj } \ No newline at end of file diff --git a/lib/log.test.js b/lib/log.test.js index a159152d..b40c9d3c 100644 --- a/lib/log.test.js +++ b/lib/log.test.js @@ -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") + }) }) \ No newline at end of file