Giter VIP home page Giter VIP logo

tslog's People

Contributors

ariesclark avatar barakd avatar beanaroo avatar coinwalletdev avatar dependabot[bot] avatar ejose19 avatar jonahsnider avatar kevintechie avatar kwonoj avatar lorefnon avatar markayers avatar mueckema avatar nini avatar nyrox avatar olafbuitelaar avatar quinnturner avatar sachaw avatar terehov avatar thomaschampagne avatar tomkeyte avatar withmask avatar zhen-dot avatar

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

tslog's Issues

Bug: `Cannot read property 'isError' of null`

Describe the bug

tslog version: 3.1.0

Unfortunately I don't know how to reproduce this but I periodically get an error thrown by tslog of Cannot read property 'isError' of null while attempting to log a message with a JS object. I see this usually in production. Although I think I've also seen it in local dev.

Expected behavior

Should not error

Additional context

import { Logger } from "tslog"

export const logger = new Logger({
  type: clientEnv.isProduction ? "json" : "pretty",
  dateTimePattern: "hour:minute:second.millisecond",
  displayFunctionName: false,
  displayFilePath: "hidden",
  dateTimeTimezone: clientEnv.isProduction
    ? "utc"
    : Intl.DateTimeFormat().resolvedOptions().timeZone,
  prettyInspectHighlightStyles: { name: "yellow", number: "blue", bigint: "blue", boolean: "blue" },
  maskValuesOfKeys: ["password", "passwordConfirmation"],
  exposeErrorCodeFrame: !clientEnv.isProduction,
})


// And then I'm also using a child logger
const log = logger.getChildLogger({ prefix: ["submitGroupStep1()"] })

Node.js Version
12

Bug: maskValuesOfKeys option mutates object properties!

To Reproduce

import { Logger } from "tslog";

const logger = new Logger();

const password = "123";
const someObj = {
    password: "123"
};

logger.info(someObj);
logger.info(password);

console.log(password === "123"); // true
console.log(someObj.password === "123"); // false

Additional context
v2.11.1

Node.js Version
v14.15.1

Feature Request: [Feature] tree-shakable dist output support

Description / Use Case for a Feature

This is feature request to support module field in package.json allows bundler can pick up tree-shakable code. Whole size of tslog itself is relatively small enough, but I hope tslog could expose import paths to skip few deps like source-map as well to squeeze size: it may possible by having export site in top level export (index.ts), but should be esm syntax to allow tree shaking.

Below's size composition for tslog which source-map takes more than half.
image

I do not have a strong opinion if it should be true esm or cjs output with esm syntax only - but given native esm support is not wide enough yet, native esm could wait longer.

Happy to try PR if you don't mind.

tslog should not modify the Error prototype

https://github.com/watson/error-callsites/blob/1d6e6cc416b56d535c608ed77980867bb7b345c9/index.js#L8-L21

Object.defineProperty(Error, "prepareStackTrace", {
configurable: true,
enumerable: true,
get: function () {
return prepareStackTrace;
},
set: function (fn?: (err: Error, stackTraces: NodeJS.CallSite[]) => string) {
// Don't set `lastPrepareStackTrace` to ourselves. If we did, we'd end up
// throwing a RangeError (Maximum call stack size exceeded).
lastPrepareStackTrace =
fn === prepareStackTrace
? fallback
: (fn as (err: Error, stackTraces: NodeJS.CallSite[]) => string);
},
});

tslog should not modify the global Error prototype. If modifying the prototype is necessary for certain features it should be explicitly enabled with an option.

This can cause issues in otherwise working code. For example, in a working API server, introducing tslog caused error handling code to crash the app instead of responding to an HTTP request.

Bug: Arrays and Dates stopped displaying correctly

Describe the bug

After upgrading from 2.9.1 to 3.0.5, there is a regression in array and date logging.

Before:

2021-01-07 22:21:30.784.000	 DEBUG 	[test.js:5]
{
  createdAt: 2021-01-07T22:21:30.782Z,
  students: [
    {
      id: 1
    },
    {
      id: 2
    }
  ]
}

After:

Notice how Date is now Date {} instead of a string and that array has object syntax.

2021-01-07 22:20:31.495  DEBUG [test.js:5 Object.<anonymous>]
{
  createdAt: Date {},
  students: Array {
    '0': {
      id: 1
    },
    '1': {
      id: 2
    },
    length: 2
  }
}

Also, sometimes I'm seeing [Circular] in place of a Date, but not sure how to reproduce that.

To Reproduce

Run this with 2.9.1 and 3.0.5

var tslog = require("tslog")

const log = new tslog.Logger()

log.debug({
  createdAt: new Date(),
  students: [{ id: 1 }, { id: 2 }],
})

Expected behavior

Same as 2.9.1

Env

System:
OS: macOS 11.1
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Memory: 1.44 GB / 64.00 GB
Shell: 3.1.2 - /usr/local/bin/fish

Bug: Doesn't mask password keys when type is `json`

Describe the bug
It doesn't mask password when type is json

