Skip to content

Commit

Permalink
Merge pull request #17 from pinojs/next-major
Browse files Browse the repository at this point in the history
pino v5 update
  • Loading branch information
mcollina authored Aug 7, 2018
2 parents 4273de8 + 4f8ed72 commit 2f4d908
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 106 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: node_js

node_js:
- "9"
- "10"
- "8"
- "6"

Expand Down
84 changes: 52 additions & 32 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,26 @@ prettified logs will look like:
$ npm install -g pino-pretty
```


<a id="usage"></a>
## Usage

It's recommended to use `pino-pretty` with `pino`
by piping output to the CLI tool:

```sh
pino app.js | pino-pretty
```

<a id="cliargs"></a>
## CLI Arguments
### CLI Arguments

+ `--colorize` (`-c`): Adds terminal color escape sequences to the output.
+ `--crlf` (`-f`): Appends carriage return and line feed, instead of just a line
feed, to the formatted log line.
+ `--dateFormat` (`-d`): Sets the format string to apply when translating the date
to human readable format (see: `--translateTime`). The default format string
is `'yyyy-mm-dd HH:MM:ss.l o'`. For a list of available patter letters
is `'yyyy-mm-dd HH:MM:ss.l o'`. For a list of available pattern letters
see the [`dateformat` documentation](https://www.npmjs.com/package/dateformat).
When the value is anything other than the default value, `--translateTime` is
implied.
Expand All @@ -60,12 +71,47 @@ date and time string. See `--dateFormat` for information on the output format.
+ `--search` (`-s`): Specifiy a search pattern according to
[jmespath](http://jmespath.org/).

<a id="api"></a>
## API
<a id="integration"></a>
## Programmatic Integration

We recommend against using `pino-pretty` in production, and highly
recommend installing `pino-pretty` as a development dependency.

When installed, `pretty-print` will be used by `pino` as the default
prettifier.

Install `pino-pretty` alongside `pino` and set the
`prettyPrint` option to `true`:

```js
const pino = require('pino')
const logger = pino({
prettyPrint: true
})

logger.info('hi')
```

The `prettyPrint` option can also be an object containing `pretty-print`
options:

```js
const pino = require('pino')
const logger = pino({
prettyPrint: { colorize: true }
})

