Skip to content

Commit

Permalink
Merge pull request #9 from quintoandar/updateLoggingFormat
Browse files Browse the repository at this point in the history
Update logging format
  • Loading branch information
github-felipe-caputo authored Dec 19, 2018
2 parents 5c6a127 + 5e943b5 commit 901ec42
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 9 deletions.
38 changes: 36 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,53 @@ Winston logger with sentry configuration included. Also show the file from which
| CONSOLE_LOG_LEVEL | The level of the logs displayed on the console (optional, defaults to info) |
| CAPTURE_UNHANDLED_REJECTIONS | A value (true or false) saying if you want these exceptions to be logged in you app |

## Usage
## Setting up

```sh
npm install --save git+https://github.com/quintoandar/node-logger.git#<latest-release-version>
```

Or add it on your `package.json` file like:

```sh
"dependencies": {
"quintoandar-logger": "git+https://github.com/quintoandar/node-logger.git#<latest-release-version>",
},
```

[See releases](https://github.com/quintoandar/node-logger/releases)

## Usage

### Info

When logging info you are able to send the string (the info message) plus any other metadata you want as the second parameter.

```js
const logger = require('quintoandar-logger').getLogger(module);

logger.info("Some info");
const object = { id: 11, someInfo: 'someInfo' }
logger.info(`Some info about processing cool object with id ${object.id}`, { data: object });
```

It will be logged as a json:
```sh
{"level":"info","message":"Some info about processing cool object with id 10","extra_data":{"data":{"id":"11","someInfo":"someInfo"}},"logger_name":"path/to/my/file.js","timestamp":"2018-12-19T18:15:57.078Z"}
```

### Warning and Error

With warning and error messages the behaviour is similar, with one differece: both level of logging are submitted to Sentry, so if you want to submit metadata you need to include it on a specific key named `extra`.

```js
const logger = require('quintoandar-logger').getLogger(module);

const object = { id: 11, someInfo: 'someInfo' }
logger.error(`Some error while processing cool object with id ${object.id}`, { extra: { data: object } });
```

And then it will be displayed on Sentry under the field `Additional Data`.

## TODO

- Create Express Middleware Request Logger
Expand Down
65 changes: 65 additions & 0 deletions src/customFormats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const { format } = require('winston');

function fillExcept(info, fillExceptKeys, metadataKey) {
const savedKeys = fillExceptKeys.reduce((acc, key) => {
acc[key] = info[key];
delete info[key];
return acc;
}, {});
const metadata = Object.keys(info).reduce((acc, key) => {
acc[key] = info[key];
delete info[key];
return acc;
}, {});

Object.assign(info, savedKeys, {
[metadataKey]: metadata
});
return info;
}

function fillWith(info, fillWithKeys, metadataKey) {
info[metadataKey] = fillWithKeys.reduce((acc, key) => {
acc[key] = info[key];
delete info[key];
return acc;
}, {});
return info;
}

const extraData = format((info, opts = {}) => {
let metadataKey = 'extra_data';
if (opts.key) {
metadataKey = opts.key;
}

let fillExceptKeys = [];
if (!opts.fillExcept && !opts.fillWith) {
fillExceptKeys.push('level');
fillExceptKeys.push('message');
}

if (opts.fillExcept) {
fillExceptKeys = opts.fillExcept;
}

if (fillExceptKeys.length > 0) {
return fillExcept(info, fillExceptKeys, metadataKey);
}

if (opts.fillWith) {
return fillWith(info, opts.fillWith, metadataKey);
}

return info;
});

const loggerName = format((info, path) => {
info.logger_name = path;
return info;
});

module.exports = {
loggerName,
extraData,
};
18 changes: 11 additions & 7 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
const { transports, createLogger } = require('winston');
const { transports, format, createLogger } = require('winston');
const Sentry = require('winston-raven-sentry');
const { loggerName, extraData } = require('./customFormats');

function getLogger(mod) {
const path = mod.filename.split('/').slice(-2).join('/');
const winstonTransports = [
new (transports.Console)({
timestamp: true,
colorize: false,
new transports.Console({
format: format.combine(
extraData(),
loggerName(path),
format.timestamp(),
format.json(),
),
level: process.env.CONSOLE_LOG_LEVEL || 'info',
label: path,
stderrLevels: ['error']
stderrLevels: ['error'],
}),
];

Expand All @@ -21,7 +25,7 @@ function getLogger(mod) {
app: process.env.SENTRY_APP,
environment: process.env.SENTRY_ENVIRONMENT,
},
config: {
config: {
captureUnhandledRejections: process.env.CAPTURE_UNHANDLED_REJECTIONS || false,
},
release: process.env.SENTRY_RELEASE,
Expand Down

0 comments on commit 901ec42

Please sign in to comment.