To Reproduce
tslog is v2.10.0

When type is pretty, it masks password key

const log = new Logger()
log.info({ name: 'name1', password: 'secretPassword' })

output:

0|worker  | 2020-11-03 15:42:45.388.000
0|worker  |  INFO
0|worker  | [src/util.js:25]
0|worker  |
0|worker  | {
0|worker  |   name: 'name1',
0|worker  |   password: '[***]'
0|worker  | }

It works as expected and the password was masked.

But when type is json

const log = new Logger({type: 'json'})
log.info({ name: 'name1', password: 'secretPassword' })

Output:

0|worker  | {"instanceName":"localhost","hostname":"localhost","date":"2020-11-03T15:50:11.733Z","logLevel":"info","logLevelId":3,"filePath":"src/util.js","fullFilePath":"/src/util.js","fileName":"util.js","lineNumber":25,"columnNumber":5,"isConstructor":false,"functionName":null,"typeName":"Object","methodName":null,"argumentsArray":["{ name: 'name1', password: 'secretPassword' }"]}

Password value wasn't masked in this case

Expected behavior
Password value should be masked for type json

Node.js Version
v10.23.0

Question: Rename Silly to Step via Config?

Is it possible via configuration to rename the "silly" level to "step"?

I'm designing an automation framework that will be using your logging library (great work btw!). I'd like to use the silly level as a way to report manual testing steps. So it would be ideal if the logs reported "step" instead of "silly".

Feature Request: Simpler transport

Description / Use Case for a Feature

Because the severity of a log is included with the logObject, there should be a simpler transport implementation option similar to the IStd interface for prettyprint.

export interface TSimpleTransport {
  log: (logObject: ILogObject) => void
}

And this type added as an overload to attachTransport