logger.info('hi')
```

See the [Options](#options) section for all possible options.

<a id="options"></a>
### Options

`pino-pretty` exports a factory function that can be used to format log strings.
It accepts an options argument with keys corresponding to the options described
in [CLI Arguments](#cliargs):
This factory function is used internally by pino, and accepts an options argument
with keys corresponding to the options described in [CLI Arguments](#cliargs):

```js
{
Expand All @@ -82,32 +128,6 @@ in [CLI Arguments](#cliargs):
}
```

See the [next subsection](#usemetadata) for information on how to use this
directly with `pino`.

<a id="usemetadata"></a>
### pretty.asMetaWrapper(writable)

```js
const factory = require('pino-pretty')
const pino = require('pino')

// writable is any Writable stream
const writable = process.stdout
const dest = factory({ colorize: true }).asMetaWrapper(writable)

const logger = pino({}, dest)
```

The function returned by the factory has a `.asMetaWrapper(dest)` function attached
which will return an object that can be supplied directly to Pino as a stream
that is compatible with Pino's [metadata stream API][mdstream].
This allows `pino-pretty` to skip the expensive task of parsing JSON log lines
and instead work directly with Pino's log object.

The default stream is `process.stdout`.

[mdstream]: https://github.com/pinojs/pino/blob/fc4c83b/docs/API.md#metadata

<a id="license"><a>
## License
Expand Down
11 changes: 6 additions & 5 deletions bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,27 @@ const CONSTANTS = require('./lib/constants')
args
.option(['c', 'colorize'], 'Force adding color sequences to the output')
.option(['f', 'crlf'], 'Append CRLF instead of LF to formatted lines')
.option(['d', 'dateFormat'], 'A format string to govern display of dates. When not set to the default value, `--translateTime` is implied', CONSTANTS.DATE_FORMAT)
.option(['e', 'errorProps'], 'Comma separated list of properties on error objects to show (`*` for all properties)', '')
.option(['l', 'levelFirst'], 'Display the log level as the first output field')
.option(['k', 'errorLikeObjectKeys'], 'Define which keys contain error objects (`-k err,error`)', 'err,error')
.option(['m', 'messageKey'], 'Highlight the message under the specified key', CONSTANTS.MESSAGE_KEY)
.option(['n', 'localTime'], 'Display timestamps according to system timezone')
.option(['t', 'translateTime'], 'Convert Epoch timestamps to ISO format')
.option(['t', 'translateTime'], 'Display epoch timestamps as UTC ISO format or according to an optional format string (default ISO 8601)')
.option(['s', 'search'], 'specifiy a search pattern according to jmespath')

args
.example('cat log | pino-pretty', 'To prettify logs, simply pipe a log file through')
.example('cat log | pino-pretty -m fooMessage', 'To highlight a string at a key other than \'msg\', use')
.example('cat log | pino-pretty -t', 'To convert Epoch timestamps to ISO timestamps use the -t option')
.example('cat log | pino-pretty -t "SYS:yyyy-mm-dd HH:MM:ss"', 'To convert Epoch timestamps to local timezone format use the -t option with "SYS:" prefixed format string')
.example('cat log | pino-pretty -l', 'To flip level and time/date in standard output use the -l option')
.example('cat log | pino-pretty -s \'msg === `hello world`\'', 'Only prints messages with msg equals to \'hello world\'')
.example('cat log | pino-pretty -s "msg == \'hello world\'"', 'Only prints messages with msg equals to \'hello world\'')

const opts = args.parse(process.argv)
const pretty = prettyFactory(opts)
const prettyTransport = through.obj(function (chunk, enc, cb) {
process.stdout.write(pretty(chunk.toString()))
const line = pretty(chunk.toString())
if (line === undefined) return cb()
process.stdout.write(line)
cb()
})

Expand Down
61 changes: 12 additions & 49 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,9 @@ const levels = {
const defaultOptions = {
colorize: false,
crlf: false,
dateFormat: CONSTANTS.DATE_FORMAT,
errorLikeObjectKeys: ['err', 'error'],
errorProps: '',
levelFirst: false,
localTime: false,
messageKey: CONSTANTS.MESSAGE_KEY,
translateTime: false,
useMetadata: false,
Expand All @@ -40,10 +38,18 @@ function isPinoLog (log) {
return log && (log.hasOwnProperty('v') && log.v === 1)
}

function formatTime (epoch, formatString, localTime) {
function formatTime (epoch, translateTime) {
const instant = new Date(epoch)
if (localTime) return dateformat(instant, formatString)
return dateformat(instant, 'UTC:' + formatString)
if (translateTime === true) {
return dateformat(instant, 'UTC:' + CONSTANTS.DATE_FORMAT)
} else {
const upperFormat = translateTime.toUpperCase()
return (!upperFormat.startsWith('SYS:'))
? dateformat(instant, 'UTC:' + translateTime)
: (upperFormat === 'SYS:STANDARD')
? dateformat(instant, CONSTANTS.DATE_FORMAT)
: dateformat(instant, translateTime.slice(4))
}
}

function nocolor (input) {
Expand All @@ -58,10 +64,6 @@ module.exports = function prettyFactory (options) {
const errorLikeObjectKeys = opts.errorLikeObjectKeys
const errorProps = opts.errorProps.split(',')

if (opts.dateFormat.length > 0 && opts.dateFormat !== CONSTANTS.DATE_FORMAT) {
opts.translateTime = true
}

const color = {
default: nocolor,
60: nocolor,
Expand All @@ -84,8 +86,6 @@ module.exports = function prettyFactory (options) {
color.message = ctx.cyan
}

pretty.asMetaWrapper = asMetaWrapper

const search = opts.search

return pretty
Expand Down Expand Up @@ -117,7 +117,7 @@ module.exports = function prettyFactory (options) {
]

if (opts.translateTime) {
log.time = formatTime(log.time, opts.dateFormat, opts.localTime)
log.time = formatTime(log.time, opts.translateTime)
}

var line = `[${log.time}]`
Expand Down Expand Up @@ -252,40 +252,3 @@ module.exports = function prettyFactory (options) {
}
}
}

function asMetaWrapper (dest) {
const parsed = Symbol('parsedChindings')

if (!dest) {
dest = process.stdout
} else if (!dest.write) {
throw new Error('the destination must be writable')
}

const pretty = this

return {
[Symbol.for('needsMetadata')]: true,
lastLevel: 0,
lastMsg: null,
lastObj: null,
lastLogger: null,
write (chunk) {
var chindings = this.lastLogger[parsed]

if (!chindings) {
chindings = JSON.parse('{"v":1' + this.lastLogger.chindings + '}')
this.lastLogger[parsed] = chindings
}

const obj = Object.assign({
level: this.lastLevel,
msg: this.lastMsg,
time: this.lastTime
}, chindings, this.lastObj)

const formatted = pretty(obj)
dest.write(formatted)
}
}
}
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pino-pretty",
"version": "1.0.1",
"version": "2.0.0-rc.1",
"description": "Prettifier for Pino log lines",
"main": "index.js",
"bin": {
Expand Down Expand Up @@ -30,7 +30,7 @@
"test"
],
"dependencies": {
"args": "^3.0.8",
"args": "^5.0.0",
"chalk": "^2.3.2",
"dateformat": "^3.0.3",
"fast-json-parse": "^1.0.3",
Expand All @@ -40,10 +40,10 @@
"through2": "^2.0.3"
},
"devDependencies": {
"pino": "^4.16.0",
"pino": "^5.0.0",
"pre-commit": "^1.2.2",
"snazzy": "^7.1.1",
"standard": "^11.0.1",
"tap": "^11.1.3"
"tap": "^12.0.1"
}
}
Loading

0 comments on commit 2f4d908

Please sign in to comment.