Skip to content

Commit

Permalink
feat: change log level to verbosity (#7306)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartoszherba authored Nov 6, 2024
1 parent 14350c4 commit 1f6e660
Show file tree
Hide file tree
Showing 14 changed files with 81 additions and 115 deletions.
7 changes: 7 additions & 0 deletions .changeset/bright-ways-play.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@vue-storefront/middleware": minor
"@vue-storefront/logger": minor
"@vue-storefront/sdk": minor
---

Change LogLevel into LogVerbosity
47 changes: 23 additions & 24 deletions docs/content/3.middleware/2.guides/10.logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ const someExtension = {
name: "some-extension",
extendApp(params) {
const logger = getLogger(params);
logger.info("You can call a logger inside extendApp hook, called on bootstrap of the application");
}
logger.info(
"You can call a logger inside extendApp hook, called on bootstrap of the application"
);
},
};
```

Expand All @@ -57,7 +59,9 @@ const someExtension = {
name: "some-extension",
hooks(req, res, alokai) {
const logger = getLogger(alokai);
logger.info("You can call a logger every time a hooks factory gets invoked");
logger.info(
"You can call a logger every time a hooks factory gets invoked"
);
return {
// ...
};
Expand Down Expand Up @@ -110,7 +114,9 @@ const someExtension = {
name: "some-extension",
hooks(req, res, alokai) {
const hooksLogger = getLogger(alokai);
hooksLogger.info("You can call a logger every time a hooks factory gets invoked");
hooksLogger.info(
"You can call a logger every time a hooks factory gets invoked"
);
return {
beforeCall(params) {
// Never access via closure a logger belonging to the hooks factory:
Expand All @@ -119,7 +125,7 @@ const someExtension = {
const logger = getLogger(params);
logger.info("Do that!");
return params.args;
}
},
};
},
};
Expand All @@ -145,8 +151,8 @@ const testingExtension = {
return {
// ...
};
}
}
},
},
};
```