This would allow a transport logger to take out all the per-severity boilerplate and still support minLevel (because the logger simply wouldn't call the transport unless minlevel is reached). It would also remain backwards compatible if new severity types are added to the interface (which would otherwise be breaking for transports with the current implementation)

Simple implementation:

class ConsoleLogTransport implements TSimpleTransport {
  //Special processing for severity differences can go here
  log: (logObject: ILogObject) => {
    console.log(logObject.argumentsArray.ToString())
  }
}

An example existing transport implementation that could have about 10 lines cut out of it if this is implemented:

class DebugConsoleOutput implements IStd {
    write(message: string) {console.log(message)}
}

/**
 * Writes TSLog Pretty Print messages to the vscode debug console. It requires the logger during construction to import
 * its pretty print preferences
 *
 * @class DebugConsoleTransport
 * @implements {TTransportLogger<(ILogObject) => void>}
 */
class DebugConsoleTransport implements TTransportLogger<(logObject: ILogObject) => void> {
    private readonly debugConsoleOutput = new DebugConsoleOutput()
    constructor(
        private readonly logger: Logger
    ){}
    log(logObject: ILogObject): void {
        this.logger.printPrettyLog(this.debugConsoleOutput, logObject)
    }
    silly = this.log
    debug = this.log
    trace = this.log
    info = this.log
    warn = this.log
    error = this.log
    fatal = this.log
}

Bug: TypeError: Cannot read property '0' of undefined

Describe the bug
2020-06-04 15:13:57.858 INFO [test.ts:5] TypeError: Cannot read property '0' of undefined
at stylizeWithColor (internal/util/inspect.js:340:27)
at formatPrimitive (internal/util/inspect.js:1120:12)
at formatValue (internal/util/inspect.js:533:12)
at formatProperty (internal/util/inspect.js:1406:11)
at formatRaw (internal/util/inspect.js:785:9)
at formatValue (internal/util/inspect.js:591:10)
at Object.inspect (internal/util/inspect.js:221:10)
at ../node_modules/tslog/src/index.ts:435:26
at Array.forEach ()
at Logger._printPrettyLog (../node_modules/tslog/src/index.ts:430:30)

To Reproduce

import { Logger } from "tslog";

const logger = new Logger();

logger.info({ foo: "bar" });

Expected behavior
Log object

Context
Node v12.14.0
ts-node v8.10.2
tslog v2.1.0

Feature Request: Allow custom delimiters

Description / Use Case for a Feature
The use case is for formatting the logs with more customization.

Right now my logs look like:
image

I would like to be able to not have all the spaces between the meta information but still have the colored output with log levels and time. Is that possible or would it be a feature request?

Bug: stack trace error

Describe the bug
After updating to 2.6.1 I got error in bluebird

/node_modules/bluebird/js/release/debuggability.js:768 var lastStackLines = (lastLineError.stack || "").split("\n");

seems like tslog converts error.stack into array

To Reproduce

const { Logger } = require("tslog");
const promise = require("bluebird");

const logger = new Logger();

async function run() {
    try {
        await promise.any([Promise.resolve()]);
    } catch (err) {
        logger.error(err);
    }
}
run();

Additional context
Node.JS 12.18.0
tslog ^2.6.1

Seems related #33

Bug: About maskStrings parameter

Describe the bug
When maskStrings parameter is used tslog is masking the keys as well and also adding an extra colon. Also the maskStrings works case sensitive unlike maskValuesOfKeys. See the screenshot below.

To Reproduce
Steps to reproduce the behavior:

  1. mkdir tslogBugMaskStrings
  2. cd tslogBugMaskStrings
  3. npm init -y
  4. npm i tslog
  5. Create a js file called index.js, touch index.js perhaps
  6. run the following code:
const { Logger } = require('tslog');
let log = new Logger({
  maskStrings: ['password'],
  maskValuesOfKeys: ['password', 'password_hash']
});

log.info({ 
  password: 'password',
  password_hash: 'hush-hush-hush',
  paSSword_column: "pass Pass password."
});

Expected behavior
There should be one colon after the key and if it is not intended, keys should not be masked.

Screenshots

Additional context
I added this as a separate issue to keep things cleaner with issue #37

Feature Request: Defaults / Formatter

Description / Use Case for a Feature

I'd really like to see a way to handle defaults with tslog. I appreciate requestId, hostname etc. but I also need to add a few more parameters as I intend to use your logger with Google's Stackdriver, which needs some additional values e.g. for labels, a service context and so on.

I can imagine that there are more use cases for custom defaults that will always be logged. Right now I'm using a transport where I attach that information. But this leads to the output deviating from what is actually being logged by tslog when not using the transport.

Maybe introducing formatters like other logging libraries do could also solve that problem by letting us mutate the arguments before they are sent to either the default transport or a custom one.

Attached transports do not respect individual minLevel

Describe the bug
When transport's minLevel is different from stdoutput, the log is not generated on transports with minLevel less than stdoutput.

To Reproduce
Steps to reproduce the behavior:

  1. Run the following code:
import { ILogObject, Logger } from 'tslog';
import { appendFileSync }  from 'fs';

function logToTransport(logObject: ILogObject) {
  appendFileSync('logs.txt', JSON.stringify(logObject) + '\n');
}

const logger: Logger = new Logger({ minLevel: 'info' });
logger.attachTransport(
  {
    silly: logToTransport,
    debug: logToTransport,
    trace: logToTransport,
    info: logToTransport,
    warn: logToTransport,
    error: logToTransport,
    fatal: logToTransport,
  },
  'debug'
);

logger.info("I am an info log.");
logger.warn("I am a warn log with a json object:", { foo: "bar" });
logger.debug("I am a debug log.");
  1. The "info" log is generated on the stdoutput and attached transport.
  2. The "warn" log is generated on the stdoutput and attached transport.
  3. The "debug" log is not generated on the attached transport.

Expected behavior
The "debug" log should be generated in the attached transport with minLevel is debug.

Additional context
To resolve, I believe that is need to change the code highlighted in the image below from this.settings.minLevel to transport.minLevel.

File: tslog/src/index.ts

tempsnip

Bug: Logging rror causes "Converting circular structure to JSON"

Describe the bug
When I pass an error object which has a circular structure to logger.info or any other logging method, I get the following error:

TypeError: Converting circular structure to JSON

To Reproduce
Execute the following code:

import { Logger } from 'tslog';

const logger = new Logger();

const request = { url: 'http://example.com/does-not-exist', originalRequest: {} };
request.originalRequest = request;

const error = new Error('Failed to fetch the resource');
error.request = request;

logger.warn('The request failed', error);

To see this happening in a more realistic context, install got and run the following code:

import { Logger } from 'tslog';
import got from 'got';

const logger = new Logger();

async function getResponse() {
  try {
    const response = await got.get('http://example.com/does-not-exist');
    return response;
  } catch (error) {
    logger.warn('Failed to fetch the data', error);  
  }
};

getResponse();

Expected behavior
tslog stringifies the error object in such a way that it does not throw an error.

Screenshots
Output from the 2nd example above:

(node:15937) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Socket'
    |     property '_httpMessage' -> object with constructor 'ClientRequest'
    --- property 'socket' closes the circle
    at JSON.stringify (<anonymous>)
    at Logger._buildErrorObject (/tmp/tmp.5tNebHIiKR/node_modules/tslog/src/index.ts:466:55)
    at /tmp/tmp.5tNebHIiKR/node_modules/tslog/src/index.ts:432:16
    at Array.forEach (<anonymous>)
    at Logger._buildLogObject (/tmp/tmp.5tNebHIiKR/node_modules/tslog/src/index.ts:429:28)
    at Logger._handleLog (/tmp/tmp.5tNebHIiKR/node_modules/tslog/src/index.ts:353:40)
    at Logger.warn (/tmp/tmp.5tNebHIiKR/node_modules/tslog/src/index.ts:298:28)
    at getResponse (/tmp/tmp.5tNebHIiKR/bug.ts:11:12)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Additional context
N/a

Node.js Version
v12.18.2

OS incl. Version
Linux Mint 19.1

Europe/Paris timezone bug

Hello, there is a slight problem with the display of the time for the Europe/Paris timezone, instead of 00h00 it changes to 24h00
Sans titre

Bug: Logging URL objects fails

Describe the bug
TSlog version: 3.1.1

Similar to #86.
When logging a URL object, an error occurs.

root@88f15f987cd8:/srv# yarn ts-node src/tslogdebug.ts
yarn run v1.22.5
$ /srv/node_modules/.bin/ts-node src/tslogdebug.ts
2021-03-09 18:30:36.039  INFO [src/tslogdebug.ts:5 Object.<anonymous>] TypeError: Cannot convert undefined or null to object
    at getPrototypeOf (<anonymous>)
    at URL.[nodejs.util.inspect.custom] (internal/url.js:357:9)
    at internal/per_context/primordials.js:23:32
    at formatValue (internal/util/inspect.js:783:19)
    at Object.inspect (internal/util/inspect.js:337:10)
    at Logger._inspectAndHideSensitive (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:897:26)
    at /srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:664:18
    at Array.forEach (<anonymous>)
    at Logger.printPrettyLog (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:632:30)
    at Logger._handleLog (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:348:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

To Reproduce
Steps to reproduce the behavior:
Run the code below.

import { Logger } from "tslog";

const logger = new Logger();
const url = new URL("http://example.com");
logger.info(url);

Additional context
Add any other context about the problem here.

Node.js Version
v14.16.0 (node:14.16.0-buster docker image)

OS incl. Version
Debian (buster) docker image on Debian (buster) host.

Bug: Passing Buffer object causes an error

Describe the bug

Version: 3.1.0

When a Buffer object is passed to logging methods, an error occurs.

To Reproduce

Run the code below:

import { Logger } from 'tslog'
const logger = new Logger()
const buffer = Buffer.from('foo')
logger.info(buffer)

Then, an error as below is thrown.

/srv # yarn ts-node reproduce-error.ts
yarn run v1.22.5
$ /srv/node_modules/.bin/ts-node reproduce-error.ts
2021-02-01 06:28:15.593  INFO [reproduce-error.ts:4 Object.<anonymous>] TypeError: Method get TypedArray.prototype.length called on incompatible receiver [object Object]
    at Buffer.get length [as length] (<anonymous>)
    at Buffer.inspect (buffer.js:826:39)
    at internal/per_context/primordials.js:23:32
    at formatValue (internal/util/inspect.js:764:19)
    at Object.inspect (internal/util/inspect.js:326:10)
    at Logger._inspectAndHideSensitive (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:885:26)
    at /srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:652:18
    at Array.forEach (<anonymous>)
    at Logger.printPrettyLog (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:632:30)
    at Logger._handleLog (/srv/node_modules/tslog/src/LoggerWithoutCallSite.ts:348:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Expected behavior

I think a log similar to the output from console.log should be printed as below.

<Buffer 66 6f 6f>

Node.js Version
v14.13.1

OS incl. Version
Alpine Linux (node:14-alpine docker image)

json loging api: [Feature]

when log output is json add option to to log json object
for example
logger.info({userId: 123})

expected output:
{
//...
userId: 123
}

current output:
{
//...
argumentsArray:[{userId: 123}]

Not a bug: Color pallet

It's not a bug but some recommendations are needed. I'm using iTerm + Oh-My-Zsh with Powerlevel10k and can't get those nice colors you have in the screenshot any how.

Can you recommend what was used to get shiny and beautiful looking logs?

Here is what i see:
image

Bug: Method names for async functions not showing

Describe the bug
When a log is written from an async function it does not have a method name associated with it in the output. This might be an issue with how async/await works - or how I implement so not sure this is a tslog issue or not?

2020-11-18 02:31:14.309.000      INFO   [src\main.ts:5 testSync]                testSync - Yep    
2020-11-18 02:31:14.338.000      INFO   [src\main.ts:8]                 testAsync - Nope

To Reproduce

import { Logger } from 'tslog';
const logger = new Logger();

const testSync = () => {
  logger.info('testSync - Yep');
};
const testAsync = async () => {
  logger.info('testAsync - Nope');
};

(async () => {
  testSync();
  await testAsync();
})();

Expected behavior
I would expect the output to show [src\main.ts:8 testAsync] not just [src\main.ts:8].

Screenshots
image

Additional context
Add any other context about the problem here.

Node.js Version
v15.2.1

OS incl. Version
Windows 10

Bug: [BUG] Unhandled exception in `_maskValuesOfKeys`

Describe the bug
A clear and concise description of what the bug is.

With latest release, there are some unhandled exception being thrown like below:

exceptionStack: 'TypeError: Cannot set property devToolsWebContents of #<BrowserWindow> which has only a getter\n' +
    '    at C:\\github\\apps\\dist\\main.bundle.js:147454:30\n' +
    '    at Array.forEach (<anonymous>)\n' +
    '    at Function.traverseObjectRecursively (C:\\github\\apps\\dist\\main.bundle.js:147445:26)\n' +
    '    at Function.logObjectMaskValuesOfKeys (C:\\github\\apps\\dist\\main.bundle.js:147467:29)\n' +
    '    at Logger._maskValuesOfKeys (C:\\github\\apps\\dist\\main.bundle.js:148020:44)\n' +
    '    at Logger._inspectAndHideSensitive (C:\\github\\apps\\dist\\main.bundle.js:148013:35)\n' +
    '    at C:\\github\\apps\\dist\\main.bundle.js:147911:26\n' +
    '    at Array.forEach (<anonymous>)\n' +
    '    at Logger.printPrettyLog (C:\\github\\apps\\dist\\main.bundle.js:147899:34)\n' +
    '    at Object.writer (C:\\github\\apps\\dist\\main.bundle.js:161187:21)',

looks like introduced with a80f4a4. Assuming traverse tries to mutate given object payload somehow.

To Reproduce
Steps to reproduce the behavior:

clone https://github.com/kwonoj/tslog-getter-exception, npm ci && npm start

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context

Though this repro is written in electron, I suspect this could happen in plain node.js usecases. Electron's picked up as it was quickest way to find object have setter restriction while I work with.

Node.js Version

OS incl. Version

Error when trying to access relevant call sites

I am currently trying to integrate tslog in a nextjs api function. I stumbled upon an error where relevantCallSites turned out to be an array of 3 elements. Since the default for ignoreStackLevels seems to be 3, it makes sense that undefined cannot be evaluated.

I haven't yet tracked down why my callsites only have a length of 3 but in any case, it'd be better to check if relevantCallSites.length > 0 and not pass it down in case there is no CallSite left.

const stackFrame: NodeJS.CallSite = this._callSiteWrapper(
relevantCallSites[0]
);

Bug: Logs are blank in Sentry breadcrumbs

Describe the bug

Here's what tslog looks like in Sentry breadcrumbs with pretty logging:

image

This is captured to sentry in Node like this:

  } catch (error) {
    Sentry.captureException(error)
    throw error
  }

Not sure what the core issue is 🤷

Expected behavior
Pretty logs would show up correctly

Feature Request: [Feature] [Question] masking dynamic values, such as regex pattern matching

Description / Use Case for a Feature

I may misunderstand docs and this is already supported, labeled question to clarify it.

There are some cases we would like to traverse all object payload recursively to detect a certain patterns of strings matching regex, such as prefix-based auth token and vice versa. Is there way to specify it via current mask* configuration values?

Feature Request: Isomorphic logging (browser support)

Description / Use Case for a Feature

As I've said before, I'm really loving tslog in Blitz apps! But there's one thing I really wish tslog supported, and that is logging in the browser.

Currently I have to be constantly making a cognitive choice between using tslog or console.log based on if I'm in a server or browser context. And this is often since Blitz is a fullstack monolith.

Possible implementation

Provide a separate browser bundle (via package.json browser field) that has a minimal logger without any node.js dependencies. Should be a small as possible for bundle size concerns. Ideally it would accept all the same options, but some of the options would be no-op in the browser.

Bug: Instantiating logger breaks console.error()

Describe the bug
We are using tslog inside Blitz.js. It's really great, but noticed that it's causing a regression because it breaks the default behavior of console.error.

Before instantiating a tslog logger, console.error(new Error("Hello")) prints the following:

Error: Hello
    at Test (webpack-internal:///./pages/ssr.tsx:92:17)
    ...redacted

But after instantiating a logger, console.error(new Error("Hello")) prints this:

[Error: Hello]

As you can see, this is very bad because you can't tell where the error is from.

In this case, third-party code is using console.error, so it's not something we can change.

To Reproduce
Steps to reproduce the behavior:

  1. Run console.error(new Error("Hello"))
  2. See error with stack trace
  3. Instantiate logger: new Logger()
  4. Run console.error(new Error("Hello"))
  5. See there is no stack trace.

Node.js Version
Node v12

OS incl. Version

  System:
    OS: macOS 10.15.7
    CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
    Memory: 5.43 GB / 64.00 GB
    Shell: 3.1.2 - /usr/local/bin/fish

How to disable short path in log message?

Thanks for such an awesome library! I've been using it in next.js project, but unfortunately, I was not able to get helpful "short paths" due to the way how next.js works

Can I disable them? I looked at the available settings, but haven't found one.

Thanks!

image

GraphQL JSON Parse error: Unrecognized token '<' error when using TSLog library

Hello,

I am currently running into an issue where upon adding a log using this library, my graphql query errors stop working and return the following error: JSON Parse error: Unrecognized token '<'. This only affects when i am expecting graphql to return an error, i am able to get data when i am expecting data. I am using apollo-server and graphql with this library.
I added the following parameters:
export const logger = new Logger({ minLevel: "debug", displayDateTime: true, dateTimeTimezone: "America/New_York", name: "console", overwriteConsole: true });

If more information is required please let me know. Thank you for your help!

Bug: TypeError: errorCallSites.splice is not a function

Describe the bug
Got TypeError: errorCallSites.splice is not a function while trying to log uncaughtException.

To Reproduce

import { Logger } from "tslog";

const logger = new Logger();

function logError(err: any) {
    console.error(err);  // GOOD -> TypeError: Cannot read property 'id' of undefined
    logger.error(err); // !ERROR HERE -> TypeError: errorCallSites.splice is not a function
}

process.on("uncaughtException", logError);

let obj: any;
const id = obj.id; // generating uncaught exception

Expected behavior
Log error TypeError: Cannot read property 'id' of undefined

Additional context
Node.JS 12.18.0
typescript ^3.9.6
tslog ^2.6.0

[Question]: disable all colors in `prettyPrintLog`

Description / Use Case for a Feature

If I read correctly, it looks like few cases colors are always applied, such as dateTime or logLevels:

I'm curious if there's way to disable all colors entirely when using prettyPrintLog.

Context: I'm trying to write pretty printed output into files, looks like

function transport(logObject): {
  logger.prettyPrintLog(fileWriteStream, logObject)
}

and it always ends up printing out color code in log output like

�[90m10/28/2020, 22:54:32:930.000	�[39m�[1m�[0m INFO �[0m�[22m	

Having colors in stdout is still preferred - hope if there's way to have strings without color only for certain cases. Originally I thought creating child logger turns off all colors would allow to use prettyPrintLog without colors, but seems like there's no such option unless I miss something.

tslog shouldn't modify global util.inspect styles by default

Describe the bug
Currently, tslog overwrites util.inspect styles by its own:

prettyInspectHighlightStyles: {
special: "cyan",
number: "green",
bigint: "green",
boolean: "yellow",
undefined: "red",
null: "red",
string: "red",
symbol: "green",
date: "magenta",
name: "white",
regexp: "red",
module: "underline",

tslog/src/LoggerHelper.ts

Lines 136 to 144 in 2760b41

public static setUtilsInspectStyles(
utilsInspectStyles: IHighlightStyles
): void {
Object.entries(utilsInspectStyles).forEach(
([symbol, color]: [string, TUtilsInspectColors]) => {
inspect.styles[symbol] = color;
}
);
}

which will affect other consumers of util.inspect, this shouldn't be enabled by default and instead by provided as an export (ie: CustomHighlightStyles that must be explicitly be used as:

import { Logger, CustomHighlightStyles } from "tslog";

const log = new Logger({ prettyInspectHighlightStyles: CustomHighlightStyles });

To Reproduce
Steps to reproduce the behavior:

  1. Create a logger with default options
  2. Use console.log(inspect({ foo: "bar" }, { colors: true }))
  3. Notice how the colors changed implicitly

Expected behavior
Global shouldn't be modified implicitly

Screenshots
N/A

Additional context
I'm aware util.inspect doesn't provide a way to create a custom inspect function (ie: new Inspect()), so in case this library needs to modify global inspect at least it should be explicitly (and with a docs warning).

Node.js Version
16.3.0

OS incl. Version
Archlinux

Bug: Cannot convert undefined or null to object

Describe the bug

These both fail as of 3.0.3. They worked fine in 2.9.1

To Reproduce

logger.info("A", null)
logger.info("B", undefined)

Expected behavior
Logger should accept all values, especially null and undefined.

Node.js Version
12

OS incl. Version
System:
OS: macOS 11.1
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Memory: 1.43 GB / 64.00 GB
Shell: 3.1.2 - /usr/local/bin/fish

Bug: Error thrown of setting a property name that only has a getter

Describe the bug
In some applications, ts-log will report the error (this is with ts-node, same errors produces in normal JavaScript!):

 TypeError  Cannot set property name of  which has only a getter
error stack:
 LoggerWithoutCallSite.ts:463 _buildErrorObject
    node_modules\tslog\src\LoggerWithoutCallSite.ts:463:21

 LoggerWithoutCallSite.ts:424 <anonymous>
    node_modules\tslog\src\LoggerWithoutCallSite.ts:424:16

 LoggerWithoutCallSite.ts:421 _buildLogObject
    node_modules\tslog\src\LoggerWithoutCallSite.ts:421:28

 LoggerWithoutCallSite.ts:332 _handleLog
    node_modules\tslog\src\LoggerWithoutCallSite.ts:332:40

 LoggerWithoutCallSite.ts:289 fatal
    node_modules\tslog\src\LoggerWithoutCallSite.ts:289:28

 main.ts:54 <anonymous>
    main.ts:54:60node:events:327 emit
    node:events:327:20node:domain:486 EventEmitter.emit
    node:domain:486:12

 source-map-support.js:495 process.emit
    C:\Users\<name>\AppData\Roaming\npm\node_modules\ts-node\node_modules\source-map-support\source-map-support.js:495:21

To Reproduce
This happens when you do:

const { Logger } = require('tslog');
const logger = new Logger();

class CustomError extends Error {
  get name() {
    return 'CustomError';
  }
}

try {
  throw new CustomError();
} catch(ex) {
  logger.fatal(ex);
  // logger.error(ex); also causes it!
}

Expected behavior
Shouldn't override setters (it seems?) and the error should be printed.

Node.js Version
v15.0.1

OS incl. Version
Windows 10 Pro (build 2004, 10.0.19041)

Feature Request: React-Native

I try to use your library in my react-native project.

After yarn add tslog and use it in project, I have an errors like:

Unable to resolve module `os` from `node_modules/tslog/dist/index.js`

I suppose, that this os module is node based dependency. In react-native we can not access to node features. Can you adapt your library to use it specific environment, like react native?

Bug: Can not run debug a script with tslog in vscode

Describe the bug

I'm not sure this is a issue in this lib or if the issue is with vscode debugger. But when I debug a script with tslog in vscode I get the following error:

Process exited with code 1
Uncaught Error: write EPIPE
Emitted 'error' event at: <node_internals>/internal/errors.js:463

To Reproduce

Steps to reproduce the behavior:

  1. Create a new project
$ mkdir tslog-test
$ cd tslog-test
$ npm init -y
$ npm install tslog
  1. Create a new javascript file and name it test.js:
const { Logger } = require('tslog');

const logger = new Logger();

logger.error('Hello');
console.log('The end');
  1. Create a launch.json file by following the GUI guide or create a new file and place it in .vscode/launch.json:
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/test.js"
    }
  ]
}
  1. Open the debug panel in vscode och click on "Launch Program" and see the error in "DEBUG CONSOLE".

However, if I execute the script without a debugger it works fine:

$ node test.js
2020-09-16 10:46:16.834	 ERROR 	[test.js:5]  	  	Hello
The end

And it works also fine with nodes builtin debugger:

$ node inspect test.js
< Debugger listening on ws://127.0.0.1:9229/df1e3c02-dc43-40af-83f5-0cd1bc9c534f
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in test.js:1
> 1 const { Logger } = require('tslog');
  2
  3 const logger = new Logger();
debug> c
< 2020-09-16 10:47:29.536
<  ERROR
< [test.js:5]
< Hello
< The end
< Waiting for the debugger to disconnect...
debug>

Expected behavior
I expected to be able to use VScodes debugger with tslog.

Node.js Version
e.g. 12.8.0

OS incl. Version
macOS 10.15.6

Bug: TypeError: Cannot read property 'isNative' of undefined

Describe the bug
I get an error: [TypeError: Cannot read property 'isNative' of undefined] when using the library

To Reproduce

In electron environment:
console.log('quicktest')
try {
const log: Logger = new Logger()
log.silly('I am a silly log.')
} catch (e) {
console.log(e)
}
console.log('quicktest')

get output:

quicktest
[TypeError: Cannot read property 'isNative' of undefined]
quicktest

Expected behavior
Not getting an error

Additional context
I am using electron, and running this in the main process

exception when loging errorr: [BUG]

Describe the bug
when trying to log error object an exception is thrown

To Reproduce
Steps to reproduce the behavior:
write in the code the following code:
logger.error(new Error())

Expected behavior
should work

Additional context
TypeError: stack.reduce is not a function
at Function.getCallSites (/my-app/node_modules/tslog/src/LoggerHelper.ts:57:15)
at Logger._buildErrorObject (/my-app/node_modules/tslog/src/index.ts:451:60)
at /my-app/node_modules/tslog/src/index.ts:428:16
at Array.forEach ()
at Logger._buildLogObject (/my-app/node_modules/tslog/src/index.ts:425:28)
at Logger._handleLog (/my-app/node_modules/tslog/src/index.ts:351:40)
at Logger.error (/my-app/node_modules/tslog/src/index.ts:304:28)

this happend because error.stack is string and not array

const stack: NodeJS.CallSite[] =
error == null
? ((new Error().stack as unknown) as NodeJS.CallSite[]).slice(1)
: ((error.stack as unknown) as NodeJS.CallSite[]);

How does this compare to pino, winston and co?

Hi there,

I came across tslog in search of a good logging library and it looks promising!
I'm currently mostly using pino but having some issues with it's API and other things.

I was wondering if you could give a quick summary on how this logging library compares to X, what you did differently, why and what's the overall philosophy of it?
I'm sort of tasked with defining some best practices wrt to logging and observability at my company.

When I say X, I mostly mean:

  • pino
  • winston
    i.e. the 2 most popular libs

Some features that I'm looking for usually:

  • json logging support (must have - I see tslog has it)
  • support for child loggers
  • support to change the log level globally at runtime (winston has that, pino doesn't)

Appreciate your thoughts!

Bug: Masking the password only if it is not the last key-value pair.

Describe the bug
TSLog masks password only if it is not the last value in the json.

To Reproduce
Steps to reproduce the behavior:

  1. mkdir tslogBugReplace
  2. cd tslogBugReplace
  3. npm init -y
  4. npm i tslog
  5. Open directory with your favourite text editor and create index.js
  6. Run the following code:
const { Logger } = require('tslog');
let log = new Logger();

log.info({ password: 'topsecret', user: 'test'});
// password is masked.

log.info({ user: 'test', password: 'topsecret' });
// password is not masked!

log.info({ user: 'test', password: 'topsecret', iWillMask: 'Because I exist' });
// Whew! It's masked again.
// Hint: util.inspect() does not add a comma after the last key in json.

// In the following example:
// Keys do not include password. 
// Only values have the keyword 'password' (case insensitive).
log.info({ 
  errorCode: 'WrongPasswordOrEmail', 
  message: 'Email or Password is wrong! Password, password, password!',
  anyKey: 'any value' // removing this key will result in unmasked message.
});
  1. node index.js or you can also see the screenshot below.

Expected behavior
Password should be masked regardless of the comma at the end when it was serialized for replacement with the mask string.

Screenshots

Additional context
I have seen the code for replacing the value of the key is using inspect from util library. A simple regex matching for every key-value pair is a bit hard to write. I am currently working on a depth first search approach, where each property is visited and modified then copied to a clone until a cycle is encountered. Finally I would call util.inpect() on the clone as well, and modify the result for pretty printing.

[Question] displayFilePath/displayFunctionName in a "facade" class

Hello, I have a class LoggerService:

import { Logger } from 'tslog'

class LoggerService {
  private logger: Logger

  construtor() {
    this.logger = new Logger()
  }

  error(...args) {
    this.logger.error(args)
  }
}

Now if I call error() somewhere in another file:

// app.ts
startApp() {
  this.loggerService.error('something is wrong')
}

The settings displayFilePath and displayFunctionName shows:

2020-10-24 16:18:18.210  ERROR  [src/core/logger/logger.service.ts:105 LoggerService.error]             something is wrong 

I'd like the log to show:

2020-10-24 16:18:18.210  ERROR  [src/app.ts:35 app.startApp]             something is wrong 

So my question is can I do something to say "take the file name and function name from the parent class App instead of LoggerService?

For the stack, I can remove the first item of the array, I wonder if something similar could be done.

Feature Request: [Feature] Consistent formatting + timestamp customization for floating point

Description / Use Case for a Feature

  1. Space / tab mixed formatting:

image

If logger contains different display configs across log object as above - for example displayLogname: true then some other properties are not set - properties are substituted as space then each separator uses tab. This mixes spaces / tab for output, as well as it'll have numbers of tab instead of single tab separator.

Curious if it's possible logger do not emit separator for property not to display and have consistent (preferably single tab) separator?

  1. floating point customization

It looks like ms point is fixed to 3 always, and it's usually not very much helpful as most of log may need ms only. Will it be possible to allow customization for this as well?

Cannot run with node once compiled

node version: v12.13.1
os: MacOS
typescript: 3.9.6
tslog: 2.6.1

I have no issue running this with ts-node, but when I actually run the tsc on my project and do a node ./dist/index.js I get the following error. I have tried removing it and everything works as expected, but as soon as I even just instantiate the new Logger() I get the error below.

/Users/****/source/*****/node_modules/@babel/template/lib/builder.js:71
      rootStack = error.stack.split("\n").slice(3).join("\n");

tsconfig.json

  "compilerOptions": {
    "target": "es5",
    "lib": ["esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "strict": true,
    "noErrorTruncation": true,
    "rootDir": "src",
    "outDir": "dist",
    "sourceMap": true
  },
  "include": ["./src/**/*"],
  "exclude": [
    "node_modules"
  ]
}```

Bug: JSON type returning hostname and instance name when supposed to be hidden by default

Describe the bug
The json type is returning the full logObject regardless of the values provided to be hidden/displayed in the settings.

To Reproduce
Steps to reproduce the behavior:

  1. Create new Logger with settings param {type: 'json'}
  2. Pass a string to Logger instance to see the output.

Expected behavior
The log output when formatted as json should not display the values that are supposed to be hidden by default. Ie. hostname, instancename.

Node.js Version
14.16.0

OS incl. Version
macOS 10.15.7

Bug: Absolute paths using ES modules in Node

Describe the bug
In the module description, it says

Paths are relative to the root of the application folder

Using node ES modules in an express project, the paths are not relative, but absolute from the system root.

To Reproduce
The logger module file is below

import { Logger } from 'tslog'

const logger = new Logger({
  name: 'log',
  displayLoggerName: false,
  printLogMessageInNewLine: true,
  overwriteConsole: true,
})

export default logger

Using it like the following:

import logger from './utils/logger.mjs'

logger.info(`Connecting to ${config.PORT}`)

const err = new Error('Test Error')
logger.prettyError(err)

The output is

2021-04-18 06:56:20.482  INFO [file:///home/vanntile/src/tests/nn/src/app.mjs:12 undefined.<anonymous>]
Connecting to 8080 

 Error  Test Error
error stack:
• app.mjs:24 <anonymous>
    file:/home/vanntile/src/tests/nn/src/app.mjs:24:13

Expected behavior
The paths being relative from the project root.

Additional context
This happens both when running with node and nodemon.

Node.js Version
14.15.3

npm Version
7.9.0

OS incl. Version
Ubuntu 20.04

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.