Skip to content

Commit 33742c9

Browse files
committed
some minor improvements
1 parent ac7e187 commit 33742c9

File tree

3 files changed

+110
-116
lines changed

3 files changed

+110
-116
lines changed

Readme.md

+14-15
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
# micrologger
22

3-
Meaningful application and request logs to be used with koa microservices
3+
Simple but meaningful application and request logs to be used with koa microservices
44

55
Support for rotating files and/or sending to a logging collector fluentd (more to come)
66

7-
Add to the top of your koa application and pass in koa app:
7+
Add to the top of your koa application and pass in koa app to get started:
88

99
```js
1010
const app = require('koa')();
1111
const logger = require('micrologger');
12-
logger(app);
12+
app.use(logger());
1313
```
1414
This will give you all application and request logs:
1515

1616
Make sure to pass NODE_ENV=development for local development
1717

18-
Rotating log files will be saved to 'logs/out.log' in the root of your app. Rotating files can be turned off by passing in logToFile:false
18+
Rotating log files will be saved to 'logs/out.log' in the root of your app. Pass logToFile:true in the options and pass in NODE_ENV=developemnt to use rotating files
1919

2020
That is all you need for micrologger to start collecting and sending logs.
2121

@@ -109,12 +109,12 @@ You can add fluentd as a collector
109109
add the fluent block below and all the logs will be sent to fluentd
110110

111111
```js
112-
logger(app, {
112+
app.use(logger({
113113
fluent: {
114114
host: '127.0.0.1',
115115
port: '24224'
116116
}
117-
});
117+
}))
118118
```
119119

