Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adapt plugin to hapi v17 #16

Merged
merged 5 commits into from
Jun 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,29 @@ Logger.debug('Will write to console and send UDP syslog packet');

### hapi.js

#### hapi `>= 17.0.0`

Register as plugin in `manifest.js`:

```
plugin: {
plugin: 'dalee-logger/hapi-17',
options: {
app: 'node-daemon',
hostname: 'example.com',
console: {
enabled: true
},
syslog: {
host: 'example.com',
port: 514
}
}
}
```

#### hapi `>= 15.2.0` `< 17.0.0`

Register as plugin in `manifest.js`:

```
Expand Down
5 changes: 5 additions & 0 deletions express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"use strict";

var _index = require("./dist/index.js");

module.exports = _index.express;
5 changes: 5 additions & 0 deletions hapi-17.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"use strict";

var _index = require("./dist/index.js");

module.exports = _index.hapi17;
5 changes: 5 additions & 0 deletions hapi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"use strict";

var _index = require("./dist/index.js");

module.exports.register = _index.register;
4 changes: 2 additions & 2 deletions src/adapter/console.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import util from 'util';
import {SEVERITY_NAME} from '../constants';
import { SEVERITY_NAME } from '../constants';

/**
* Console adapter
Expand All @@ -13,7 +13,7 @@ export default class Console {
* @constructor
*/
constructor(options) {
this._options = options || {enabled: true};
this._options = options || { enabled: true };
if (!this._options.hasOwnProperty('enabled')) {
this._options.enabled = true;
}
Expand Down
4 changes: 2 additions & 2 deletions src/helpers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {SEVERITY_NAME} from './constants';
import { SEVERITY_NAME } from './constants';
import _ from 'lodash';
import util from 'util';

Expand All @@ -14,7 +14,7 @@ const severityMethods = Object.values(SEVERITY_NAME);
export function processLogData(data, tags) {
const severity = severityFromTags('debug', tags);
const message = formatMessage(severity, data, tags);
return {severity, message};
return { severity, message };
}

/**
Expand Down
26 changes: 18 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import moment from 'moment';

import {FACILITY, SEVERITY, SEVERITY_NAME, FACILITY_CODE, SEVERITY_CODE} from './constants';
import { FACILITY, SEVERITY, SEVERITY_NAME, FACILITY_CODE, SEVERITY_CODE } from './constants';
import LoggerImpl from './logger';
import Syslog from './adapter/syslog';
import Console from './adapter/console';
import Memory from './adapter/memory';
import {setupLogger as setupHapiLogger} from './plugin/hapi';
import { setupLogger as setupHapiLogger } from './plugin/hapi';
import { setupLogger as setupHapi17Logger } from './plugin/hapi-17';
import setupExpress from './plugin/express';

/**
Expand Down Expand Up @@ -138,6 +139,8 @@ const unhandledException = err => {
}, 2000);
};

const pkg = require('../package.json');

// default registrations
// register default logger
moment.locale('en');
Expand All @@ -158,19 +161,26 @@ exports.SEVERITY_CODE = SEVERITY_CODE;
exports.SEVERITY_NAME = SEVERITY_NAME;

// Hapi.js plugin registration
exports.register = (server, options, next) => {
exports.register = async (server, options, next) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

async без await'ов.

Copy link
Contributor

Choose a reason for hiding this comment

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

И, кстати, как hapi < 17 отреагирует на то, что register вернёт промис?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

hapi < 17 нормально это воспринимает. А для 17+ это может быть критично, он await-ит регистрацию плагина.

const hapiLogger = new LoggerImpl();
gLoggerInstances.push(hapiLogger);

setupHapiLogger(hapiLogger, server, options);
next();
if (server.version < '17.0.0') {
setupHapiLogger(hapiLogger, server, options);
return next();
}

setupHapi17Logger(hapiLogger, server, options);
};

// Hapi plugin metadata
exports.register.attributes = {
pkg: require('../package.json')
exports.hapi17 = {
register: exports.register,
pkg
};

// Hapi plugin metadata
exports.register.attributes = { pkg };

// Express.js plugin registration
exports.express = (options) => {
const expressLogger = new LoggerImpl();
Expand Down
2 changes: 1 addition & 1 deletion src/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import util from 'util';
import path from 'path';
import validator from 'validator';

import {FACILITY, SEVERITY, SEVERITY_NAME, FACILITY_CODE, SEVERITY_CODE, SEVERITY_CODE2} from './constants';
import { FACILITY, SEVERITY, SEVERITY_NAME, FACILITY_CODE, SEVERITY_CODE, SEVERITY_CODE2 } from './constants';

/**
* Logger class, singleton
Expand Down
4 changes: 2 additions & 2 deletions src/plugin/express.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {processLogData} from '../helpers';
import { processLogData } from '../helpers';
import Syslog from '../adapter/syslog';
import Console from '../adapter/console';

Expand Down Expand Up @@ -36,7 +36,7 @@ export class ExpressLogger {
if (typeof tags === 'string') {
tags = [tags];
}
const {severity, message} = processLogData(data, tags);
const { severity, message } = processLogData(data, tags);
this._logger[severity](message);
}

Expand Down
74 changes: 74 additions & 0 deletions src/plugin/hapi-17.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Syslog from '../adapter/syslog';
import Console from '../adapter/console';
import HapiPlugin from './hapi-plugin.js';

/**
*
* @param {Object} Logger
* @param {Server} server
* @param {Object} options
*/
export function setupLogger(Logger, server, options) {
const hapiPlugin = new HapiPlugin(Logger);

// always add console as adapter
Logger.setParameters(options);
Logger.addAdapter(Console, options.console || {});

// if syslog object is provided, add syslog adapter
if (options.syslog) {
Logger.addAdapter(Syslog, options.syslog);
}

//
// expose logger everywhere in hapi
//
server.app.logger = Logger;
server.decorate('server', 'logger', Logger);

//
// logging requested via `server.log`
// possible calls:
// - `server.log('error', data);`
// - `server.log(['error', 'database'], data);`
//
server.events.on('log', (...args) => {
hapiPlugin.onServerLog(server, ...args);
});

//
// logging requested via `request.log`
// possible calls:
// - `request.log('error', data);`
// - `request.log(['error', 'database'], data);`
//
server.events.on('request', (...args) => {
hapiPlugin.onRequestLog(...args);
});

//
// error during route handler processing
//
server.events.on({ name: 'request', channels: 'error' }, (...args) => {
hapiPlugin.onRequestError(...args);
});

//
// internal hapi event related to request
// currently we only interested in received sub-event
// to render request before any processing will start
//
server.events.on({ name: 'request', channels: 'internal' }, (...args) => {
hapiPlugin.onRequestInternal(...args);
});

//
// just handler to notify that server is started
//
server.ext({
type: 'onPostStart',
method: (server) => hapiPlugin.onServerStart(server)
});
}

module.exports.HapiPlugin = HapiPlugin;
80 changes: 80 additions & 0 deletions src/plugin/hapi-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { processLogData } from '../helpers';

/**
* HapiPlugin
*
*/
export default class HapiPlugin {

/**
*
* @param {Logger} Logger
* @constructor
*/
constructor(Logger) {
this._logger = Logger;
}

/**
*
* @param {Server} server
* @param next
*/
async onServerStart(server, next) {
this._logger.info('server started:', server.info.uri);

if (server.version < '17.0.0') {
return next();
}
}

/**
*
* @param {Server} server
* @param {Object} event
* @param {Array} tags
*/
onServerLog(server, event, tags) {
const data = event.error || event.data;
const { severity, message } = processLogData(data, tags);
this._logger[severity](message);
}

/**
*
* @param {Request} request
* @param {Object} event
* @param {Array} tags
*/
onRequestLog(request, event, tags) {
const data = event.error || event.data;
const { severity, message } = processLogData(data, tags);
this._logger[severity](message);
}

/**
*
* @param {Request} request
* @param {error} err
*/
onRequestError(request, err) {
this._logger.error(err);
}

/**
*
* @param {Request} request
* @param {Object} event
* @param {Object} tags
*/
onRequestInternal(request, event, tags) {
// new request just received
if (tags.received) {
const method = request.method.toUpperCase();
const proto = (request.headers['x-forwarded-proto'] || request.connection.info.protocol);
const url = `${proto}://${request.info.host}${request.url.path}`;
this._logger.debug(method, url);
}
}

}
Loading