This commit is contained in:
Tutur33
2023-11-24 23:58:26 +01:00
parent 25395c0ee1
commit 938ad9d309
4191 changed files with 41 additions and 518781 deletions
-13
View File
@@ -1,13 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
# [*.md]
# trim_trailing_whitespace = false
-8
View File
@@ -1,8 +0,0 @@
{
"extends": [
"standard"
],
"rules": {
"no-var": "off"
}
}
-8
View File
@@ -1,8 +0,0 @@
coverage: true
coverage-map: 'coverage-map.js'
reporter: terse
files:
- 'lib/**/*.test.js'
- 'test/**/*.test.js'
-23
View File
@@ -1,23 +0,0 @@
The MIT License (MIT)
Copyright (c) 2019 the Pino team
Pino team listed at https://github.com/pinojs/pino#the-team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-381
View File
@@ -1,381 +0,0 @@
<a id="intro"></a>
# pino-pretty
[![NPM Package Version](https://img.shields.io/npm/v/pino-pretty)](https://www.npmjs.com/package/pino-pretty)
[![Build Status](https://img.shields.io/github/actions/workflow/status/pinojs/pino-pretty/ci.yml?branch=master)](https://github.com/pinojs/pino-pretty/actions?query=workflow%3ACI)
[![Coverage Status](https://img.shields.io/coveralls/github/pinojs/pino-pretty)](https://coveralls.io/github/pinojs/pino-pretty?branch=master)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
This module provides a basic [ndjson](http://ndjson.org/) formatter to be used in __development__. If an
incoming line looks like it could be a log line from an ndjson logger, in
particular the [Pino](https://getpino.io/) logging library, then it will apply
extra formatting by considering things like the log level and timestamp.
A standard Pino log line like:
```
{"level":30,"time":1522431328992,"msg":"hello world","pid":42,"hostname":"foo","v":1}
```
Will format to:
```
[17:35:28.992] INFO (42): hello world
```
If you landed on this page due to the deprecation of the `prettyPrint` option
of `pino`, read the [Programmatic Integration](#integration) section.
<a id="example"></a>
## Example
Using the [example script][exscript] from the Pino module, we can see what the
prettified logs will look like:
![demo](demo.png)
[exscript]: https://github.com/pinojs/pino/blob/25ba61f40ea5a1a753c85002812426d765da52a4/examples/basic.js
<a id="install"></a>
## Install
```sh
$ npm install -g pino-pretty
```
<a id="usage"></a>
## Usage
It is recommended to use `pino-pretty` with `pino`
by piping output to the CLI tool:
```sh
node app.js | pino-pretty
```
<a id="cliargs"></a>
### CLI Arguments
- `--colorize` (`-c`): Adds terminal color escape sequences to the output.
- `--colorizeObjects` (`-C`): Allows suppressing colorization of objects when set to `false`. In combination with `--singleLine`, this ensures that the end of each line is parsable JSON.
- `--crlf` (`-f`): Appends carriage return and line feed, instead of just a line
feed, to the formatted log line.
- `--errorProps` (`-e`): When formatting an error object, display this list
of properties. The list should be a comma-separated list of properties Default: `''`.
Do not use this option if logging from pino@7. Support will be removed from future verions.
- `--levelFirst` (`-l`): Display the log level name before the logged date and time.
- `--errorLikeObjectKeys` (`-k`): Define the log keys that are associated with
error like objects. Default: `err,error`.
- `--messageKey` (`-m`): Define the key that contains the main log message.
Default: `msg`.
- `--levelKey` (`--levelKey`): Define the key that contains the level of the log. Nested keys are supported with each property delimited by a dot character (`.`).
Keys may be escaped to target property names that contains the delimiter itself:
(`--levelKey tags\\.level`).
Default: `level`.
- `--levelLabel` (`-b`): Output the log level using the specified label.
Default: `levelLabel`.
- `--minimumLevel` (`-L`): Hide messages below the specified log level. Accepts a number, `trace`, `debug`, `info`, `warn`, `error`, or `fatal`. If any more filtering is required, consider using [`jq`](https://stedolan.github.io/jq/).
- `--customLevels` (`-x`): Override default levels with custom levels, e.g. `-x err:99,info:1`
- `--customColors` (`-X`): Override default colors with custom colors, e.g. `-X err:red,info:blue`
- `--useOnlyCustomProps` (`-U`): Only use custom levels and colors (if provided) (default: true); else fallback to default levels and colors, e.g. `-U false`
- `--messageFormat` (`-o`): Format output of message, e.g. `{levelLabel} - {pid} - url:{req.url}` will output message: `INFO - 1123 - url:localhost:3000/test`
Default: `false`
- `--timestampKey` (`-a`): Define the key that contains the log timestamp.
Default: `time`.
- `--translateTime` (`-t`): Translate the epoch time value into a human-readable
date and time string. This flag also can set the format string to apply when
translating the date to a human-readable format. For a list of available pattern
letters, see the [`dateformat` documentation](https://www.npmjs.com/package/dateformat).
- The default format is `HH:MM:ss.l` in the local timezone.
- Require a `UTC:` prefix to translate time to UTC, e.g. `UTC:yyyy-mm-dd HH:MM:ss.l o`.
- Require a `SYS:` prefix to translate time to the local system's time zone. A
shortcut `SYS:standard` to translate time to `yyyy-mm-dd HH:MM:ss.l o` in
system time zone.
- `--ignore` (`-i`): Ignore one or several keys, nested keys are supported with each property delimited by a dot character (`.`),
keys may be escaped to target property names that contains the delimiter itself:
(`-i time,hostname,req.headers,log\\.domain\\.corp/foo`).
The `--ignore` option would be ignored, if both `--ignore` and `--include` are passed.
Default: `hostname`.
- `--include` (`-I`): The opposite of `--ignore`. Include one or several keys.
- `--hideObject` (`-H`): Hide objects from output (but not error object)
- `--singleLine` (`-S`): Print each log message on a single line (errors will still be multi-line)
- `--config`: Specify a path to a config file containing the pino-pretty options. pino-pretty will attempt to read from a `.pino-prettyrc` in your current directory (`process.cwd`) if not specified
<a id="integration"></a>
## Programmatic Integration
We recommend against using `pino-pretty` in production and highly
recommend installing `pino-pretty` as a development dependency.
Install `pino-pretty` alongside `pino` and set the transport target to `'pino-pretty'`:
```js
const pino = require('pino')
const logger = pino({
transport: {
target: 'pino-pretty'
},
})
logger.info('hi')
```
The transport option can also have an options object containing `pino-pretty` options:
```js
const pino = require('pino')
const logger = pino({
transport: {
target: 'pino-pretty',
options: {
colorize: true
}
}
})
logger.info('hi')
```
Use it as a stream:
```js
const pino = require('pino')
const pretty = require('pino-pretty')
const logger = pino(pretty())
logger.info('hi')
```
Options are also supported:
```js
const pino = require('pino')
const pretty = require('pino-pretty')
const stream = pretty({
colorize: true
})
const logger = pino(stream)
logger.info('hi')
```
See the [Options](#options) section for all possible options.
### Usage as a stream
If you are using `pino-pretty` as a stream and you need to provide options to `pino`,
pass the options as the first argument and `pino-pretty` as second argument:
```js
const pino = require('pino')
const pretty = require('pino-pretty')
const stream = pretty({
colorize: true
})
const logger = pino({ level: 'info' }, stream)
// Nothing is printed
logger.debug('hi')
```
### Usage with Jest
Logging with Jest is _problematic_, as the test framework requires no asynchronous operation to
continue after the test has finished. The following is the only supported way to use this module
with Jest:
```js
import pino from 'pino'
import pretty from 'pino-pretty'
test('test pino-pretty', () => {
const logger = pino(pretty({ sync: true }));
logger.info('Info');
logger.error('Error');
});
```
### Handling non-serializable options
Using the new [pino v7+
transports](https://getpino.io/#/docs/transports?id=v7-transports) not all
options are serializable, for example if you want to use `messageFormat` as a
function you will need to wrap `pino-pretty` in a custom module.
Executing `main.js` below will log a colorized `hello world` message using a
custom function `messageFormat`:
```js
// main.js
const pino = require('pino')
const logger = pino({
transport: {
target: './pino-pretty-transport',
options: {
colorize: true
}
},
})
logger.info('world')
```
```js
// pino-pretty-transport.js
module.exports = opts => require('pino-pretty')({
...opts,
messageFormat: (log, messageKey) => `hello ${log[messageKey]}`
})
```
<a id="options"></a>
### Options
The options accepted have keys corresponding to the options described in [CLI Arguments](#cliargs):
```js
{
colorize: colorette.isColorSupported, // --colorize
colorizeObjects: true, //--colorizeObjects
crlf: false, // --crlf
errorLikeObjectKeys: ['err', 'error'], // --errorLikeObjectKeys
errorProps: '', // --errorProps
levelFirst: false, // --levelFirst
messageKey: 'msg', // --messageKey
levelKey: 'level', // --levelKey
messageFormat: false, // --messageFormat
timestampKey: 'time', // --timestampKey
translateTime: false, // --translateTime
ignore: 'pid,hostname', // --ignore
include: 'level,time', // --include
hideObject: false, // --hideObject
singleLine: false, // --singleLine
config: '/path/to/config/', // --config
customColors: 'err:red,info:blue', // --customColors
customLevels: 'err:99,info:1', // --customLevels
levelLabel: 'levelLabel', // --levelLabel
minimumLevel: 'info', // --minimumLevel
useOnlyCustomProps: true, // --useOnlyCustomProps
// The file or file descriptor (1 is stdout) to write to
destination: 1,
// Alternatively, pass a `sonic-boom` instance (allowing more flexibility):
// destination: new SonicBoom({ dest: 'a/file', mkdir: true })
// You can also configure some SonicBoom options directly
sync: false, // by default we write asynchronously
append: true, // the file is opened with the 'a' flag
mkdir: true, // create the target destination
customPrettifiers: {}
}
```
The `colorize` default follows
[`colorette.isColorSupported`](https://github.com/jorgebucaran/colorette#iscolorsupported).
The defaults for `sync`, `append`, `mkdir` inherit from
[`SonicBoom(opts)`](https://github.com/pinojs/sonic-boom#API).
`customPrettifiers` option provides the ability to add a custom prettify function
for specific log properties. `customPrettifiers` is an object, where keys are
log properties that will be prettified and value is the prettify function itself.
For example, if a log line contains a `query` property,
you can specify a prettifier for it:
```js
{
customPrettifiers: {
query: prettifyQuery
}
}
//...
const prettifyQuery = value => {
// do some prettify magic
}
```
Additionally, `customPrettifiers` can be used to format the `time`, `hostname`,
`pid`, `name`, `caller` and `level` outputs:
```js
{
customPrettifiers: {
// The argument for this function will be the same
// string that's at the start of the log-line by default:
time: timestamp => `🕰 ${timestamp}`,
// The argument for the level-prettifier may vary depending
// on if the levelKey option is used or not.
// By default this will be the same numerics as the Pino default:
level: logLevel => `LEVEL: ${logLevel}`
// other prettifiers can be used for the other keys if needed, for example
hostname: hostname => colorGreen(hostname)
pid: pid => colorRed(pid)
name: name => colorBlue(name)
caller: caller => colorCyan(caller)
}
}
```
Note that prettifiers do not include any coloring, if the stock coloring on
`level` is desired, it can be accomplished using the following:
```js
const { colorizerFactory } = require('pino-pretty')
const levelColorize = colorizerFactory(true)
const levelPrettifier = logLevel => `LEVEL: ${levelColorize(logLevel)}`
//...
{
customPrettifiers: { level: levelPrettifier }
}
```
`messageFormat` option allows you to customize the message output.
A template `string` like this can define the format:
```js
{
messageFormat: '{levelLabel} - {pid} - url:{req.url}'
}
```
In addition to this, if / end statement blocks can also be specified.
Else statements and nested conditions are not supported.
```js
{
messageFormat: '{levelLabel} - {if pid}{pid} - {end}url:{req.url}'
}
```
This option can also be defined as a `function` with this prototype:
```js
{
messageFormat: (log, messageKey, levelLabel) => {
// do some log message customization
return customized_message;
}
}
```
## Limitations
Because `pino-pretty` uses stdout redirection, in some cases the command may
terminate with an error due to shell limitations.
For example, currently, mingw64 based shells (e.g. Bash as supplied by [git for
Windows](https://gitforwindows.org)) are affected and terminate the process with
a `stdout is not a tty` error message.
Any PRs are welcomed!
<a id="license"></a>
## License
MIT License
-105
View File
@@ -1,105 +0,0 @@
'use strict'
// We do not expect amazing numbers from `pino-pretty` as the whole purpose
// of the module is a very slow operation. However, this benchmark should give
// us some guidance on how features, or code changes, will affect the
// performance of the module.
const bench = require('fastbench')
const {
prettyFactory
} = require('./index')
const max = 10
const tstampMillis = 1693401358754
/* eslint-disable no-var */
const run = bench([
function basicLog (cb) {
const pretty = prettyFactory({})
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","msg":"benchmark","foo":"foo","bar":{"bar":"bar"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function objectLog (cb) {
const pretty = prettyFactory({})
const input = {
time: tstampMillis,
pid: 1,
hostname: 'foo',
msg: 'benchmark',
foo: 'foo',
bar: { bar: 'bar' }
}
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function coloredLog (cb) {
const pretty = prettyFactory({ colorize: true })
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","msg":"benchmark","foo":"foo","bar":{"bar":"bar"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function customPrettifiers (cb) {
const pretty = prettyFactory({
customPrettifiers: {
time (tstamp) {
return tstamp
},
pid () {
return ''
}
}
})
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","msg":"benchmark","foo":"foo","bar":{"bar":"bar"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function logWithErrorObject (cb) {
const pretty = prettyFactory({})
const err = Error('boom')
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","msg":"benchmark","foo":"foo","bar":{"bar":"bar"},"err":{"message":"${err.message}","stack":"${err.stack}"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function logRemappedMsgErrKeys (cb) {
const pretty = prettyFactory({
messageKey: 'message',
errorLikeObjectKeys: ['myError']
})
const err = Error('boom')
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","message":"benchmark","foo":"foo","bar":{"bar":"bar"},"myError":{"message":"${err.message}","stack":"${err.stack}"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
},
function messageFormatString (cb) {
const pretty = prettyFactory({
messageFormat: '{levelLabel}{if pid} {pid} - {end}{msg}'
})
const input = `{"time":${tstampMillis},"pid":1,"hostname":"foo","msg":"benchmark","foo":"foo","bar":{"bar":"bar"}}\n`
for (var i = 0; i < max; i += 1) {
pretty(input)
}
setImmediate(cb)
}
], 10000)
run(run)
-116
View File
@@ -1,116 +0,0 @@
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const help = require('help-me')({
dir: path.join(__dirname, 'help'),
ext: '.txt'
})
const pump = require('pump')
const sjp = require('secure-json-parse')
const JoyCon = require('joycon')
const stripJsonComments = require('strip-json-comments')
const build = require('./')
const CONSTANTS = require('./lib/constants')
const { isObject } = require('./lib/utils')
const minimist = require('minimist')
const parseJSON = input => {
return sjp.parse(stripJsonComments(input), { protoAction: 'remove' })
}
const joycon = new JoyCon({
parseJSON,
files: [
'pino-pretty.config.cjs',
'pino-pretty.config.js',
'.pino-prettyrc',
'.pino-prettyrc.json'
],
stopDir: path.dirname(process.cwd())
})
const cmd = minimist(process.argv.slice(2))
helper(cmd)
const DEFAULT_VALUE = '\0default'
let opts = minimist(process.argv, {
alias: {
colorize: 'c',
colorizeObjects: 'C',
crlf: 'f',
errorProps: 'e',
levelFirst: 'l',
minimumLevel: 'L',
customLevels: 'x',
customColors: 'X',
useOnlyCustomProps: 'U',
errorLikeObjectKeys: 'k',
messageKey: 'm',
levelKey: CONSTANTS.LEVEL_KEY,
levelLabel: 'b',
messageFormat: 'o',
timestampKey: 'a',
translateTime: 't',
ignore: 'i',
include: 'I',
hideObject: 'H',
singleLine: 'S'
},
default: {
messageKey: DEFAULT_VALUE,
minimumLevel: DEFAULT_VALUE,
levelKey: DEFAULT_VALUE,
timestampKey: DEFAULT_VALUE
}
})
// Remove default values
opts = filter(opts, value => value !== DEFAULT_VALUE)
const config = loadConfig(opts.config)
// Override config with cli options
opts = Object.assign({}, config, opts)
// set defaults
opts.errorLikeObjectKeys = opts.errorLikeObjectKeys || 'err,error'
opts.errorProps = opts.errorProps || ''
const res = build(opts)
pump(process.stdin, res)
// https://github.com/pinojs/pino/pull/358
/* istanbul ignore next */
if (!process.stdin.isTTY && !fs.fstatSync(process.stdin.fd).isFile()) {
process.once('SIGINT', function noOp () {})
}
function loadConfig (configPath) {
const files = configPath ? [path.resolve(configPath)] : undefined
const result = joycon.loadSync(files)
if (result.path && !isObject(result.data)) {
configPath = configPath || path.basename(result.path)
throw new Error(`Invalid runtime configuration file: ${configPath}`)
}
if (configPath && !result.data) {
throw new Error(`Failed to load runtime configuration file: ${configPath}`)
}
return result.data
}
function filter (obj, cb) {
return Object.keys(obj).reduce((acc, key) => {
const value = obj[key]
if (cb(value, key)) {
acc[key] = value
}
return acc
}, {})
}
function helper (cmd) {
if (cmd.h || cmd.help) {
help.toStdout()
}
}
-9
View File
@@ -1,9 +0,0 @@
'use strict'
module.exports = testFile => {
// Ignore coverage on files that do not have a direct corollary.
if (testFile.startsWith('test/')) return false
// Indicate the matching name, sans '.test.js', should be checked for coverage.
return testFile.replace(/\.test\.js$/, '.js')
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

-214
View File
@@ -1,214 +0,0 @@
// Type definitions for pino-pretty 7.0
// Project: https://github.com/pinojs/pino-pretty#readme
// Definitions by: Adam Vigneaux <https://github.com/AdamVig>
// tearwyx <https://github.com/tearwyx>
// Minimum TypeScript Version: 3.0
/// <reference types="node" />
import { Transform } from 'stream';
import { OnUnknown } from 'pino-abstract-transport';
// @ts-ignore fall back to any if pino is not available, i.e. when running pino tests
import { DestinationStream, Level } from 'pino';
type LogDescriptor = Record<string, unknown>;
declare function PinoPretty(options?: PrettyOptions_): PinoPretty.PrettyStream;
declare function colorizerFactory(
useColors?: boolean,
customColors?: [number, string][],
useOnlyCustomProps?: boolean,
): {
(
level?: number | string,
opts?: {
customLevels?: { [level: number]: string };
customLevelNames?: { [name: string]: number };
},
): string,
message: (input: string | number) => string,
greyMessage: (input: string | number) => string,
}
declare function prettyFactory(
options: PrettyOptions_,
): (inputData: any) => string
interface PrettyOptions_ {
/**
* Hide objects from output (but not error object).
* @default false
*/
hideObject?: boolean;
/**
* Translate the epoch time value into a human readable date and time string. This flag also can set the format
* string to apply when translating the date to human readable format. For a list of available pattern letters
* see the {@link https://www.npmjs.com/package/dateformat|dateformat documentation}.
* - The default format is `yyyy-mm-dd HH:MM:ss.l o` in UTC.
* - Requires a `SYS:` prefix to translate time to the local system's timezone. Use the shortcut `SYS:standard`
* to translate time to `yyyy-mm-dd HH:MM:ss.l o` in system timezone.
* @default false
*/
translateTime?: boolean | string;
/**
* If set to true, it will print the name of the log level as the first field in the log line.
* @default false
*/
levelFirst?: boolean;
/**
* Define the key that contains the level of the log.
* @default "level"
*/
levelKey?: string;
/**
* Output the log level using the specified label.
* @default "levelLabel"
*/
levelLabel?: string;
/**
* The key in the JSON object to use as the highlighted message.
* @default "msg"
*/
messageKey?: string;
/**
* Print each log message on a single line (errors will still be multi-line).
* @default false
*/
singleLine?: boolean;
/**
* The key in the JSON object to use for timestamp display.
* @default "time"
*/
timestampKey?: string;
/**
* The minimum log level to include in the output.
* @default "trace"
*/
minimumLevel?: Level;
/**
* Format output of message, e.g. {level} - {pid} will output message: INFO - 1123
* @default false
*
* @example
* ```typescript
* {
* messageFormat: (log, messageKey) => {
* const message = log[messageKey];
* if (log.requestId) return `[${log.requestId}] ${message}`;
* return message;
* }
* }
* ```
*/
messageFormat?: false | string | PinoPretty.MessageFormatFunc;
/**
* If set to true, will add color information to the formatted output message.
* @default false
*/
colorize?: boolean;
/**
* If set to false while `colorize` is `true`, will output JSON objects without color.
* @default true
*/
colorizeObjects?: boolean;
/**
* Appends carriage return and line feed, instead of just a line feed, to the formatted log line.
* @default false
*/
crlf?: boolean;
/**
* Define the log keys that are associated with error like objects.
* @default ["err", "error"]
*/
errorLikeObjectKeys?: string[];
/**
* When formatting an error object, display this list of properties.
* The list should be a comma separated list of properties.
* @default ""
*/
errorProps?: string;
/**
* Ignore one or several keys.
* Will be overridden by the option include if include is presented.
* @example "time,hostname"
*/
ignore?: string;
/**
* Include one or several keys.
* @example "time,level"
*/
include?: string;
/**
* Makes messaging synchronous.
* @default false
*/
sync?: boolean;
/**
* The file, file descriptor, or stream to write to. Defaults to 1 (stdout).
* @default 1
*/
destination?: string | number | DestinationStream | NodeJS.WritableStream;
/**
* Opens the file with the 'a' flag.
* @default true
*/
append?: boolean;
/**
* Ensure directory for destination file exists.
* @default false
*/
mkdir?: boolean;
/**
* Provides the ability to add a custom prettify function for specific log properties.
* `customPrettifiers` is an object, where keys are log properties that will be prettified
* and value is the prettify function itself.
* For example, if a log line contains a query property, you can specify a prettifier for it:
* @default {}
*
* @example
* ```typescript
* {
* customPrettifiers: {
* query: prettifyQuery
* }
* }
* //...
* const prettifyQuery = value => {
* // do some prettify magic
* }
* ```
*/
customPrettifiers?: Record<string, PinoPretty.Prettifier>;
/**
* Change the level names and values to an user custom preset.
*
* Can be a CSV string in 'level_name:level_value' format or an object.
*
* @example ( CSV ) customLevels: 'info:10,some_level:40'
* @example ( Object ) customLevels: { info: 10, some_level: 40 }
*/
customLevels?: string|object;
/**
* Change the level colors to an user custom preset.
*
* Can be a CSV string in 'level_name:color_value' format or an object.
* Also supports 'default' as level_name for fallback color.
*
* @example ( CSV ) customColors: 'info:white,some_level:red'
* @example ( Object ) customColors: { info: 'white', some_level: 'red' }
*/
customColors?: string|object;
}
declare namespace PinoPretty {
type Prettifier = (inputData: string | object) => string;
type MessageFormatFunc = (log: LogDescriptor, messageKey: string, levelLabel: string) => string;
type PrettyOptions = PrettyOptions_;
type PrettyStream = Transform & OnUnknown;
type ColorizerFactory = typeof colorizerFactory;
type PrettyFactory = typeof prettyFactory;
}
export default PinoPretty;
export { PinoPretty, PrettyOptions_ as PrettyOptions, colorizerFactory, prettyFactory };
-170
View File
@@ -1,170 +0,0 @@
'use strict'
const { isColorSupported } = require('colorette')
const pump = require('pump')
const { Transform } = require('readable-stream')
const abstractTransport = require('pino-abstract-transport')
const colors = require('./lib/colors')
const {
ERROR_LIKE_KEYS,
LEVEL_KEY,
LEVEL_LABEL,
MESSAGE_KEY,
TIMESTAMP_KEY
} = require('./lib/constants')
const {
buildSafeSonicBoom,
parseFactoryOptions
} = require('./lib/utils')
const pretty = require('./lib/pretty')
/**
* @typedef {object} PinoPrettyOptions
* @property {boolean} [colorize] Indicates if colors should be used when
* prettifying. The default will be determined by the terminal capabilities at
* run time.
* @property {boolean} [colorizeObjects=true] Apply coloring to rendered objects
* when coloring is enabled.
* @property {boolean} [crlf=false] End lines with `\r\n` instead of `\n`.
* @property {string|null} [customColors=null] A comma separated list of colors
* to use for specific level labels, e.g. `err:red,info:blue`.
* @property {string|null} [customLevels=null] A comma separated list of user
* defined level names and numbers, e.g. `err:99,info:1`.
* @property {CustomPrettifiers} [customPrettifiers={}] A set of prettifier
* functions to apply to keys defined in this object.
* @property {K_ERROR_LIKE_KEYS} [errorLikeObjectKeys] A list of string property
* names to consider as error objects.
* @property {string} [errorProps=''] A comma separated list of properties on
* error objects to include in the output.
* @property {boolean} [hideObject=false] When `true`, data objects will be
* omitted from the output (except for error objects).
* @property {string} [ignore='hostname'] A comma separated list of log keys
* to omit when outputting the prettified log information.
* @property {undefined|string} [include=undefined] A comma separated list of
* log keys to include in the prettified log information. Only the keys in this
* list will be included in the output.
* @property {boolean} [levelFirst=false] When true, the log level will be the
* first field in the prettified output.
* @property {string} [levelKey='level'] The key name in the log data that
* contains the level value for the log.
* @property {string} [levelLabel='levelLabel'] Token name to use in
* `messageFormat` to represent the name of the logged level.
* @property {null|MessageFormatString|MessageFormatFunction} [messageFormat=null]
* When a string, defines how the prettified line should be formatted according
* to defined tokens. When a function, a synchronous function that returns a
* formatted string.
* @property {string} [messageKey='msg'] Defines the key in incoming logs that
* contains the message of the log, if present.
* @property {undefined|string|number} [minimumLevel=undefined] The minimum
* level for logs that should be processed. Any logs below this level will
* be omitted.
* @property {object} [outputStream=process.stdout] The stream to write
* prettified log lines to.
* @property {boolean} [singleLine=false] When `true` any objects, except error
* objects, in the log data will be printed as a single line instead as multiple
* lines.
* @property {string} [timestampKey='time'] Defines the key in incoming logs
* that contains the timestamp of the log, if present.
* @property {boolean|string} [translateTime=true] When true, will translate a
* JavaScript date integer into a human-readable string. If set to a string,
* it must be a format string.
* @property {boolean} [useOnlyCustomProps=true] When true, only custom levels
* and colors will be used if they have been provided.
*/
/**
* The default options that will be used when prettifying log lines.
*
* @type {PinoPrettyOptions}
*/
const defaultOptions = {
colorize: isColorSupported,
colorizeObjects: true,
crlf: false,
customColors: null,
customLevels: null,
customPrettifiers: {},
errorLikeObjectKeys: ERROR_LIKE_KEYS,
errorProps: '',
hideObject: false,
ignore: 'hostname',
include: undefined,
levelFirst: false,
levelKey: LEVEL_KEY,
levelLabel: LEVEL_LABEL,
messageFormat: null,
messageKey: MESSAGE_KEY,
minimumLevel: undefined,
outputStream: process.stdout,
singleLine: false,
timestampKey: TIMESTAMP_KEY,
translateTime: true,
useOnlyCustomProps: true
}
/**
* Processes the supplied options and returns a function that accepts log data
* and produces a prettified log string.
*
* @param {PinoPrettyOptions} options Configuration for the prettifier.
* @returns {LogPrettifierFunc}
*/
function prettyFactory (options) {
const context = parseFactoryOptions(Object.assign({}, defaultOptions, options))
return pretty.bind({ ...context, context })
}
/**
* @typedef {PinoPrettyOptions} BuildStreamOpts
* @property {object|number|string} [destination] A destination stream, file
* descriptor, or target path to a file.
* @property {boolean} [append]
* @property {boolean} [mkdir]
* @property {boolean} [sync=false]
*/
/**
* Constructs a {@link LogPrettifierFunc} and a stream to which the produced
* prettified log data will be written.
*
* @param {BuildStreamOpts} opts
* @returns {Transform | (Transform & OnUnknown)}
*/
function build (opts = {}) {
const pretty = prettyFactory(opts)
return abstractTransport(function (source) {
const stream = new Transform({
objectMode: true,
autoDestroy: true,
transform (chunk, enc, cb) {
const line = pretty(chunk)
cb(null, line)
}
})
let destination
if (typeof opts.destination === 'object' && typeof opts.destination.write === 'function') {
destination = opts.destination
} else {
destination = buildSafeSonicBoom({
dest: opts.destination || 1,
append: opts.append,
mkdir: opts.mkdir,
sync: opts.sync // by default sonic will be async
})
}
source.on('unknown', function (line) {
destination.write(line + '\n')
})
pump(source, stream, destination)
return stream
}, { parse: 'lines' })
}
module.exports = build
module.exports.prettyFactory = prettyFactory
module.exports.colorizerFactory = colors
module.exports.default = build
-67
View File
@@ -1,67 +0,0 @@
{
"name": "pino-pretty",
"version": "10.2.3",
"description": "Prettifier for Pino log lines",
"type": "commonjs",
"main": "index.js",
"types": "index.d.ts",
"bin": {
"pino-pretty": "./bin.js"
},
"scripts": {
"ci": "standard && tap --coverage-report=lcovonly && npm run test-types",
"lint": "standard | snazzy",
"test": "tap",
"test-types": "tsc && tsd",
"test:watch": "tap --no-coverage-report -w",
"test:report": "tap --coverage-report=html"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/pinojs/pino-pretty.git"
},
"keywords": [
"pino"
],
"author": "James Sumners <james.sumners@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/pinojs/pino-pretty/issues"
},
"homepage": "https://github.com/pinojs/pino-pretty#readme",
"precommit": [
"lint",
"test"
],
"dependencies": {
"colorette": "^2.0.7",
"dateformat": "^4.6.3",
"fast-copy": "^3.0.0",
"fast-safe-stringify": "^2.1.1",
"help-me": "^4.0.1",
"joycon": "^3.1.1",
"minimist": "^1.2.6",
"on-exit-leak-free": "^2.1.0",
"pino-abstract-transport": "^1.0.0",
"pump": "^3.0.0",
"readable-stream": "^4.0.0",
"secure-json-parse": "^2.4.0",
"sonic-boom": "^3.0.0",
"strip-json-comments": "^3.1.1"
},
"devDependencies": {
"@types/node": "^20.1.0",
"fastbench": "^1.0.1",
"pino": "^8.0.0",
"pre-commit": "^1.2.2",
"rimraf": "^3.0.2",
"snazzy": "^9.0.0",
"standard": "^17.0.0",
"tap": "^16.0.0",
"tsd": "^0.29.0",
"typescript": "^5.0.2"
},
"tsd": {
"directory": "./test/types"
}
}
-13
View File
@@ -1,13 +0,0 @@
{
"compilerOptions": {
"target": "es6",
"lib": [ "es2015" ],
"module": "commonjs",
"noEmit": true,
"strict": true
},
"include": [
"./test/types/pino-pretty.test.d.ts",
"./index.d.ts"
]
}