Expand Down Expand Up @@ -202,25 +208,18 @@ export interface LoggerOptions {
/**
* The log level aligned with RFC5424.
*/
level?: LogLevel; // (def. "info")
verbosity?: LogVerbosity; // (def. "info")

/**
* Whether to include the stack trace in the log message.
*/
includeStackTrace?: boolean; // (def. true)

/**
* Own implementation of logger to be used internally.
*
* @remarks If provided then other options won't be used.
*/
handler?: LoggerInterface;
}
```

#### 1. level
#### 1. Verbosity

This option sets the log level based on the [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424) syslog standard. It defines the severity of log messages that should be recorded. Available log levels are:
This option sets the log verbosity level based on the [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424) syslog standard. It defines the severity of log messages that should be recorded. Available log levels are:

- **emergency**: The highest severity level, indicating a system-wide emergency.
- **alert**: Indicates an urgent condition that requires immediate attention.
Expand All @@ -232,12 +231,12 @@ This option sets the log level based on the [RFC 5424](https://datatracker.ietf.
- **debug**: The most detailed log level, useful for tracing and debugging the application.

**Example:**
Setting the log level to `error` ensures only error messages and above (i.e., critical, alert, emergency) will be captured:
Setting the log verbosity level to `error` ensures only error messages and above (i.e., critical, alert, emergency) will be captured:

```json
{
"logger": {
"level": "error"
"verbosity": "error"
}
}
```
Expand All @@ -247,7 +246,7 @@ For a development environment, you might prefer a more verbose log level like `d
```json
{
"logger": {
"level": "debug"
"verbosity": "debug"
}
}
```
Expand All @@ -272,7 +271,7 @@ To configure the logger globally, add a `logger` object to the top-level configu
{
"logger": {
"includeStackTrace": true,
"level": "debug"
"verbosity": "debug"
},
// The rest of the middleware configuration
"integrations": {
Expand All @@ -294,15 +293,15 @@ For example, here is how you would configure the logger for an integration with
"integrations": {
"commerce": {
"location": "@vsf-enterprise/sapcc-api/server",

"configuration": {
// Configuration of integration itself
}

// Configuration of the logger only for "commerce" integration
"logger": {
"includeStackTrace": true,
"level": "debug"
"verbosity": "debug"
},
}
}
Expand Down Expand Up @@ -337,4 +336,4 @@ export interface LoggerInterface {

Each method in this interface corresponds to a log level defined by [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424), and the logger implementation should handle the provided `logData` and optional `metadata`.

Once a custom `handler` is provided, **all other logger configuration options (such as `level` or `includeStackTrace`) will no longer be used**. This allows for complete control over how the logs are processed.
Once a custom `handler` is provided, **all other logger configuration options (such as `verbosity` or `includeStackTrace`) will no longer be used**. This allows for complete control over how the logs are processed.
80 changes: 24 additions & 56 deletions docs/content/4.sdk/2.getting-started/4.logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ If the Logger is already included in the Alokai Storefront, you can skip this st
The Logger is provided by the SDK and framework specific packages.

In order to install the Logger, you need to update following packages to at least the following versions:
* `@vue-storefront/sdk` to `3.3.0`
* `@vue-storefront/nuxt` to `6.2.0`
* `@vue-storefront/next` to `4.3.0`

- `@vue-storefront/sdk` to `3.3.0`
- `@vue-storefront/nuxt` to `6.2.0`
- `@vue-storefront/next` to `4.3.0`

After updating the packages, you need to provide the Logger module to the SDK config.

Expand Down Expand Up @@ -46,35 +47,36 @@ export default defineSdkConfig(({ buildModule, loggerModule, middlewareModule, g
// ...
}));
```
::
::
## Configuration
The default configuration is already provided, but you can customize it by providing the following options:
* `level` - the minimum level of the message to be logged. The default value is `info`. Possible values are:
* `emergency`
* `alert`
* `critical`
* `error`
* `warning`
* `notice`
* `info`
* `debug`
* `includeStackTrace` - a boolean value that determines if the stack trace should be included in the log message. The default value is `true`.
* `handler` - a custom handler that will be called when the message is logged.
- `verbosity` - the minimum level of the message to be logged. The default value is `info`. Possible values are:
- `emergency`
- `alert`
- `critical`
- `error`
- `warning`
- `notice`
- `info`
- `debug`
- `includeStackTrace` - a boolean value that determines if the stack trace should be included in the log message. The default value is `true`.
To provide the configuration for the Logger, you need to update the SDK config with the Logger module configuration by providing an object with options to the `buildModule` function, e.g.:
```ts
// ...
logger: buildModule(loggerModule, {
level: 'debug',
verbosity: 'debug',
includeStackTrace: false,
}),
```
### Custom handler
There might a certain use case where you want to customize the way the Logger logs messages e.g. you want to change a log provider to a different one.
Then you can provide your own custom handler for the Logger. The handler must implement the `LoggerInterface` interface provided in the section [types](#type).
Expand All @@ -93,27 +95,27 @@ You can use the Logger in the same way as you would use any other SDK modules:
::code-group
```tsx [Server Side]
import { getSdk } from '@/sdk';
import { getSdk } from "@/sdk";

function ServerComponent() {
const sdk = getSdk();

sdk.logger.info('Example server side log');
sdk.logger.info("Example server side log");

// ...
}
```
```tsx [Client Side]
import { useSdk } from '@/sdk/alokai-context';
import { useSdk } from "@/sdk/alokai-context";

function ClientComponent() {
const sdk = useSdk();

useEffect(() => {
sdk.logger.info('Example client side log');
sdk.logger.info("Example client side log");
}, []);

// ...
}
```
Expand All @@ -128,41 +130,7 @@ function ClientComponent() {
useSdk().logger.info('Example log');
<script>
```
::
Now instead of using `console.log` you can use the Logger to log messages at different levels.
## Type
```ts
type LogData = unknown;
type Metadata = Record<string, unknown>;
type LogLevel =
| "emergency"
| "alert"
| "critical"
| "error"
| "warning"
| "notice"
| "info"
| "debug";

interface LoggerInterface {
emergency(logData: LogData, metadata?: Metadata): void;
alert(logData: LogData, metadata?: Metadata): void;
critical(logData: LogData, metadata?: Metadata): void;
error(logData: LogData, metadata?: Metadata): void;
warning(logData: LogData, metadata?: Metadata): void;
notice(logData: LogData, metadata?: Metadata): void;
info(logData: LogData, metadata?: Metadata): void;
debug(logData: LogData, metadata?: Metadata): void;
}

type LoggerModuleConfig = Partial<{
level: LogLevel;
includeStackTrace: boolean;
handler: LoggerInterface;
[key: string]: any;
}>;

```
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Metadata } from "../../../src/interfaces/LoggerInterface";
import { LogLevel } from "../../../src/interfaces/LogLevel";
import { LogVerbosity } from "../../../src/interfaces/LogVerbosity";
import { GCPStructuredLog } from "../../../src/structuredLog/GCPStructuredLog";

// We do not want to serialize the log payload at this point
Expand Down Expand Up @@ -157,7 +157,7 @@ describe("GCPStructuredLog", () => {
const gcpStructuredLog = log.createLog(
logData,
options,
severity as LogLevel,
severity as LogVerbosity,
metadata as unknown as Metadata
);
expect(gcpStructuredLog).toEqual(expected);
Expand Down
16 changes: 8 additions & 8 deletions packages/logger/src/ConsolaStructuredLogger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ConsolaOptions, createConsola } from "consola";

import dotenv from "dotenv";
import { LogLevel } from "./interfaces/LogLevel";
import { LogVerbosity } from "./interfaces/LogVerbosity";
import type {
LogData,
LoggerInterface,
Expand All @@ -23,11 +23,11 @@ interface ConsolaLoggerOptions
const createConsolaStructuredLogger = (
structuredLog: StructuredLog,
options: ConsolaLoggerOptions = {
level: "info",
verbosity: "info",
includeStackTrace: true,
}
): LoggerInterface => {
const levelMap: Record<LogLevel, number> = {
const levelMap: Record<LogVerbosity, number> = {
emergency: 0,
alert: 0,
critical: 0,
Expand All @@ -45,20 +45,20 @@ const createConsolaStructuredLogger = (
};

const logger = createConsola({
level: levelMap?.[options.level] ?? levelMap.info,
level: levelMap?.[options.verbosity] ?? levelMap.info,
reporters: options.reporters || [buildJsonReporter()],
});

if (options.reporters) {
logger.setReporters(options.reporters);
}

const mapToConsolaLevel = (level: LogLevel): number => {
const mapToConsolaLevel = (level: LogVerbosity): number => {
return levelMap?.[level] ?? levelMap.info; // Default to 'info' level
};

const logStructured = (
level: LogLevel,
level: LogVerbosity,
logData: LogData,
metadata?: Metadata
): void => {
Expand Down Expand Up @@ -99,14 +99,14 @@ const createConsolaStructuredLogger = (
};

const log = (
level: LogLevel,
level: LogVerbosity,
logData: LogData,
metadata?: Metadata
): void => {
logStructured(level, logData, metadata);
};

const logAtLevel = (level: LogLevel) => {
const logAtLevel = (level: LogVerbosity) => {
return (logData: LogData, metadata?: Metadata) =>
log(level, logData, metadata);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/logger/src/LoggerFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export enum LoggerType {
export class LoggerFactory {
static create(type: LoggerType, options?: LoggerOptions) {
const defaultOptions = {
level: "info",
verbosity: "info",
includeStackTrace: false,
} satisfies LoggerOptions;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* @see https://datatracker.ietf.org/doc/html/rfc5424
*/
export type LogLevel =
export type LogVerbosity =
| "emergency"
| "alert"
| "critical"
Expand Down
Loading

0 comments on commit 1f6e660

Please sign in to comment.