Skip to content

Commit

Permalink
update createLogger api
Browse files Browse the repository at this point in the history
  • Loading branch information
Cap32 committed Jul 31, 2017
1 parent 794820b commit 3ef0c69
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 51 deletions.
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,35 @@ var logger = require('pot-logger').default; /* or */

---

#### createLogger(category[, color, appender])
#### createLogger(category[, appenderDescription])

Create a custom logger.

###### Arguments

1. `category` (String): Logger category.
2. `color` (String): Category text color. Support all [chalk.js](https://github.com/chalk/chalk) colors. Defaults to `gray`.
3. `appender` (Object): [log4js](https://nomiddlename.github.io/log4js-node/appenders.html) appender.
2. `appenderDescription` (String|Object|Function):
- (String): Category text color. Support all [chalk.js](https://github.com/chalk/chalk) colors. Supports dot notation (i.e. `red.bold`).
- (Object): [log4js](https://nomiddlename.github.io/log4js-node/appenders.html) appender.
- (Function): A function that should return an [log4js](https://nomiddlename.github.io/log4js-node/appenders.html) appender. The only argument of this function is a `ref` object
+ `category` (String)
+ `daemon` (Boolean)
+ `defaultDaemonAppender` (Object)
+ `defaultConsoleAppender` (Object)

###### Returns

Returns a new `logger`.

###### Example

```js
import { createLogger } from 'pot-logger';
const logger = createLogger('test', (ref) => {
return ref.daemon ? ref.defaultDaemonAppender : ref.defaultConsoleAppender;
});
```

---

#### getLogger(category)
Expand Down
89 changes: 45 additions & 44 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import chalk from 'chalk';

const isFunction = (src) => typeof src === 'function';
const isObject = (src) => typeof src === 'object';
const isString = (src) => typeof src === 'string';

const defaultCategory = 'out';
const defaultLogLevel = 'INFO';
Expand Down Expand Up @@ -311,66 +312,66 @@ export function getLogger(category) {
return logSystem.getLogger(category);
}

export function createLogger(category, style, getAppender) {
if (!style) { style = 'dim'; }

export function createLogger(category, description) {
if (logSystem.hasLogger(category)) {
throw new Error(
`Failed to create logger: "${category}" has already exists.`
);
}

const getStyledCategoryStr = () => {
const pattern = '[%c]';
const validatColor = (style) => {
if (!isFunction(chalk[style])) {
throw new Error(`Category with style "${style}" is NOT support.`);
}
};
if (isObject(description)) {
logSystem.appenders[category] = description;
}
else {
let style = 'dim';

if (isString(description)) { style = description; }

const getStyledCategoryStr = () => {
const pattern = '[%c]';
const validatColor = (style) => {
if (!isFunction(chalk[style])) {
throw new Error(`Category with style "${style}" is NOT support.`);
}
};

if (Array.isArray(style)) {
const getStyle = style.reduce((chalkChaining, color) => {
const getStyle = style.split('.').reduce((chalkChaining, color) => {
validatColor(color);
return chalkChaining[color].bind(chalkChaining);
return chalkChaining[color];
}, chalk);
return getStyle(pattern);
}
else {
validatColor(style);
return chalk[style](pattern);
}
};
};

const ref = {
category,
get daemon() {
return config.daemon;
},
get defaultDaemonAppender() {
return { ...defaultFileAppender };
},
get defaultConsoleAppender() {
return {
type: 'console',
layout: {
type: 'pattern',
pattern: `%[%p%] ${getStyledCategoryStr()} %m`,
},
};
},
};
const ref = {
category,
get daemon() {
return config.daemon;
},
get defaultDaemonAppender() {
return { ...defaultFileAppender };
},
get defaultConsoleAppender() {
return {
type: 'console',
layout: {
type: 'pattern',
pattern: `%[%p%] ${getStyledCategoryStr()} %m`,
},
};
},
};

logSystem.appenders[category] = () => {
if (isFunction(getAppender)) { return getAppender(ref); }
const { daemon } = config;
return ref[daemon ? 'defaultDaemonAppender' : 'defaultConsoleAppender'];
};
logSystem.appenders[category] = () => {
if (isFunction(description)) { return description(ref); }
const { daemon } = config;
return ref[daemon ? 'defaultDaemonAppender' : 'defaultConsoleAppender'];
};
}

logSystem.requestUpdateAppenders();
logSystem.requestUpdateCategories();

return logSystem.getLogger(category);
}

export const logger = createLogger(defaultCategory, 0, () => defaultAppenders.con);
export const logger = createLogger(defaultCategory, defaultAppenders.con);
export default logger;
59 changes: 55 additions & 4 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { join } from 'path';
import { pathExists, remove, readFile } from 'fs-extra';
import { build, requireSandbox } from './utils';
import stripAnsi from 'strip-ansi';
import chalk from 'chalk';
import delay from 'delay';

beforeAll(build);
Expand Down Expand Up @@ -66,7 +67,7 @@ describe('logger', () => {
});

describe('createLogger', () => {
test('should `createLogger()` work with default appender', () => {
test('default appender', () => {
const category = 'hello';
const message = 'world';
const log = jest.fn();
Expand All @@ -77,23 +78,73 @@ describe('createLogger', () => {
expect(stripAnsi(arg)).toBe(`INFO [${category}] ${message}`);
});

test('should `createLogger()` work with custom appender', () => {
test('custom appender object', () => {
const category = 'hello';
const message = 'world';
const prefix = 'My custom logger -';
const log = jest.fn();
const { createLogger } = requireSandbox({ console: { log } });
const logger = createLogger(category, 0, () => ({
const logger = createLogger(category, {
type: 'console',
layout: {
type: 'pattern',
pattern: `${prefix} %m`,
},
}));
});
logger.info(message);
const arg = log.mock.calls[0][0];
expect(stripAnsi(arg)).toBe(`${prefix} ${message}`);
});

test('custom appender function', () => {
const category = 'hello';
const message = 'world';
const prefix = 'My custom logger -';
const log = jest.fn();
const { createLogger } = requireSandbox({ console: { log } });
const logger = createLogger(category, (ref) => {
expect(ref.category).toBe(category);
expect(ref.daemon).toBe(false);
expect(typeof ref.defaultDaemonAppender).toBe('object');
expect(typeof ref.defaultConsoleAppender).toBe('object');
return {
type: 'console',
layout: {
type: 'pattern',
pattern: `${prefix} %m`,
},
};
});
logger.info(message);
const arg = log.mock.calls[0][0];
expect(stripAnsi(arg)).toBe(`${prefix} ${message}`);
});

test('colored appender', () => {
const category = 'hello';
const message = 'world';
const log = jest.fn();
const { createLogger } = requireSandbox({ console: { log } });
const logger = createLogger(category, 'red');
logger.info(message);
const arg = log.mock.calls[0][0];
expect(arg).toBe(
`${chalk.green('INFO')} ${chalk.red(`[${category}]`)} ${message}`
);
});

test('dot notation colored appender', () => {
const category = 'hello';
const message = 'world';
const log = jest.fn();
const { createLogger } = requireSandbox({ console: { log } });
const logger = createLogger(category, 'red.bold');
logger.info(message);
const arg = log.mock.calls[0][0];
expect(arg).toBe(
`${chalk.green('INFO')} ${chalk.red.bold(`[${category}]`)} ${message}`
);
});
});

describe('getLogger', () => {
Expand Down

0 comments on commit 3ef0c69

Please sign in to comment.