fullstack-build / tslog Goto Github PK
View Code? Open in Web Editor NEW📝 tslog - Universal Logger for TypeScript and JavaScript
Home Page: https://tslog.js.org
License: MIT License
📝 tslog - Universal Logger for TypeScript and JavaScript
Home Page: https://tslog.js.org
License: MIT License
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
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
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.
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.
Lines 64 to 78 in 77ab7c9
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.
Describe the bug
logging an Error object with colorizePrettyLogs: false throws a ERR_INVALID_ARG_TYPE
To Reproduce
https://github.com/markayers/tslog-error-bug-repro
Expected behavior
a stacktrace log without ansi color codes
PR
#83
Node.js Version
12.19.0
OS incl. Version
Windows 10 Pro v2004 build 19041.746
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.
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 }],
})
Same as 2.9.1
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
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
Description / Use Case for a Feature
when writing web server its nice thing to see all the logs that relate to one request
this can be done using cls-hooked
see https://itnext.io/nodejs-logging-made-right-117a19e8b4ce
so custom formatter, or maybe option to make the logger name dynamic(accepting function instead of string)
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".
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
}
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
Description / Use Case for a Feature
The use case is for formatting the logs with more customization.
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?
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
This logger is awesome, but I'd also like to see some sort of NestJS module like this one for pino. Unfortunately, trying to integrate tslog
as an application-level logger in NestJS breaks the call site at this moment.
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:
mkdir tslogBugMaskStrings
cd tslogBugMaskStrings
npm init -y
npm i tslog
touch index.js
perhapsconst { 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.
Additional context
I added this as a separate issue to keep things cleaner with issue #37
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.
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:
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.");
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
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
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.
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)
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}]
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]
.
Additional context
Add any other context about the problem here.
Node.js Version
v15.2.1
OS incl. Version
Windows 10
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
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.
tslog/src/LoggerWithoutCallSite.ts
Lines 372 to 374 in 2e0d103
I am using tslog and jest for writing unit tests. I wanted to check if there is a way to silent the tslog when running unit tests without using any jest configuration?
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?
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.
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:
console.error(new Error("Hello"))
new Logger()
console.error(new Error("Hello"))
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
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!
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
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.
Describe the bug
Currently, tslog
overwrites util.inspect
styles by its own:
tslog/src/LoggerWithoutCallSite.ts
Lines 75 to 87 in 2760b41
Lines 136 to 144 in 2760b41
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:
console.log(inspect({ foo: "bar" }, { colors: true }))
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
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
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:60
• node:events:327 emit
node:events:327:20
• node: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)
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?
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:
$ mkdir tslog-test
$ cd tslog-test
$ npm init -y
$ npm install tslog
test.js
:const { Logger } = require('tslog');
const logger = new Logger();
logger.error('Hello');
console.log('The end');
.vscode/launch.json
:{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/test.js"
}
]
}
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
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
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[]);
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:
Some features that I'm looking for usually:
Appreciate your thoughts!
Describe the bug
TSLog masks password only if it is not the last value in the json.
To Reproduce
Steps to reproduce the behavior:
mkdir tslogBugReplace
cd tslogBugReplace
npm init -y
npm i tslog
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.
});
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.
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.
Description / Use Case for a Feature
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?
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?
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"
]
}```
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:
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
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.