Giter Club home page Giter Club logo

logger's Introduction

koa-logger

npm version build status

Development style logger middleware for koa. Compatible with request-received.

Notice: koa-logger@2 supports koa@2; if you want to use this module with koa@1, please use koa-logger@1.

<-- GET /
--> GET / 200 835ms 746b
<-- GET /
--> GET / 200 960ms 1.9kb
<-- GET /users
--> GET /users 200 357ms 922b
<-- GET /users?page=2
--> GET /users?page=2 200 466ms 4.66kb

Installation

$ npm install koa-logger

Example

const logger = require('koa-logger')
const Koa = require('koa')

const app = new Koa()
app.use(logger())

Notes

Recommended that you .use() this middleware near the top to "wrap" all subsequent middleware.

Use Custom Transporter

const logger = require('koa-logger')
const Koa = require('koa')

const app = new Koa()
app.use(logger((str, args) => {
  // redirect koa logger to other output pipe
  // default is process.stdout(by console.log function)
}))

or

app.use(logger({
  transporter: (str, args) => {
    // ...
  }
}))

Param str is output string with ANSI Color, and you can get pure text with other modules like strip-ansi
Param args is a array by [format, method, url, status, time, length]

License

MIT

logger's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logger's Issues

bug generator in 1.0.1 no in master

Can you publish the master. Version 1.0.1 isn't compatible with koa or co.

