почему он использует (method) ILogger.error(...values: readonly unknown[]): void (+1 overload) а не метод который я реализовал error(error: Error): void {
this.write(
LoggerLevel.Error,
(error.stack ? [error.stack] : [error.name, error.message])
.filter(Boolean)
.map(v => v.toString())
.join('\n')
);
}
The provided code uses ILogger.error(...values: readonly unknown[]): void because it's designed to handle logging of any kind of value, not just errors. Here's a breakdown of why and how it works:
1. Flexibility of ILogger.error(...values: readonly unknown[]): void:
Handles Various Data Types: The ...values: readonly unknown[] parameter allows you to pass any number of arguments of any type to the logger. This could be strings, numbers, objects, or even errors.
Generic Logging: This approach enables you to log informative messages, debug data, or even complex objects for debugging purposes and more, it is not limited to error type logging.
Consistent Interface: All logging methods (trace, debug, info, warn, error, fatal) in the ILogger interface follow this pattern. This makes the API consistent and easy to use.
Centralized Formatting: The actual formatting and output logic is handled within the write method (in Logger.ts), which gives flexibility in how the values are processed and displayed.
2. Why not error(error: Error): void?
Limited to Errors: The error(error: Error): void signature is specifically designed for Error objects. While it can be helpful for processing errors with stacks it is not as flexible as the current implementation.
Inconsistency: Having a specific method for Error objects would break the consistency of the ILogger interface. It would need different signatures for all methods.
Less Flexible: The error method you described would only support errors as input. That would prevent users to log additional information or context along with the error.
Unnecessary Specialization: The write method in the current implementation already handles the formatting of different values, including errors. There is no need for a separate function just for handling Error objects.
3. How the Current Implementation Handles Errors:
Logger.tswrite method:
It receives LogLevel and ...values as arguments.
It checks if the current logger level supports the message level using this.has(level).
If the message should be logged, it uses the Logger.levels map to get the console method to call ('trace', 'debug', 'info', 'warn', or 'error').
It logs the level and all values passed.
Error Output: In the provided implementation, the error will be printed in the console with the log level (ex: "[ERROR]") and all passed values.
Flexibility of formatting: If more advanced error handling/formatting is needed it can be implemented in the write method by checking the type of the values, and doing error specific formatting or handling.
Example
typescript
import { Logger, LogLevel } from './lib/utils/logger/Logger';
const logger = new Logger(LogLevel.Debug);
try {
throw new Error('Something went wrong');
} catch (error: any) {
logger.error('An error occurred:', error); // Passes error as one of the values
logger.error('An error occurred:', error.message, error.stack); // Passes message and stack
logger.error('Error name:', error.name); // Passes error name.
logger.error({error: error, timestamp: new Date()}); // Passes error object and timestamp.
}
In Summary:
The ILogger.error(...values: readonly unknown[]): void method is used for its flexibility and consistency in handling different logging needs. It allows you to log messages of all types and does not limit logging to only error objects. The write method in Logger.ts takes care of outputting those values. If error specific handling or formatting is required it should be implemented in the write method. This approach enables a more versatile logging solution.
Okay, let's break down how to correctly set up that declaration merging for @sapphire/framework to extend the SapphireClient interface.
Understanding Declaration Merging
In TypeScript, declaration merging allows you to extend existing interfaces, types, and namespaces by adding new properties or members. This is crucial for extending types provided by external libraries, such as @sapphire/framework, without modifying the library's source code directly.
Steps to Correctly Set Up Declaration Merging
Create a Declaration File:
You should create a .d.ts file (e.g., sapphire.d.ts or custom-sapphire.d.ts) in your project. A good place is usually in a types/ or @types/ folder at the root of your project, but it can be placed elsewhere as well, make sure that tsconfig.json recognizes it and includes it in the compilation.
Write the Declaration Merge:
Open the .d.ts file you created and paste the following code. It is crucial to make sure the file path matches your project structure:
typescript
import type { Player } from './path/to/your/player';
import type { Soundboard } from './path/to/your/soundboard';
import type { Utils } from './path/to/your/utils';
import type { Config } from './path/to/your/config';
import type { Logger as SapphireLogger } from './path/to/your/logger';
declare module '@sapphire/framework' {
interface SapphireClient {
readonly player: Player;
readonly config: typeof Config;
readonly utils: typeof Utils;
logger: SapphireLogger;
// readonly db: Database;
readonly soundboard: Soundboard;
}
}
Important Considerations:
Replace the placeholder paths ('./path/to/your/player', etc.) with the actual paths to the corresponding type definitions.
Make sure you have defined the types used in the declarations, otherwise you will get type errors.
If the logger type is from @sapphire/framework change the import from ./path/to/your/logger to @sapphire/framework
Ensure TypeScript Includes the Declaration File:
Your tsconfig.json should include the declaration file you created in the include or files configuration. For example:
In this example, it will include all .ts files inside src folder, and all definition files (.d.ts) inside types folder.
If you put the file outside the src or types folders you must include it there as well, for example with "include": ["src/**/*.ts", "../custom.d.ts"]
Usage
After setting this up, TypeScript should recognize the added properties (player, config, utils, logger, soundboard) when you access them on an instance of SapphireClient.
Complete Example
Let's say your project structure looks something like this:
export const Config = {
token: '[redacted possible key]',
};
src/lib/logger.ts:
typescript
import { Logger as SapphireLogger } from '@sapphire/framework';
export { SapphireLogger }
types/sapphire.d.ts:
typescript
import type { Player } from '../src/lib/player';
import type { Soundboard } from '../src/lib/soundboard';
import type { Utils } from '../src/lib/utils';
import type { Config } from '../src/lib/config';
import type { SapphireLogger } from '../src/lib/logger';
declare module '@sapphire/framework' {
interface SapphireClient {
readonly player: Player;
readonly config: typeof Config;
readonly utils: typeof Utils;
logger: SapphireLogger;
// readonly db: Database;
readonly soundboard: Soundboard;
}
}
Explanation:
The declaration merging is in types/sapphire.d.ts and it declares additional properties to the SapphireClient interface using the declare module '@sapphire/framework' syntax.
The tsconfig.json includes the types/sapphire.d.ts in the "include" section to make sure that the typescript compiler picks up the declaration file.
In the src/index.ts file, after creating a SapphireClient instance we are assigning values to the declared properties, and using them.
Key Points
Pathing: Make sure the import paths in your declaration file point to where the actual types are declared.
Type Definitions: Ensure that the types you are referencing (like Player, Soundboard, etc.) are defined or exported correctly.
tsconfig.json: The include or files property must be configured properly to include your declaration file.
Consistency: Make sure that the properties you add are actually present in your class that implements SapphireClient, otherwise you will get errors at runtime.
By following these steps, you can successfully extend the SapphireClient interface in @sapphire/framework and add custom properties that are correctly type-checked by TypeScript.
You're encountering a common situation when working with dependency injection and class hierarchies: you have two seemingly different loggers because they are being accessed through different parts of your application's structure. Let's break down why and how to manage it:
Understanding the Context
this.container.logger: This logger is usually the main application-wide logger, often configured as a service in your dependency injection container. It's designed for logging events within your framework's structures, such as command execution, event handling, and lifecycle management.
this.container.client.logger: This logger is likely a logger instance attached directly to your Discord client, potentially as an extension. This means it could have been configured on the client itself to log its own events, such as connection state changes, websocket events, etc.
Why Two Loggers Exist
Separation of Concerns:
The framework wants a central logger to log framework events, and application-specific code might need a way to inject a different logger instance to be used by the application.
The Discord client might have its own internal logging needs, and that logger might not be suitable to handle all logging requirements of your framework.
This separation allows you to configure the logging for your framework separately from the logging specific to the Discord client.
Different Configurations:
These two loggers might have different configurations (e.g., logging levels, output destinations).
You might configure this.container.logger to log to a file, while this.container.client.logger might only log to the console.
Plugin/Extension:
You might have an extension or plugin on SapphireClient that adds the logger property with a different implementation than the one you are using in your dependency injection container.
How to Manage the Two Loggers
Choose the Right Logger:
Framework Logging: Use this.container.logger for logging related to your framework logic, commands, events, etc. This is the primary logger for your bot's custom logic.
Client/Discord Logging: Use this.container.client.logger for logging events specific to the Discord client's actions and connection states.
Custom Application Logging: Depending on your project, you might want to create your own logger, which you inject to all parts of your application, instead of relying on the one from @sapphire/framework. This can be useful if you need to add specific features or outputs.
Configure Each Logger:
You should properly configure this.container.logger in your dependency injection container.
You might be able to configure the client logger using a property on SapphireClient configuration or via a plugin/extension system. Consult documentation of the library used to extend the client to learn how to configure it.
Avoid Conflicting Configurations:
Make sure that the configurations do not conflict with each other.
For example, if both loggers try to write to the same file, you might end up with issues.
Consolidate If Necessary:
If you don't need separate logging configurations, you might consider replacing this.container.client.logger with the main framework logger. But this might remove some flexibility in the configuration.
Logging Levels:
Make sure you check the LogLevel of each logger, and set a suitable level to log all messages.
Example Scenario
Let's imagine you have a command that makes an API request:
typescript
import { Command, type CommandContext } from '@sapphire/framework';
export class MyCommand extends Command {
public override async chatInputRun(interaction: CommandContext) {
this.container.logger.debug(`Command ${interaction.commandName} was triggered by ${interaction.user.id}.`); // Framework Log
try {
// Make API request
const response = await fetch('https://some-api.com/data');
this.container.logger.debug(`API request to "https://some-api.com/data" was successful.`); // Framework Log
const data = await response.json();
} catch (error: any) {
this.container.logger.error(`Error during API request ${error}`); // Framework Log
this.container.client.logger.error(`Error during API request ${error.message}`); // Client/Discord specific log
}
}
}
In Summary
You have two loggers because they serve different purposes:
this.container.logger is designed for logging events within your custom application and framework, such as commands and event handling.
this.container.client.logger is often a separate logger instance attached directly to your Discord client, mainly for events related to the Discord connection.
By understanding their purposes, you can use them effectively to log different aspects of your application and keep logs separate, or consolidate them as needed.
Recommendation
Use this.container.logger as your primary logger for your bot's logic.
Use this.container.client.logger for logs specific to the Discord client if you need it.
Make sure to set the appropriate LogLevel for each logger.
If needed, and if flexibility is not a concern, consider consolidating the loggers.