All declarations of 'logger' must have identical modifiers.ts(2687)
Subsequent property declarations must have the same type. Property 'logger' must be of type 'ILogger', but here has type 'Logger'.ts(2717)
index.d.mts(3416, 5): 'logger' was also declared here.
import { ActivityType, GatewayIntentBits, type Message, Partials } from 'discord.js';
import { BucketScope, SapphireClient } from '@sapphire/framework';
import type { InternationalizationContext } from '@sapphire/plugin-i18next';
import { Player } from 'discord-player';
import Config from '../config.ts';
// import Database from './Database.ts';
import { guild } from '../models/guild.ts';
import type * as Utils from './utils.ts';
import type Soundboard from './Soundboard.ts';
import Logger from './Logger.ts';
export class EnidClient extends SapphireClient {
public override player!: Player;
// public db: Database;
public override utils!: typeof Utils;
public override config!: typeof Config;
public soundboard!: InstanceType;
public readonly logger: Logger;
code
Assistant
User
Subsequent property declarations must have the same type. Property 'logger' must be of type 'ILogger', but here has type 'Logger'.ts(2717)
index.d.mts(3416, 5): 'logger' was also declared here.
но вот мой logger - export default class Logger extends EventEmitter
Assistant
User
почему он использует (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')
);
}
Assistant
User
мне нужно чтобы туда можно было передать только Error
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The error you're encountering arises from a conflict in how the logger property is defined in your EnidClient class versus how it's defined within the @sapphire/framework.
Here's a breakdown of the problem and how to fix it:
The Problem
SapphireClient defines logger as ILogger:
The SapphireClient class from @sapphire/framework declares the logger property as type ILogger which is an interface.
See: ./repos/framework/src/lib/SapphireClient.ts
ts
export class SapphireClient<Ready extends boolean = boolean> extends Client<Ready> {
// ...
public override logger: ILogger;
// ...
}
Your EnidClient class is extending SapphireClient and declares logger as type Logger, a concrete class implementation of ILogger.
See: Your code
ts
import Logger from './Logger.ts';
export class EnidClient extends SapphireClient {
// ...
public readonly logger: Logger;
// ...
}
TypeScript Conflict:
TypeScript enforces that when you override a property from a parent class, the overriding property must have the same type or a more specific subtype.
In your case, Logger is not the same type as ILogger and not a subtype of it, hence the errors.
The Solution
To fix the issue, you should make your EnidClient's logger property use the ILogger type and initialize it with your Logger implementation.
Here's the corrected code for your EnidClient class:
typescript
Key changes:
public override readonly logger: ILogger;: The type of the logger property is changed to ILogger, which is the interface expected by the base class. The readonly modifier prevents modification of the logger instance after initialization.
this.logger = new Logger(/* Log Level Here */);: Now the logger property is initialized with an instance of your Logger class.
With these changes, you are satisfying the type constraints of the SapphireClient class and properly using your custom Logger class for logging within the Sapphire framework. Remember to provide the desired LogLevel to the Logger constructor.
Okay, I understand the issue better now. Your Logger class is not compatible with the ILogger interface from @sapphire/framework because it extends EventEmitter instead of implementing ILogger.
Here's how to reconcile this and ensure your Logger class works with Sapphire:
Understanding the Problem
ILogger Interface: The @sapphire/framework expects a logger that adheres to its ILogger interface. This interface defines specific methods like trace, debug, info, etc.
Your Logger Class: Your Logger class, which extends EventEmitter, doesn't inherently implement the ILogger interface and does not have the required methods like trace, debug, info.
TypeScript Error: TypeScript throws an error because the logger property in SapphireClient is typed as ILogger, but your EnidClient is attempting to assign a different type.
Solution: Make your Logger Class Implement ILogger
To fix the issue, you need to modify your Logger class to implement the ILogger interface. This involves adding the required methods to your class. Since you're extending EventEmitter, you'll want to forward the logging calls to console.
Here's a revised Logger.ts that demonstrates this, along with adjustments to your client:
Revised Logger.ts
typescript
import { EventEmitter } from 'node:events';
import { LogLevel, type ILogger } from '@sapphire/framework';
export default class Logger extends EventEmitter implements ILogger {
public level: LogLevel;
public constructor(level: LogLevel = LogLevel.Info) {
super();
this.level = level;
}
public has(level: LogLevel): boolean {
return level >= this.level;
}
public trace(...values: readonly unknown[]): void {
this.write(LogLevel.Trace, ...values);
}
public debug(...values: readonly unknown[]): void {
this.write(LogLevel.Debug, ...values);
}
public info(...values: readonly unknown[]): void {
this.write(LogLevel.Info, ...values);
}
public warn(...values: readonly unknown[]): void {
this.write(LogLevel.Warn, ...values);
}
public error(...values: readonly unknown[]): void {
this.write(LogLevel.Error, ...values);
}
public fatal(...values: readonly unknown[]): void {
this.write(LogLevel.Fatal, ...values);
}
public write(level: LogLevel, ...values: readonly unknown[]): void {
if (!this.has(level)) return;
const method = Logger.levels.get(level);
if (typeof method === 'string') console[method](`[${method.toUpperCase()}]`, ...values);
}
protected static readonly levels = new Map<LogLevel, LogMethods>([
[LogLevel.Trace, 'trace'],
[LogLevel.Debug, 'debug'],
[LogLevel.Info, 'info'],
[LogLevel.Warn, 'warn'],
[LogLevel.Error, 'error'],
[LogLevel.Fatal, 'error']
]);
}
export type LogMethods = 'trace' | 'debug' | 'info' | 'warn' | 'error';
Revised EnidClient.ts
typescript
Key Changes:
implements ILogger: The Logger class now explicitly states that it implements the ILogger interface.
Added ILogger methods: trace, debug, info, warn, error, and fatal are now added to the Logger class with the write method to send to the console.
Set log level: When creating an instance of the Logger you can optionally provide a log level. In this case we set it to LogLevel.Debug
Updated import: The EnidClient now imports the LogLevel enum.
Explanation
Implementing the Interface: By adding implements ILogger to your Logger class, you tell TypeScript that your class is contractually obligated to have all the methods defined in the ILogger interface.
Forwarding to console: The new Logger class includes basic implementations of the methods, which forward the logs to the console.
Now, your Logger class will be compatible with the logger property of SapphireClient, resolving the TypeScript error, and ensuring you can use your custom logger with the framework.
You've identified a crucial point about how the @sapphire/framework's ILogger interface is designed to be used, and why your specific error method signature wasn't being directly called. Let's break down why and how to adapt.
The Core Issue
ILogger's error Method:
The ILogger interface in @sapphire/framework defines the error method as:
typescript
error(...values: readonly unknown[]): void;
This signature is designed to accept a variable number of arguments (...values) of any type, as a readonly array. This pattern allows for logging flexibility, as one can provide multiple values that can be stringified, or logged as an object, or both.
Your Logger's error Method (Initial):
You originally defined error as:
typescript
error(error: Error): void { ... }
This method signature expects a single argument of type Error. It's not directly compatible with the ILogger interface's requirement for ...values: readonly unknown[].
Why the Framework Calls the ILogger method, not Yours:
When you assign your Logger instance to the logger property of SapphireClient, TypeScript ensures that your class satisfies the ILogger interface.
The framework and other parts of your code using the ILogger type will always use the method signature that is defined on the interface: (...values: readonly unknown[]).
Therefore, calls like container.logger.error("Something went wrong", myError) are designed to call your error method implemented as:
ts
public error(...values: readonly unknown[]): void {
this.write(LogLevel.Error, ...values);
}
instead of the method you defined with a signature of error(error: Error): void.
How to Adapt Your Error Handling
You have a few options to adapt your Logger to handle errors effectively:
Option 1: Modify Your error Method to Accept ...values (Recommended)
This option is the recommended approach, as it allows your custom logger to conform to the ILogger interface and handle any value passed to it by the framework and other parts of your code.
* Adjust your error method in your Logger class to use the ...values: readonly unknown[] signature, and then adapt your logging logic within that method.
* This ensures that you can handle any number of arguments of any type passed to the error method, and provides flexibility.
* Here's an updated implementation:
typescript
import { EventEmitter } from 'node:events';
import { LogLevel, type ILogger } from '@sapphire/framework';
export default class Logger extends EventEmitter implements ILogger {
public level: LogLevel;
public constructor(level: LogLevel = LogLevel.Info) {
super();
this.level = level;
}
public has(level: LogLevel): boolean {
return level >= this.level;
}
public trace(...values: readonly unknown[]): void {
this.write(LogLevel.Trace, ...values);
}
public debug(...values: readonly unknown[]): void {
this.write(LogLevel.Debug, ...values);
}
public info(...values: readonly unknown[]): void {
this.write(LogLevel.Info, ...values);
}
public warn(...values: readonly unknown[]): void {
this.write(LogLevel.Warn, ...values);
}
// Updated error method using the ...values signature
public error(...values: readonly unknown[]): void {
// Process each value
const stringifiedValues = values.map(value => {
if (value instanceof Error) {
return (value.stack ? [value.stack] : [value.name, value.message])
.filter(Boolean)
.map(v => v.toString())
.join('\n');
} else {
return String(value);
}
});
this.write(LogLevel.Error, ...stringifiedValues);
}
public fatal(...values: readonly unknown[]): void {
this.write(LogLevel.Fatal, ...values);
}
public write(level: LogLevel, ...values: readonly unknown[]): void {
if (!this.has(level)) return;
const method = Logger.levels.get(level);
if (typeof method === 'string') console[method](`[${method.toUpperCase()}]`, ...values);
}
protected static readonly levels = new Map<LogLevel, LogMethods>([
[LogLevel.Trace, 'trace'],
[LogLevel.Debug, 'debug'],
[LogLevel.Info, 'info'],
[LogLevel.Warn, 'warn'],
[LogLevel.Error, 'error'],
[LogLevel.Fatal, 'error']
]);
}
export type LogMethods = 'trace' | 'debug' | 'info' | 'warn' | 'error';
Option 2: Provide an Error Logging Method Separately (Less Flexible)
You could keep your error(error: Error) method and have users of your logger pass errors specifically to that method.
* However, the framework will still not be using this method, as it conforms to the ILogger interface and will use error(...values: readonly unknown[]): void
* This approach means that you would need to make sure that you always call this specific method on the Logger instance when wanting to log errors, and cannot rely on the framework to call it correctly.
This approach is more restrictive and less flexible. I'd recommend avoiding it.
Why Option 1 is Better
Flexibility: It aligns your Logger with how @sapphire/framework and general logging practices work, allowing any type of value to be passed to the error method.
Simplicity: It requires less code overall than other options.
Standard Usage: Using ...values matches the standard way of logging in JavaScript and how many logging interfaces are designed.
In Summary
The key takeaway is that by adopting the error(...values: readonly unknown[]): void signature, you create a more versatile Logger that integrates seamlessly with @sapphire/framework and standard JavaScript logging practices. Option 1 above is the best approach here.
Okay, I understand. You want your error method in your custom logger to only accept an Error object, while still being compatible with the ILogger interface. This is a bit of a tricky situation because the ILogger interface specifies ...values: readonly unknown[] for its error method.
Here's a solution that allows you to enforce the Error type for your internal handling while still satisfying the interface:
Revised Logger.ts
typescript
import { EventEmitter } from 'node:events';
import { LogLevel, type ILogger } from '@sapphire/framework';
export default class Logger extends EventEmitter implements ILogger {
public level: LogLevel;
public constructor(level: LogLevel = LogLevel.Info) {
super();
this.level = level;
}
public has(level: LogLevel): boolean {
return level >= this.level;
}
public trace(...values: readonly unknown[]): void {
this.write(LogLevel.Trace, ...values);
}
public debug(...values: readonly unknown[]): void {
this.write(LogLevel.Debug, ...values);
}
public info(...values: readonly unknown[]): void {
this.write(LogLevel.Info, ...values);
}
public warn(...values: readonly unknown[]): void {
this.write(LogLevel.Warn, ...values);
}
// This is the method that conforms to the ILogger interface, it will call the internal _error method
public error(...values: readonly unknown[]): void {
// Filter out non-Error values, and log others
for(const value of values) {
if (value instanceof Error) {
this._error(value);
} else {
this.write(LogLevel.Error, value)
}
}
}
//This is the internal method that handles the Error type logging
private _error(error: Error): void {
this.write(
LogLevel.Error,
(error.stack ? [error.stack] : [error.name, error.message])
.filter(Boolean)
.map(v => v.toString())
.join('\n')
);
}
public fatal(...values: readonly unknown[]): void {
this.write(LogLevel.Fatal, ...values);
}
public write(level: LogLevel, ...values: readonly unknown[]): void {
if (!this.has(level)) return;
const method = Logger.levels.get(level);
if (typeof method === 'string') console[method](`[${method.toUpperCase()}]`, ...values);
}
protected static readonly levels = new Map<LogLevel, LogMethods>([
[LogLevel.Trace, 'trace'],
[LogLevel.Debug, 'debug'],
[LogLevel.Info, 'info'],
[LogLevel.Warn, 'warn'],
[LogLevel.Error, 'error'],
[LogLevel.Fatal, 'error']
]);
}
export type LogMethods = 'trace' | 'debug' | 'info' | 'warn' | 'error';
Explanation of Changes
Interface-Compliant error:
The error method now conforms to ILogger by accepting ...values: readonly unknown[]. This satisfies the interface contract with the framework.
Internal _error Method:
We've introduced a new private method called _error(error: Error) specifically for handling Error objects. This is where your custom logic for formatting and logging Error objects is placed.
Handling Multiple Values:
The error method now iterates over the values array. If a value is of type Error, then it calls the internal _error method, while all other non-Error values are sent to the write method as is.
Internal Error Logging Logic:
*The _error method is the location where the logic for formatting error logging is performed.
Private Method:
The _error method is private so it cannot be called from outside the class. This makes the class use the interface-compliant error method.
How It Works
When the framework calls the error method on your logger instance it will pass one or more values.
The error method will then check each value, and if it is an instance of Error, pass it to the _error method, and if not, pass it to the write method.
The _error method then performs your desired error-specific logic.
Important Considerations
Flexibility Trade-off: By strictly enforcing Error in the private _error method, you are losing some flexibility of the framework as you will not be able to handle other types of values, these values are passed to the write method. However, this may be what you want for your application.
Type Safety: While you've achieved type safety internally within your Logger, the framework expects the error method to handle any type and any number of arguments.
Clarity: Using an internal method _error makes it clear that you're doing specific error formatting and handling, while also satisfying the interface.
Example Usage
typescript
// With the new Logger, calls can either be an error:
container.logger.error(new Error("Something broke"));
// Or a string or other type:
container.logger.error("Something broke", "some other information");
This setup provides a balance between conforming to the ILogger interface while still ensuring you can do specific handling of Error objects in your logger. If you require more flexibility with error handling, you may want to remove the _error method and just log values passed to the public error method after checking if it is an instance of Error.
Dataset releases
Not yet included in a published release.
import { ActivityType, GatewayIntentBits, type Message, Partials } from 'discord.js';
import { BucketScope, SapphireClient, type ILogger } from '@sapphire/framework';
import type { InternationalizationContext } from '@sapphire/plugin-i18next';
import { Player } from 'discord-player';
import Config from '../config.ts';
// import Database from './Database.ts';
import { guild } from '../models/guild.ts';
import type * as Utils from './utils.ts';
import type Soundboard from './Soundboard.ts';
import { Logger } from './Logger.ts';
export class EnidClient extends SapphireClient {
public override player!: Player;
// public db: Database;
public override utils!: typeof Utils;
public override config!: typeof Config;
public soundboard!: InstanceType<typeof Soundboard>;
public override readonly logger: ILogger; // Use ILogger here
public constructor() {
super({
disableMentionPrefix: false,
defaultPrefix: Config.prefix,
[Redacted Person]: true,
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.MessageContent,
GatewayIntentBits.AutoModerationConfiguration,
GatewayIntentBits.AutoModerationExecution
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction, Partials.GuildMember],
presence: {
activities: [
{
name: `Команды: ${Config.prefix}help`,
type: ActivityType.Competing
}
]
},
defaultCooldown: {
filteredUsers: Config.dev,
scope: BucketScope.User,
delay: 10_000,
limit: 2
},
loadMessageCommandListeners: true,
hmr: {
enabled: Config.debug
},
i18n: {
hmr: {
enabled: Config.debug
},
fetchLanguage: async (context: InternationalizationContext): Promise<string | null> => {
if (context.interactionGuildLocale || context.interactionLocale) {
return context.interactionGuildLocale || context.interactionLocale || null;
}
if (!context.guild) {
return 'en-US'; // или 'ru-RU' язык по умолчанию
}
// const guildSettings = await this.db.get(`guildSettings_${context.guild.id}`);
const guildSettings = await guild.get({ select: { language: true }, where: { id: context.guild.id } });
if (guildSettings && guildSettings.language) {
return guildSettings.language;
}
return 'ru-RU';
},
i18next: {
load: 'all'
}
}
});
// this.db = new Database();
this.config = Config;
this.logger = new Logger( /* Log Level Here*/ ); // Initialize with your Logger instance
this.player = Player.create(this, {
lagMonitor: 1000,
useLegacyFFmpeg: false,
skipFFmpeg: false
});
}
private async initialize(): Promise<void> {
this.utils = await import('./utils.ts');
const { default: Sound } = await import('./Soundboard.ts');
this.soundboard = new Sound();
}
public override async login(token?: string | undefined): Promise<string> {
await this.initialize();
return super.login(token);
}
public override fetchPrefix = async (message: Message): Promise<string> => {
if (this.utils.isGuildMessage(message)) {
const guildPrefix = await guild.get({ select: { prefix: true }, where: { id: message.guild.id } });
if (guildPrefix && guildPrefix.prefix) {
return guildPrefix.prefix;
}
}
return this.config.prefix;
};
}
declare module '@sapphire/framework' {
interface SapphireClient {
readonly player: Player;
readonly config: typeof Config;
readonly utils: typeof Utils;
readonly logger: ILogger;
// readonly db: Database;
readonly soundboard: Soundboard;
}
}
import { ActivityType, GatewayIntentBits, type Message, Partials } from 'discord.js';
import { BucketScope, SapphireClient, type ILogger, LogLevel } from '@sapphire/framework';
import type { InternationalizationContext } from '@sapphire/plugin-i18next';
import { Player } from 'discord-player';
import Config from '../config.ts';
// import Database from './Database.ts';
import { guild } from '../models/guild.ts';
import type * as Utils from './utils.ts';
import type Soundboard from './Soundboard.ts';
import Logger from './Logger.ts';
export class EnidClient extends SapphireClient {
public override player!: Player;
// public db: Database;
public override utils!: typeof Utils;
public override config!: typeof Config;
public soundboard!: InstanceType<typeof Soundboard>;
public override readonly logger: ILogger;
public constructor() {
super({
disableMentionPrefix: false,
defaultPrefix: Config.prefix,
[Redacted Person]: true,
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.MessageContent,
GatewayIntentBits.AutoModerationConfiguration,
GatewayIntentBits.AutoModerationExecution
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction, Partials.GuildMember],
presence: {
activities: [
{
name: `Команды: ${Config.prefix}help`,
type: ActivityType.Competing
}
]
},
defaultCooldown: {
filteredUsers: Config.dev,
scope: BucketScope.User,
delay: 10_000,
limit: 2
},
loadMessageCommandListeners: true,
hmr: {
enabled: Config.debug
},
i18n: {
hmr: {
enabled: Config.debug
},
fetchLanguage: async (context: InternationalizationContext): Promise<string | null> => {
if (context.interactionGuildLocale || context.interactionLocale) {
return context.interactionGuildLocale || context.interactionLocale || null;
}
if (!context.guild) {
return 'en-US'; // или 'ru-RU' язык по умолчанию
}
// const guildSettings = await this.db.get(`guildSettings_${context.guild.id}`);
const guildSettings = await guild.get({ select: { language: true }, where: { id: context.guild.id } });
if (guildSettings && guildSettings.language) {
return guildSettings.language;
}
return 'ru-RU';
},
i18next: {
load: 'all'
}
}
});
// this.db = new Database();
this.config = Config;
this.logger = new Logger(LogLevel.Debug);
this.player = Player.create(this, {
lagMonitor: 1000,
useLegacyFFmpeg: false,
skipFFmpeg: false
});
}
private async initialize(): Promise<void> {
this.utils = await import('./utils.ts');
const { default: Sound } = await import('./Soundboard.ts');
this.soundboard = new Sound();
}
public override async login(token?: string | undefined): Promise<string> {
await this.initialize();
return super.login(token);
}
public override fetchPrefix = async (message: Message): Promise<string> => {
if (this.utils.isGuildMessage(message)) {
const guildPrefix = await guild.get({ select: { prefix: true }, where: { id: message.guild.id } });
if (guildPrefix && guildPrefix.prefix) {
return guildPrefix.prefix;
}
}
return this.config.prefix;
};
}
declare module '@sapphire/framework' {
interface SapphireClient {
readonly player: Player;
readonly config: typeof Config;
readonly utils: typeof Utils;
readonly logger: ILogger;
// readonly db: Database;
readonly soundboard: Soundboard;
}
}