120120
```sh
@@ -136,7 +136,7 @@ Example of application error in /logs/out.log
136136
## Log info/error
137137
```js
138138
logger.info('Info Message');
139-
logger.info('Some error message');
139+
logger.error('Some error message');
140140
```
141141
The info and error message will be logged with the following structure:
142142

@@ -165,18 +165,17 @@ The info and error message will be logged with the following structure:
165165
## All options
166166

167167
```js
168-
logger(app, {
168+
app.use(logger({
169169
logsToFile: false,
170-
requestLogs: false,
171-
appLogs: false,
170+
appLogs: true,
172171
backgroundColor: 'dark',
173172
fluent: {
174173
host: '127.0.0.1',
175174
port: '24224'
176175
}
177-
})
176+
}))
178177
```
179-
* logToFile: (default is true)
180-
* requestLogs: (default is true)
181-
* appLogs: (default is true)
182-
* backgroundColor: this is the background color of your terminal. options are dark/light (default is dark)
178+
* logToFile: (optional, default is false)
179+
* appLogs: (optional, default is true) if set to false application errors will not be logged. This does not include request errors
180+
* backgroundColor: (optional) this is the background color of your terminal. options are dark/light (default is dark)
181+
* fluent with host, port

index.js

+93-100
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,33 @@ const os = require('os')
66
, sock = zeromq.socket('pub')
77
, chalk = require('chalk')
88
, humanize = require('humanize-number')
9+
, stripAnsi = require('strip-ansi')
910
, uuid = require('uuid')
1011
, stream = require('stream')
1112
, logrotate = require('logrotate-stream')
1213
, reqPath = require('app-root-path').require
1314
, name = reqPath('/package.json').name
1415

1516
let collector;
16-
let logToFile = true;
17+
let logToFile = false;
1718
let color = chalk.bold.white;
18-
function app(app, opts) {
19+
let req;
20+
let error = false;
21+
function log(opts) {
1922
if(opts && opts.backgroundColor) {
2023
if(opts.backgroundColor === 'white'){
2124
color = chalk.bold.black;
2225
} else {
2326
color = chalk.bold.white;
2427
}
2528
}
29+
if(opts && opts.zmq) {
30+
sock.connect(`tcp://${opts.zmq.addr}`);
31+
collector = 'zmq';
32+
}
33+
if(opts && opts.logToFile === true) {
34+
logToFile = true
35+
}
2636
if(opts && opts.fluent) {
2737
fluentlogger.configure('tag_prefix', {
2838
host: opts.fluent.host,
@@ -32,100 +42,17 @@ function app(app, opts) {
3242
});
3343
collector = 'fluent';
3444
}
35-
if(opts && opts.zmq) {
36-
sock.connect(`tcp://${opts.zmq.addr}`);
37-
collector = 'zmq';
38-
}
39-
if(opts && opts.logToFile === false) {
40-
logToFile = false
41-
}
42-
if(!opts || opts && opts.appLogs !== false) {
45+
if(opts && opts.appLogs !== false) {
4346
logUncaughtError();
4447
}
45-
if(!opts || opts && opts.requestLogs !== false) {
46-
app.use(request());
47-
}
48-
}
49-
50-
function logUncaughtError (err) {
51-
process.on('uncaughtException', function(err) {
52-
err = err.stack.replace(/(?:\r\n|\r|\n)\s\s+/g, ' ');
53-
let log = {
54-
class: 'application',
55-
ident: name,
56-
host: os.hostname(),
57-
pid: process.pid,
58-
severity: 'INFO',
59-
message: err
60-
}
61-
if(logToFile) {
62-
pipeLogsToFile(log);
63-
}
64-
if(process.env.NODE_ENV === 'development') {
65-
console.log(chalk.red.bold(err));
66-
} else {
67-
collectLogs('application', log);
68-
}
69-
setTimeout(process.exit.bind(process, 1), 1000);
70-
});
71-
}
72-
73-
function logInfo (data) {
74-
let log = {
75-
class: 'application',
76-
ident: name,
77-
host: os.hostname(),
78-
pid: process.pid,
79-
severity: 'INFO',
80-
message: data
81-
}
82-
if(logToFile) {
83-
pipeLogsToFile(log);
84-
}
85-
if(process.env.NODE_ENV === 'development') {
86-
console.log(color(data));
87-
} else {
88-
collectLogs('application', log);
89-
}
90-
}
91-
92-
function logError (err) {
93-
let log = {
94-
class: 'application',
95-
ident: name,
96-
host: os.hostname(),
97-
pid: process.pid,
98-
severity: 'ERROR',
99-
message: err
100-
}
101-
if(logToFile) {
102-
pipeLogsToFile(log);
103-
}
104-
if(process.env.NODE_ENV === 'development') {
105-
console.log(chalk.red.bold(err));
106-
} else {
107-
collectLogs('application', log);
108-
}
109-
}
110-
111-
function pipeLogsToFile (data) {
112-
let bufferStream = new stream.PassThrough();
113-
bufferStream.end(new Buffer(JSON.stringify(data) + '\n'));
114-
if (!fs.existsSync('./logs')){
115-
fs.mkdirSync('./logs');
116-
}
117-
let toLogFile = logrotate({ file: './logs/out.log', size: '500k', keep: 7 });
118-
bufferStream.pipe(toLogFile);
119-
}
120-
121-
function request() {
12248
return function *(next) {
12349
let ctx = this;
12450
let res = ctx.res;
12551
let reqTime = new Date;
12652
let classname = (ctx.request.headers['x-correlation-id']) ? 'service_request' : 'client_request';
12753
let correlationId = ctx.request.headers['x-correlation-id'] || uuid.v4();
12854
ctx.request.headers['x-correlation-id'] = correlationId;
55+
req = true;
12956
try {
13057
yield next;
13158
} catch (err) {
@@ -145,7 +72,7 @@ function request() {
14572
request_id: requestId,
14673
ident: name,
14774
class: classname,
148-
message: `${ctx.request.method} ${ctx.request.url}`,
75+
message: `<-- ${ctx.request.method} ${ctx.request.url}`,
14976
host: os.hostname(),
15077
client: ctx.request.ip || ctx.request.headers['x-forwarded-for'],
15178
path: ctx.request.url,
@@ -159,7 +86,7 @@ function request() {
15986
request_id: requestId,
16087
ident: name,
16188
class: classname,
162-
message: `${ctx.response.status} ${ctx.response.message} ${ctx.request.url}`,
89+
message: `--> ${ctx.response.status} ${ctx.response.message} ${ctx.request.url}`,
16390
host: os.hostname(),
16491
client: ctx.request.ip || ctx.request.headers['x-forwarded-for'],
16592
path: ctx.request.url,
@@ -171,25 +98,91 @@ function request() {
17198
severity: ctx.response.status >= 400 ? 'ERROR' : 'INFO',
17299
metadata: {}
173100
}
174-
if(logToFile){
175-
pipeLogsToFile(request);
176-
pipeLogsToFile(response);
101+
logInfo(request.message);
102+
if(response.severity === 'ERROR') {
103+
logError(response.message);
104+
} else {
105+
logInfo(response.message);
177106
}
178107
if(process.env.NODE_ENV === 'development') {
179-
console.log(chalk.cyan.underline.bold(request.message));
180-
if(response.severity === 'ERROR') {
181-
console.log(chalk.red.bold(response.message));
182-
} else {
183-
console.log(chalk.green.bold(response.message));
108+
if(logToFile){
109+
pipeLogsToFile(request);
110+
pipeLogsToFile(response);
184111
}
185-
} else {
112+
} else if(collector) {
186113
collectLogs('request', request);
187114
collectLogs('response', response);
188115
}
189116
}
190117
}
191118
}
192119

120+
function logUncaughtError () {
121+
process.on('uncaughtException', function(err) {
122+
err = stripAnsi(err.stack);
123+
error = true;
124+
logError(err)
125+
setTimeout(process.exit.bind(process, 1), 1000);
126+
});
127+
}
128+
129+
function logInfo (data) {
130+
data = stripAnsi(data);
131+
let log = {
132+
class: 'application',
133+
ident: name,
134+
host: os.hostname(),
135+
pid: process.pid,
136+
severity: 'INFO',
137+
message: data
138+
}
139+
if(data.indexOf('<--') !== -1){
140+
console.log(chalk.cyan.underline.bold(data));
141+
} else if(data.indexOf('-->') !== -1) {
142+
console.log(chalk.green.bold(data));
143+
} else {
144+
console.log(color(data));
145+
if(process.env.NODE_ENV === 'development') {
146+
if(logToFile){
147+
pipeLogsToFile(log);
148+
}
149+
} else if(collector) {
150+
collectLogs('application', log);
151+
}
152+
}
153+
}
154+
155+
function logError (err) {
156+
err = stripAnsi(err);
157+
let log = {
158+
class: 'application',
159+
ident: name,
160+
host: os.hostname(),
161+
pid: process.pid,
162+
severity: 'ERROR',
163+
message: err
164+
}
165+
console.error(chalk.red.bold(err));
166+
if(process.env.NODE_ENV === 'development') {
167+
if(logToFile){
168+
pipeLogsToFile(log);
169+
}
170+
} else if(collector && error) {
171+
collectLogs('application', log);
172+
error = false;
173+
}
174+
}
175+
176+
function pipeLogsToFile (data) {
177+
let bufferStream = new stream.PassThrough();
178+
bufferStream.end(new Buffer(JSON.stringify(data) + '\n'));
179+
if (!fs.existsSync('./logs')){
180+
fs.mkdirSync('./logs');
181+
}
182+
let toLogFile = logrotate({ file: './logs/out.log', size: '500k', keep: 7 });
183+
bufferStream.pipe(toLogFile);
184+
}
185+
193186
function collectLogs(type, data) {
194187
switch (collector) {
195188
case 'fluent':
@@ -211,6 +204,6 @@ function time(start) {
211204
return humanize(delta);
212205
}
213206

214-
module.exports = app
207+
module.exports = log
215208
module.exports.info = logInfo
216-
module.exports.error = logError
209+
module.exports.error = logError

package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "micrologger",
3-
"version": "2.0.2",
3+
"version": "2.0.3",
44
"description": "koa microservice application and request logging",
55
"main": "index.js",
66
"scripts": {
@@ -21,11 +21,13 @@
2121
"author": "Erik Scott",
2222
"license": "MIT",
2323
"dependencies": {
24+
"ain2": "^2.0.0",
2425
"app-root-path": "^2.0.1",
2526
"chalk": "^1.1.3",
2627
"fluent-logger": "^2.2.0",
2728
"humanize-number": "0.0.2",
2829
"logrotate-stream": "^0.2.5",
30+
"strip-ansi": "^3.0.1",
2931
"uuid": "^3.0.1",
3032
"zmq": "^2.15.3"
3133
},

0 commit comments

Comments
 (0)