Skip to content

Commit

Permalink
fix: handle cases where hostname, pid, and message could be undefined (
Browse files Browse the repository at this point in the history
…#1753)

Slight performance increase as well with setting the pid and hostname
strings at creation of the instance rather than at each call
  • Loading branch information
jmcdo29 authored Sep 7, 2023
2 parents eec2bbe + 44e293a commit a80439b
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 27 deletions.
5 changes: 5 additions & 0 deletions .changeset/metal-peaches-beg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ogma/logger': patch
---

Properly ignore the hostname, pid, and application in json logsm if the option is set to not usethem
10 changes: 5 additions & 5 deletions apps/docs/src/pages/en/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,21 @@ Examples can be seen below. The JSON structure follows the same form with log le

To get `ogma` to automatically print multiple values for you, rather than having to call `ogma.log` on each value, you can pass an array of value and the `{ each: true }` option to `ogma`. This will cause `ogma` to print each value of the array as if you had called `ogma.log` on each one.

::: info
:::info

Ogma ill **not** recursively print arrays of arrays. `[ ['Hello', 'World'], ['Foo', 'Bar', 'Baz']` will print two arrays across two lines, not five strings across five lines.

:::

::: info
:::info

This option is available in `@ogma/logger@^2.4.0`

:::

This option is also available globally, so you can set it on the instantiation of your ogma instance and no worry about it on each call.

::: info
:::info

This option is available in `@ogma/logger@^2.5.0`

Expand All @@ -90,8 +90,8 @@ This option is available in `@ogma/logger@^2.5.0`
| levelMap | an object with the above levels as the keys and strings as the vales | a way to provide custom log levels in the event that there are mappings the developer wants to support |
| masks | string[] | An array of words that should be replaced while logging. useful for sensitive information like passwords. |
| logPid | boolean | An optional property you can set if you don't want to log the PID. |
| logApplication | boolean | An optional property you can set if you don't want to the the applicaiton name. |
| logHostnam | boolean | An optional property you can set if you don't want to log the hostname ofthe machine you're on. |
| logApplication | boolean | An optional property you can set if you don't want to the the application name. |
| logHostname | boolean | An optional property you can set if you don't want to log the hostname of the machine you're on. |
| each | boolean | An optional property that determines if array values should be printed on separate lines by default or not |

:::note
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/src/pages/en/nestjs/custom.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ layout: ../../../layouts/MainLayout.astro

To create a custom parser, you can either `extend` an existing parser and override any of the methods, such as the `getCallerIp()` if you need to get a value other than `req.ip` in the [`@ogma/platform-express`](/en/nestjs/http/platform-express) parser, or you can create your own class that `extends AbstractInterceptorService` or `implements InterceptorService`. All of the methods of these classes and interfaces have appropriate typings and doc strings to help with creating your own parser if you want to work with a system that is not directly yet supported.

As of `@ogma/[email protected]` you also need to add the `@Parser()` decorator to your custom parser. This decorator can replace the `@Injectable()` or they can both be present, Nest will handle them the same. The `@Parser()` decorator takes in a string that should match the `ExecutionContext#getType()` method's return. e.g. for express or fastify, this would be `http`. This allows for developers of other application types that integrate with Nest to provider their own parsers and not have the interceptor throw errors about unknown context types. If a requesttype comes in the the interceptor does not know how to deal with, the request will simply continue
As of `@ogma/[email protected]` you also need to add the `@Parser()` decorator to your custom parser. This decorator can replace the `@Injectable()` or they can both be present, Nest will handle them the same. The `@Parser()` decorator takes in a string that should match the `ExecutionContext#getType()` method's return. e.g. for express or fastify, this would be `http`. This allows for developers of other application types that integrate with Nest to provider their own parsers and not have the interceptor throw errors about unknown context types. If a request type comes in the the interceptor does not know how to deal with, the request will simply continue

```ts
interface InterceptorService {
Expand Down
49 changes: 28 additions & 21 deletions packages/logger/src/logger/ogma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ const checkIfHasSpaceRegex = /[^\n]$/;
*/
export class Ogma {
private options: OgmaOptions;
private pid: string;
private jsonPid: number | undefined;
private hostname: string;
private readonly pid: string;
private readonly hostname: string;
private styler: Styler;
private each: boolean;
private application: string;
private readonly application: string;

private cachedContextFormatted: Map<string, Map<Color, string>> = new Map();
private sillyFormattedLevel: string;
Expand Down Expand Up @@ -59,8 +58,7 @@ export class Ogma {
.filter((key) => isNil(options[key]))
.forEach((key) => delete options[key]);
this.options = { ...OgmaDefaults, ...(options as OgmaOptions) };
this.jsonPid = Number(process.pid);
this.pid = this.wrapInBrackets(this.jsonPid.toString()) + ' ';
this.pid = this.wrapInBrackets(process.pid.toString()) + ' ';
this.hostname = hostname();
if (options?.logLevel && LogLevel[options.logLevel] === undefined) {
this.options.logLevel = OgmaDefaults.logLevel;
Expand All @@ -80,7 +78,10 @@ export class Ogma {
}
if (!this.options.logPid) {
this.pid = '';
this.jsonPid = undefined;
}
if (this.options.json) {
this.hostname &&= `"hostname":${this.asString(this.hostname)},`;
this.pid &&= `"pid":${process.pid},`;
}
this.cachedMasks = this.options?.masks
? new Map(this.options.masks.map((mask) => [mask, true]))
Expand Down Expand Up @@ -216,25 +217,31 @@ export class Ogma {

let fastJson = `{"time":${Date.now()},`;

fastJson += `"hostname":${this.asString(this.hostname)},`;
fastJson += `"pid":${this.jsonPid},`;
fastJson += this.hostname ?? '';
fastJson += this.pid ?? '';
fastJson += `"ool":${this.asString(LogLevel[level])},`;
fastJson += `"level":${mappedLevel},`;

if (application) fastJson += `"application":${this.asString(application)},`;

if (correlationId) fastJson += `"correlationId":${this.asString(correlationId)},`;

if (context) fastJson += `"context":${this.asString(context)},`;

if (meta && Object.keys(meta).length > 0) fastJson += `"meta":${stringify(meta)},`;

if (this.options.levelKey) fastJson += `"${this.options.levelKey}":${mappedLevel},`;

if (application) {
fastJson += `"application":${this.asString(application)},`;
}
if (correlationId) {
fastJson += `"correlationId":${this.asString(correlationId)},`;
}
if (context) {
fastJson += `"context":${this.asString(context)},`;
}
if (meta && Object.keys(meta).length > 0) {
fastJson += `"meta":${stringify(meta)},`;
}
if (this.options.levelKey) {
fastJson += `"${this.options.levelKey}":${mappedLevel},`;
}
if (typeof message === 'object')
fastJson += `"message":${stringify(message, this.circularReplacer())}`;
else fastJson += `"message":${this.asString(message.toString())}`;

else if (message !== undefined) {
fastJson += `"message":${this.asString(message.toString())}`;
}
fastJson += '}';

return fastJson;
Expand Down

0 comments on commit a80439b

Please sign in to comment.