assert.js:98
throw new assert.AssertionError({
^
AssertionError: app.use() requires a generator function

Version in master is correct.

Option to disable colors in log output

Our use case for koa-logger doesn't allow for color codes in the output. We're currently using the strip-ansi module to strip those out, however it would be preferable if we could simply disable colored output in the logger options.

ie, something like this:

const logger = require('koa-logger')
const Koa = require('koa')

const app = new Koa()
var loggerTransport = function () { ... }
var loggerConfig = { colorOutput: false }
app.use(logger(loggerTransport, loggerConfig))

Has this been considered? It seems like it would be fairly straightforward to implement. I can submit a PR if the maintainers are open to the idea.

Using in typescript

Cannot install typings

typings install dt~koa-logger --global --save
typings ERR! message Unable to find "koa-logger" ("dt") in the registry.

Non-colored output when under grunt-concurrent

When running under grunt-concurrent, the output is not colored anymore.

  • Not happening when running under nodemon only
  • On the other hand, only logger has this problem under grunt-conrrent (nodemon, watch, debug, all show their colors)

What additional information may I provide to help diagnosing that?

Support request-received v0.0.3

request-received changed what they store in ctx[Symbol.for('request-received.startTime')] from new Date() to Date.now(), so line 59 in index.js needs to drop the .getTime().

Text not visible

I'm using iTerm2 with the Solarized Dark scheme. Unfortunately the output isn't visible (or readable). It looks something like this:

screen shot 2014-12-15 at 2 22 16 pm

Text is definitely there, proof via text marking:

screen shot 2014-12-15 at 2 23 57 pm

why 7?

it looks like there is magenta status code for HTTP statuses starting from 700.

7: 'magenta',

However all the HTTP statuses are less than 600.

messed up error response logs

might just be something else in our app, too lazy to set up a stand-alone test right now

  <-- GET /tj/testing/redshift
  --> GET /tj/testing/redshift ndefinedmundefined 34ms -
Error: fail
...

remove ms

if your response time is more than 1 second (my sample app does API calls to imgur which takes FOREVER) then you'll see the time in integer seconds. i'd prefer if we remove ms and just view the time in milliseconds at least for something reasonable like < 10 seconds.

intercepting body stream makes request.js not setting header of response

in koa-logger, it replaces ctx.body with a Counter:

    if (length == null && body && body.readable) {
      ctx.body = body
        .pipe(counter = Counter())
        .on('error', ctx.onerror)
    }

in request.js, it will add headers to dest stream if it supports setHeader() method:

  // here, if koa-logger is used, dest.setHeader is undefined.

  if (dest.setHeader && !dest.headersSent) {
    for (var i in response.headers) {
      // If the response content is being decoded, the Content-Encoding header
      // of the response doesn't represent the piped content, so don't pass it.
      if (!self.gzip || i !== 'content-encoding') {
        dest.setHeader(i, response.headers[i])
      }
    }
    dest.statusCode = response.statusCode
  }

so, if we use ctx.body = request() and request() returns a stream, the headers from request() stream are lost.

remove bold

is there a reason everything is bold? only method and status should be bold IMO.

Koa-logger@2 not working if used with node < v7.6

Node version 6.9.1

Used

require('babel-register');
require('./src/server');

to transpile the code to use await async.

server.js

var Koa = require("koa");
const logger = require('koa-logger');
var app = new Koa();
var PORT = 4500;

app.use(logger());

app.use((ctx, next) => {
  ctx.body = 'gg wp'
});


app.listen(PORT);
console.log(`server listening on port ${PORT}`);

Error got

C:\Work\codebase\abc\node_modules\koa-logger\index.js:36
  return async function logger (ctx, next) {
               ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Work\codebase\abc\node_modules\babel-register\lib\node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Work\codebase\real-time-monitoring\src\server.js:2:16)

It started working after changing my code to

require('babel-register')
({
  only: "/node_modules/koa-logger/*"
});
require('./src/server');

Better not change the Stream ctx.body

Desc

I did something like this:

app.use(koaLogger).use(async ctx => {
  ctx.type = 'html'
  ctx.set('Content-Encoding', 'gzip')

  ctx.body = zlib.createGzip({
    flush: zlib.constants.Z_FULL_FLUSH,
  })
  ctx.body.write(Buffer.from('before'))
  setTimeout(() => {
    ctx.body.write(Buffer.from('after some async operation'))
    ctx.body.end()
  }, 1000)
})

However, koa-logger changes ctx.body to ctx.body.pipe(counter = Counter()):

logger/index.js

Lines 81 to 83 in 7daa5f4

ctx.body = body
.pipe(counter = Counter())
.on('error', ctx.onerror)

which makes the second write() and end buggy...

Workaround

Write into the original stream, instead of ctx.body

app.use(koaLogger).use(async ctx => {
  ctx.type = 'html'
  ctx.set('Content-Encoding', 'gzip')

  const gzip = zlib.createGzip({
    flush: zlib.constants.Z_FULL_FLUSH,
  })
  ctx.body = gzip
  gzip.write(Buffer.from('before'))
  setTimeout(() => {
    gzip.write(Buffer.from('after some async operation'))
    gzip.end()
  }, 1000)
})

Conclusion

The workaround is simple, but that did make me confused before I read the source code of koa-logger.

I would suggest not to modify the ctx.body itself.

Incorrect Status Outputs

I have a standard koa error catcher like so:

async function(ctx, next) {
  try {
    await next();
  } catch (error) {
    ctx.body = { message: "error"};
    ctx.status = 400;
  }
};

However, the output log is error status 500 no matter what I set ctx.status to. The client receives the correct status code.

Update: Looks like the code is set to use the err.status (such as when set via ctx.throw) rather than ctx.status when there is an error.

Compatibility with Chrome Devtools Node.js debugging

With Chrome Devtools becoming more popular for Node.js debugging and logs - it would be great if this library supported outputting compatible colour information for it as an option.

The chalk module seems to be causing messed up logs in the Devtools console. You can see an example at this issue: chalk/chalk#152

And this is what my console currently looks like on the latest version of Chrome:

image

add dates

still handy sometimes, especially since we're (ab)using this as production logging right now as well haha

It should be nice to replace console with own logger API

For example, using a winston instance instead of console. And even perhaps specifying the level.

app.use(logger({
  logger: winstonInstance,
  level: 'info'
}));

Then, instead of console.log;

opts.logger[opts.level]( ... )

Just have the values default to opts.logger = console and opts.level = 'log'

compatibility with traceur

traceur (from Google) does not work with koa-logger. It reports the following two warnings:

/koa-logger/index.js:70
            function done(event) {
            ^^^^^^^^
SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

and:

/media/data/Documents/quentin/Projects/checkin/node_modules/koa-logger/index.js:30
            console.log('  \033[90m<-- \033[;1m%s\033[0;90m %s\033[0m', this.m
                                                               ^^
SyntaxError: Octal literals are not allowed in strict mode.

Performance Impact enabling koa-logger

Hi, I can advice a performance impact enabling koa-logger is it right?
it should not be used on production servers?

bench results of an hello world app.

With logger enabled (koa +koa-route +koa-logger)

ab -n 1000 -c 100 http://127.0.0.1:3001/hello
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:
Server Hostname:        127.0.0.1
Server Port:            3001

Document Path:          /hello
Document Length:        31 bytes

Concurrency Level:      100
Time taken for tests:   0.581 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      167000 bytes
HTML transferred:       31000 bytes
Requests per second:    1722.55 [#/sec] (mean)
Time per request:       58.053 [ms] (mean)
Time per request:       0.581 [ms] (mean, across all concurrent requests)
Transfer rate:          280.92 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    5   4.4      4      27
Processing:    24   50  14.7     47     103
Waiting:       21   50  14.7     46     102
Total:         28   55  13.9     51     104

Percentage of the requests served within a certain time (ms)
  50%     51
  66%     55
  75%     58
  80%     63
  90%     79
  95%     82
  98%     87
  99%     90
 100%    104 (longest request)

and without logger (koa +koa-route)

ab -n 1000 -c 100 http://127.0.0.1:3001/hello
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:
Server Hostname:        127.0.0.1
Server Port:            3001

Document Path:          /hello
Document Length:        31 bytes

Concurrency Level:      100
Time taken for tests:   0.342 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      167000 bytes
HTML transferred:       31000 bytes
Requests per second:    2920.12 [#/sec] (mean)
Time per request:       34.245 [ms] (mean)
Time per request:       0.342 [ms] (mean, across all concurrent requests)
Transfer rate:          476.23 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   2.1      1      13
Processing:     3   30   6.0     32      42
Waiting:        3   30   6.0     31      41
Total:         16   32   4.5     33      43

Percentage of the requests served within a certain time (ms)
  50%     33
  66%     35
  75%     35
  80%     36
  90%     37
  95%     38
  98%     42
  99%     42
 100%     43 (longest request)

Regards.

Logging in Nanoseconds

Hey,

Would like to request the ability to have the option to allow logging in nanoseconds if the response time is under a millisecond. There is process.hrtime() in node, and while its relatively inaccurate, it would be great to have the option to have nanosecond outputs.

Thanks.

TypeError: chalk[color] is not a function

TypeError: chalk[color] is not a function at log (/Users/durban/nodejs/qeeniao-wap-web/node_modules/koa-logger/index.js:119:25) at done (/Users/durban/nodejs/qeeniao-wap-web/node_modules/koa-logger/index.js:76:9) at ServerResponse.g (events.js:260:16) at emitNone (events.js:72:20) at ServerResponse.emit (events.js:166:7) at finish (_http_outgoing.js:545:10) at doNTCallback0 (node.js:430:9) at process._tickDomainCallback (node.js:400:13)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.