From: Jérôme Benoit Date: Mon, 27 Apr 2026 21:52:08 +0000 (+0200) Subject: chore(simulator): harmonize log messages across codebase (#1813) X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=4ef0da6ddff7022718007c52ee5615847398f8d1;p=e-mobility-charging-stations-simulator.git chore(simulator): harmonize log messages across codebase (#1813) * chore(simulator): add moduleName prefix to ChargingStation log messages * fix(simulator): downgrade unknown incoming OCPP command log to warn level * chore(simulator): harmonize remaining log messages across codebase * chore(simulator): harmonize state and lifecycle log message wording * fix(simulator): use event handler names instead of constructor in log prefixes * fix(simulator): correct grammar errors in log messages * fix(simulator): correct 'non existing' to 'non-existent' in log messages --- diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index ca65b7d6..b352db03 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -35,6 +35,8 @@ import { stopTransactionOnConnector, } from './ocpp/index.js' +const moduleName = 'AutomaticTransactionGenerator' + export class AutomaticTransactionGenerator { private static readonly instances: Map = new Map< string, @@ -86,11 +88,11 @@ export class AutomaticTransactionGenerator { return } if (this.started) { - logger.warn(`${this.logPrefix()} is already started`) + logger.warn(`${this.logPrefix()} ${moduleName}.start: Already started`) return } if (this.starting) { - logger.warn(`${this.logPrefix()} is already starting`) + logger.warn(`${this.logPrefix()} ${moduleName}.start: Already starting`) return } this.starting = true @@ -104,25 +106,32 @@ export class AutomaticTransactionGenerator { return } if (!this.connectorsStatus.has(connectorId)) { - logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`) + logger.error( + `${this.logPrefix(connectorId)} ${moduleName}.startConnector: Starting on non-existent connector` + ) throw new BaseError(`Connector ${connectorId.toString()} does not exist`) } if (this.connectorsStatus.get(connectorId)?.start === false) { this.internalStartConnector(connectorId, stopAbsoluteDuration).catch((error: unknown) => - logger.error(`${this.logPrefix(connectorId)} Error while starting connector:`, error) + logger.error( + `${this.logPrefix(connectorId)} ${moduleName}.startConnector: Error while starting connector:`, + error + ) ) } else if (this.connectorsStatus.get(connectorId)?.start === true) { - logger.warn(`${this.logPrefix(connectorId)} is already started on connector`) + logger.warn( + `${this.logPrefix(connectorId)} ${moduleName}.startConnector: Already started on connector` + ) } } public stop (): void { if (!this.started) { - logger.warn(`${this.logPrefix()} is already stopped`) + logger.warn(`${this.logPrefix()} ${moduleName}.stop: Already stopped`) return } if (this.stopping) { - logger.warn(`${this.logPrefix()} is already stopping`) + logger.warn(`${this.logPrefix()} ${moduleName}.stop: Already stopping`) return } this.stopping = true @@ -133,14 +142,18 @@ export class AutomaticTransactionGenerator { public stopConnector (connectorId: number): void { if (!this.connectorsStatus.has(connectorId)) { - logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`) + logger.error( + `${this.logPrefix(connectorId)} ${moduleName}.stopConnector: Stopping on non-existent connector` + ) throw new BaseError(`Connector ${connectorId.toString()} does not exist`) } const connectorStatus = this.connectorsStatus.get(connectorId) if (connectorStatus?.start === true) { connectorStatus.start = false } else if (connectorStatus?.start === false) { - logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`) + logger.warn( + `${this.logPrefix(connectorId)} ${moduleName}.stopConnector: Already stopped on connector` + ) } } @@ -150,7 +163,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} entered in transaction loop while the ATG stop date has been reached` + )} ${moduleName}.canStartConnector: Entered in transaction loop while the ATG stop date has been reached` ) return false } @@ -158,7 +171,7 @@ export class AutomaticTransactionGenerator { logger.error( `${this.logPrefix( connectorId - )} entered in transaction loop while the charging station is not in accepted state` + )} ${moduleName}.canStartConnector: Entered in transaction loop while the charging station is not in accepted state` ) return false } @@ -166,7 +179,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} entered in transaction loop while the charging station is unavailable` + )} ${moduleName}.canStartConnector: Entered in transaction loop while the charging station is unavailable` ) return false } @@ -174,7 +187,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} entered in transaction loop while the connector ${connectorId.toString()} is unavailable` + )} ${moduleName}.canStartConnector: Entered in transaction loop while the connector ${connectorId.toString()} is unavailable` ) return false } @@ -182,7 +195,7 @@ export class AutomaticTransactionGenerator { if (connectorStatus?.transactionStarted === true) { logger.info( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix(connectorId)} entered in transaction loop while a transaction ${connectorStatus.transactionId?.toString()} is already started on connector ${connectorId.toString()}` + `${this.logPrefix(connectorId)} ${moduleName}.canStartConnector: Entered in transaction loop while a transaction ${connectorStatus.transactionId?.toString()} is already started on connector ${connectorId.toString()}` ) return false } @@ -192,7 +205,9 @@ export class AutomaticTransactionGenerator { private getConnectorStatus (connectorId: number): Status { const statusIndex = connectorId - 1 if (statusIndex < 0) { - logger.error(`${this.logPrefix(connectorId)} invalid connector id`) + logger.error( + `${this.logPrefix(connectorId)} ${moduleName}.getConnectorStatus: Invalid connector id` + ) throw new BaseError(`Invalid connector id ${connectorId.toString()}`) } let connectorStatus: Status | undefined @@ -204,7 +219,7 @@ export class AutomaticTransactionGenerator { logger.warn( `${this.logPrefix( connectorId - )} no status found for connector #${connectorId.toString()} in charging station configuration file. New status will be created` + )} ${moduleName}.getConnectorStatus: No status found for connector #${connectorId.toString()} in charging station configuration file. New status will be created` ) } if (connectorStatus != null) { @@ -253,7 +268,9 @@ export class AutomaticTransactionGenerator { if (result.accepted) { ++connectorStatus.acceptedStartTransactionRequests } else { - logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`) + logger.warn( + `${this.logPrefix(connectorId)} ${moduleName}.handleStartTransactionResult: Start transaction rejected` + ) ++connectorStatus.rejectedStartTransactionRequests } } @@ -276,7 +293,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} started on connector and will run for ${formatDurationMilliSeconds( + )} ${moduleName}.internalStartConnector: Started on connector and will run for ${formatDurationMilliSeconds( (connectorStatus.stopDate?.getTime() ?? 0) - (connectorStatus.startDate?.getTime() ?? 0) )}` ) @@ -296,7 +313,9 @@ export class AutomaticTransactionGenerator { ?.maxDelayBetweenTwoTransactions ?? 0) + 1 ) ) - logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`) + logger.info( + `${this.logPrefix(connectorId)} ${moduleName}.internalStartConnector: Waiting for ${formatDurationMilliSeconds(wait)}` + ) await sleep(wait) const start = secureRandom() if ( @@ -319,7 +338,7 @@ export class AutomaticTransactionGenerator { ) logger.info( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation + `${this.logPrefix(connectorId)} ${moduleName}.internalStartConnector: Transaction started with id ${this.chargingStation .getConnectorStatus(connectorId) ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}` ) @@ -330,7 +349,7 @@ export class AutomaticTransactionGenerator { ++connectorStatus.skippedConsecutiveTransactions ++connectorStatus.skippedTransactions logger.info( - `${this.logPrefix(connectorId)} skipped consecutively ${connectorStatus.skippedConsecutiveTransactions.toString()}/${connectorStatus.skippedTransactions.toString()} transaction(s)` + `${this.logPrefix(connectorId)} ${moduleName}.internalStartConnector: Skipped consecutively ${connectorStatus.skippedConsecutiveTransactions.toString()}/${connectorStatus.skippedTransactions.toString()} transaction(s)` ) } connectorStatus.lastRunDate = new Date() @@ -339,12 +358,12 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} stopped on connector and lasted for ${formatDurationMilliSeconds( + )} ${moduleName}.internalStartConnector: Stopped on connector and lasted for ${formatDurationMilliSeconds( connectorStatus.stoppedDate.getTime() - (connectorStatus.startDate?.getTime() ?? 0) )}` ) logger.debug( - `${this.logPrefix(connectorId)} stopped with connector status: %j`, + `${this.logPrefix(connectorId)} ${moduleName}.internalStartConnector: Stopped with connector status: %j`, connectorStatus ) this.chargingStation.emitChargingStationEvent(ChargingStationEvents.updated) @@ -410,7 +429,7 @@ export class AutomaticTransactionGenerator { ) const startTransactionLogMsg = `${this.logPrefix( connectorId - )} start transaction with an idTag '${idTag}'` + )} ${moduleName}.startTransaction: Start transaction with an idTag '${idTag}'` if (this.getRequireAuthorize()) { const connectorStatus = this.connectorsStatus.get(connectorId) if (connectorStatus != null) { @@ -438,7 +457,9 @@ export class AutomaticTransactionGenerator { PerformanceStatistics.endMeasure(measureId, beginId) return result } - logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`) + logger.info( + `${this.logPrefix(connectorId)} ${moduleName}.startTransaction: Start transaction without an idTag` + ) result = await startTransactionOnConnector(this.chargingStation, connectorId) this.handleStartTransactionResult(connectorId, result) PerformanceStatistics.endMeasure(measureId, beginId) @@ -461,7 +482,7 @@ export class AutomaticTransactionGenerator { if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) { logger.info( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation + `${this.logPrefix(connectorId)} ${moduleName}.stopTransaction: Stop transaction with id ${this.chargingStation .getConnectorStatus(connectorId) ?.transactionId?.toString()}` ) @@ -478,7 +499,7 @@ export class AutomaticTransactionGenerator { } else { const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId logger.debug( - `${this.logPrefix(connectorId)} stopping a not started transaction${ + `${this.logPrefix(connectorId)} ${moduleName}.stopTransaction: Stopping a not started transaction${ transactionId != null ? ` with id ${transactionId.toString()}` : '' }` ) @@ -494,7 +515,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} transaction loop waiting for charging station to be available` + )} ${moduleName}.waitChargingStationAvailable: Transaction loop waiting for charging station to be available` ) logged = true } @@ -509,7 +530,7 @@ export class AutomaticTransactionGenerator { logger.info( `${this.logPrefix( connectorId - )} transaction loop waiting for connector ${connectorId.toString()} to be available` + )} ${moduleName}.waitConnectorAvailable: Transaction loop waiting for connector ${connectorId.toString()} to be available` ) logged = true } @@ -524,7 +545,7 @@ export class AutomaticTransactionGenerator { if (!logged) { logger.info( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix(connectorId)} transaction loop waiting for started transaction ${connectorStatus.transactionId?.toString()} on connector ${connectorId.toString()} to be stopped` + `${this.logPrefix(connectorId)} ${moduleName}.waitRunningTransactionStopped: Transaction loop waiting for started transaction ${connectorStatus.transactionId?.toString()} on connector ${connectorId.toString()} to be stopped` ) logged = true } diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index c9408cf0..14eb79ab 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -646,7 +646,10 @@ export class Bootstrap extends EventEmitter implements IBootstrap { performanceStatistics: Statistics ) => Promise )(data).catch((error: unknown) => { - logger.error(`${this.logPrefix()} Error while storing performance statistics:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.workerEventPerformanceStatistics: Error while storing performance statistics:`, + error + ) }) } else { ;(this.storage?.storePerformanceStatistics as (performanceStatistics: Statistics) => void)( diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index a17df487..64591099 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -160,6 +160,8 @@ import { } from './ocpp/index.js' import { SharedLRUCache } from './SharedLRUCache.js' +const moduleName = 'ChargingStation' + export class ChargingStation extends EventEmitter { public automaticTransactionGenerator?: AutomaticTransactionGenerator public bootNotificationRequest?: BootNotificationRequest @@ -261,7 +263,10 @@ export class ChargingStation extends EventEmitter { ? true : this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration ).catch((error: unknown) => { - logger.error(`${this.logPrefix()} Error while starting the message sequence:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.onAccepted: Error while starting the message sequence:`, + error + ) }) this.wsConnectionRetryCount = 0 }) @@ -278,7 +283,10 @@ export class ChargingStation extends EventEmitter { this.internalStopMessageSequence() } catch (error) { const e = ensureError(error) - logger.error(`${this.logPrefix()} Error while stopping the internal message sequence:`, e) + logger.error( + `${this.logPrefix()} ${moduleName}.onDisconnected: Error while stopping the internal message sequence:`, + e + ) } }) @@ -303,7 +311,7 @@ export class ChargingStation extends EventEmitter { const connectorStatus = this.getConnectorStatus(reservation.connectorId) if (connectorStatus == null) { logger.error( - `${this.logPrefix()} No connector ${reservation.connectorId.toString()} found during reservation ${reservation.reservationId.toString()} addition` + `${this.logPrefix()} ${moduleName}.addReservation: No connector ${reservation.connectorId.toString()} found during reservation ${reservation.reservationId.toString()} addition` ) return } @@ -347,7 +355,10 @@ export class ChargingStation extends EventEmitter { await this.stop() } catch (error) { const e = ensureError(error) - logger.error(`${this.logPrefix()} Error stopping station during delete:`, e) + logger.error( + `${this.logPrefix()} ${moduleName}.delete: Error stopping station during delete:`, + e + ) } } AutomaticTransactionGenerator.deleteInstance(this) @@ -358,10 +369,14 @@ export class ChargingStation extends EventEmitter { if (idTagsFile != null) { this.idTagsCache.deleteIdTags(idTagsFile) } else { - logger.warn(`${this.logPrefix()} No ID tags file found during deletion`) + logger.warn( + `${this.logPrefix()} ${moduleName}.delete: No ID tags file found during deletion` + ) } } else { - logger.warn(`${this.logPrefix()} No station info available during deletion`) + logger.warn( + `${this.logPrefix()} ${moduleName}.delete: No station info available during deletion` + ) } this.requests.clear() this.connectors.clear() @@ -374,7 +389,7 @@ export class ChargingStation extends EventEmitter { } catch (error) { const e = ensureError(error) logger.error( - `${this.logPrefix()} Failed to delete configuration file ${this.configurationFile}:`, + `${this.logPrefix()} ${moduleName}.delete: Failed to delete configuration file ${this.configurationFile}:`, e ) } @@ -506,7 +521,7 @@ export class ChargingStation extends EventEmitter { const maximumPower = this.stationInfo?.maximumPower if (maximumPower == null || maximumPower <= 0) { logger.error( - `${this.logPrefix()} getConnectorMaximumAvailablePower: maximumPower is ${ + `${this.logPrefix()} ${moduleName}.getConnectorMaximumAvailablePower: maximumPower is ${ maximumPower?.toString() ?? 'undefined' }, cannot compute connector maximum power` ) @@ -606,7 +621,7 @@ export class ChargingStation extends EventEmitter { } this.stationInfo?.autoRegister === false && logger.warn( - `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL_MS.toString()}` + `${this.logPrefix()} ${moduleName}.getHeartbeatInterval: Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL_MS.toString()}` ) return Constants.DEFAULT_HEARTBEAT_INTERVAL_MS } @@ -798,19 +813,21 @@ export class ChargingStation extends EventEmitter { public lockConnector (connectorId: number): void { if (connectorId === 0) { - logger.warn(`${this.logPrefix()} lockConnector: connector id 0 is not a physical connector`) + logger.warn( + `${this.logPrefix()} ${moduleName}.lockConnector: connector id 0 is not a physical connector` + ) return } if (!this.hasConnector(connectorId)) { logger.warn( - `${this.logPrefix()} lockConnector: connector id ${connectorId.toString()} does not exist` + `${this.logPrefix()} ${moduleName}.lockConnector: connector id ${connectorId.toString()} does not exist` ) return } const connectorStatus = this.getConnectorStatus(connectorId) if (connectorStatus == null) { logger.warn( - `${this.logPrefix()} lockConnector: connector id ${connectorId.toString()} status is null` + `${this.logPrefix()} ${moduleName}.lockConnector: connector id ${connectorId.toString()} status is null` ) return } @@ -865,7 +882,7 @@ export class ChargingStation extends EventEmitter { if (this.stationInfo?.supervisionUser != null && this.stationInfo.supervisionPassword != null) { if (this.stationInfo.supervisionUser.includes(':')) { logger.warn( - `${this.logPrefix()} Supervision user contains ':' which is invalid in HTTP Basic Auth (RFC 7617) — skipping auth` + `${this.logPrefix()} ${moduleName}.openWSConnection: Supervision user contains ':' which is invalid in HTTP Basic Auth (RFC 7617) — skipping auth` ) } else { options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}` @@ -880,12 +897,14 @@ export class ChargingStation extends EventEmitter { if (this.isWebSocketConnectionOpened()) { logger.warn( - `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.href} is already opened` + `${this.logPrefix()} ${moduleName}.openWSConnection: OCPP connection to URL ${this.wsConnectionUrl.href} is already opened` ) return } - logger.info(`${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.href}`) + logger.info( + `${this.logPrefix()} ${moduleName}.openWSConnection: Open OCPP connection to URL ${this.wsConnectionUrl.href}` + ) this.wsConnection = new WebSocket( this.wsConnectionUrl, @@ -897,7 +916,10 @@ export class ChargingStation extends EventEmitter { // Handle WebSocket message this.wsConnection.on('message', data => { this.onMessage(data).catch((error: unknown) => - logger.error(`${this.logPrefix()} Error while processing WebSocket message:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.openWSConnection: Error while processing WebSocket message:`, + error + ) ) }) // Handle WebSocket error @@ -907,7 +929,10 @@ export class ChargingStation extends EventEmitter { // Handle WebSocket open this.wsConnection.on('open', () => { this.onOpen().catch((error: unknown) => - logger.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.openWSConnection: Error while opening WebSocket connection:`, + error + ) ) }) // Handle WebSocket ping @@ -928,7 +953,7 @@ export class ChargingStation extends EventEmitter { const connectorStatus = this.getConnectorStatus(reservation.connectorId) if (connectorStatus == null) { logger.error( - `${this.logPrefix()} Trying to remove reservation on non-existent connector id ${reservation.connectorId.toString()}` + `${this.logPrefix()} ${moduleName}.removeReservation: Trying to remove reservation on non-existent connector id ${reservation.connectorId.toString()}` ) return } @@ -966,7 +991,7 @@ export class ChargingStation extends EventEmitter { await this.stop(reason, graceful ? this.stationInfo?.stopTransactionsOnStopped : false) } catch (error) { const e = ensureError(error) - logger.error(`${this.logPrefix()} Error during reset stop phase:`, e) + logger.error(`${this.logPrefix()} ${moduleName}.reset: Error during reset stop phase:`, e) return } await sleep(this.stationInfo?.resetTime ?? 0) @@ -1049,9 +1074,9 @@ export class ChargingStation extends EventEmitter { if (isNotEmptyString(filename) && event === 'change') { try { logger.debug( - `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ + `${this.logPrefix()} ${moduleName}.start: ${FileType.ChargingStationTemplate} ${ this.templateFile - } file have changed, reload` + } file has changed, reloading` ) this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash) const idTagsFile = @@ -1084,7 +1109,7 @@ export class ChargingStation extends EventEmitter { } catch (error) { const e = ensureError(error) logger.error( - `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`, + `${this.logPrefix()} ${moduleName}.start: ${FileType.ChargingStationTemplate} file monitoring error:`, e ) } @@ -1097,10 +1122,10 @@ export class ChargingStation extends EventEmitter { this.starting = false } } else { - logger.warn(`${this.logPrefix()} Charging station is already starting...`) + logger.warn(`${this.logPrefix()} ${moduleName}.start: Already starting`) } } else { - logger.warn(`${this.logPrefix()} Charging station is already started...`) + logger.warn(`${this.logPrefix()} ${moduleName}.start: Already started`) } } @@ -1134,25 +1159,25 @@ export class ChargingStation extends EventEmitter { .requestHandler(this, RequestCommand.HEARTBEAT) .catch((error: unknown) => { logger.error( - `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`, + `${this.logPrefix()} ${moduleName}.startHeartbeat: Error while sending '${RequestCommand.HEARTBEAT}':`, error ) }) }, clampToSafeTimerValue(heartbeatInterval)) logger.info( - `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds( + `${this.logPrefix()} ${moduleName}.startHeartbeat: Heartbeat started every ${formatDurationMilliSeconds( heartbeatInterval )}` ) } else if (this.heartbeatSetInterval != null) { logger.info( - `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds( + `${this.logPrefix()} ${moduleName}.startHeartbeat: Heartbeat already started every ${formatDurationMilliSeconds( heartbeatInterval )}` ) } else { logger.error( - `${this.logPrefix()} Heartbeat interval set to ${heartbeatInterval.toString()}, not starting the heartbeat` + `${this.logPrefix()} ${moduleName}.startHeartbeat: Heartbeat interval set to ${heartbeatInterval.toString()}, not starting the heartbeat` ) } } @@ -1177,7 +1202,10 @@ export class ChargingStation extends EventEmitter { `Timeout ${formatDurationMilliSeconds(Constants.STOP_MESSAGE_SEQUENCE_TIMEOUT_MS)} reached at stopping message sequence` ) } catch (error: unknown) { - logger.error(`${this.logPrefix()} Error while stopping message sequence:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.stop: Error while stopping message sequence:`, + error + ) } this.ocppIncomingRequestService.stop(this) this.closeWSConnection() @@ -1194,10 +1222,10 @@ export class ChargingStation extends EventEmitter { this.stopping = false } } else { - logger.warn(`${this.logPrefix()} Charging station is already stopping...`) + logger.warn(`${this.logPrefix()} ${moduleName}.stop: Already stopping`) } } else { - logger.warn(`${this.logPrefix()} Charging station is already stopped...`) + logger.warn(`${this.logPrefix()} ${moduleName}.stop: Already stopped`) } } @@ -1219,19 +1247,21 @@ export class ChargingStation extends EventEmitter { public unlockConnector (connectorId: number): void { if (connectorId === 0) { - logger.warn(`${this.logPrefix()} unlockConnector: connector id 0 is not a physical connector`) + logger.warn( + `${this.logPrefix()} ${moduleName}.unlockConnector: connector id 0 is not a physical connector` + ) return } if (!this.hasConnector(connectorId)) { logger.warn( - `${this.logPrefix()} unlockConnector: connector id ${connectorId.toString()} does not exist` + `${this.logPrefix()} ${moduleName}.unlockConnector: connector id ${connectorId.toString()} does not exist` ) return } const connectorStatus = this.getConnectorStatus(connectorId) if (connectorStatus == null) { logger.warn( - `${this.logPrefix()} unlockConnector: connector id ${connectorId.toString()} status is null` + `${this.logPrefix()} ${moduleName}.unlockConnector: connector id ${connectorId.toString()} status is null` ) return } @@ -1315,7 +1345,7 @@ export class ChargingStation extends EventEmitter { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (configuration == null || isEmpty(configuration)) { logger.error( - `${this.logPrefix()} Invalid charging station configuration file ${ + `${this.logPrefix()} ${moduleName}.getConfigurationFromFile: Invalid charging station configuration file ${ this.configurationFile }` ) @@ -1323,7 +1353,7 @@ export class ChargingStation extends EventEmitter { } if (!isNotEmptyString(configuration.configurationHash)) { logger.error( - `${this.logPrefix()} Missing charging station configuration hash in file ${ + `${this.logPrefix()} ${moduleName}.getConfigurationFromFile: Missing charging station configuration hash in file ${ this.configurationFile }` ) @@ -1344,7 +1374,7 @@ export class ChargingStation extends EventEmitter { this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash) ) { logger.warn( - `${this.logPrefix()} Using cached charging station configuration due to file read error` + `${this.logPrefix()} ${moduleName}.getConfigurationFromFile: Using cached charging station configuration due to file read error` ) return this.sharedLRUCache.getChargingStationConfiguration(this.configurationFileHash) } @@ -1372,7 +1402,7 @@ export class ChargingStation extends EventEmitter { ) { logger.warn( // eslint-disable-next-line @typescript-eslint/no-base-to-string - `${this.logPrefix()} Unknown supervision url distribution '${supervisionUrlDistribution}' in configuration from values '${SupervisionUrlDistribution.toString()}', defaulting to '${ + `${this.logPrefix()} ${moduleName}.getConfiguredSupervisionUrl: Unknown supervision url distribution '${supervisionUrlDistribution}' in configuration from values '${SupervisionUrlDistribution.toString()}', defaulting to '${ SupervisionUrlDistribution.CHARGING_STATION_AFFINITY }'` ) @@ -1389,7 +1419,7 @@ export class ChargingStation extends EventEmitter { return new URL(configuredSupervisionUrl) } const errorMsg = 'No supervision url(s) configured' - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.getConfiguredSupervisionUrl: ${errorMsg}`) throw new BaseError(errorMsg) } @@ -1428,7 +1458,7 @@ export class ChargingStation extends EventEmitter { const maximumPower = localStationInfo?.maximumPower if (maximumPower == null || maximumPower <= 0) { logger.error( - `${this.logPrefix()} getMaximumAmperage: maximumPower is ${ + `${this.logPrefix()} ${moduleName}.getMaximumAmperage: maximumPower is ${ maximumPower?.toString() ?? 'undefined' }, cannot compute maximum amperage` ) @@ -1568,7 +1598,7 @@ export class ChargingStation extends EventEmitter { const stationTemplate = this.getTemplateFromFile() if (stationTemplate == null) { const errorMsg = `Failed to read charging station template file ${this.templateFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.getStationInfoFromTemplate: ${errorMsg}`) throw new BaseError(errorMsg) } checkTemplate(stationTemplate, this.logPrefix(), this.templateFile) @@ -1604,7 +1634,7 @@ export class ChargingStation extends EventEmitter { !new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion) ) { logger.warn( - `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${ + `${this.logPrefix()} ${moduleName}.getStationInfoFromTemplate: Firmware version '${stationInfo.firmwareVersion}' in template file ${ this.templateFile } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'` ) @@ -1672,7 +1702,7 @@ export class ChargingStation extends EventEmitter { } const [, errorCallback, requestCommandName] = cachedRequest logger.debug( - `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify( + `${this.logPrefix()} ${moduleName}.handleErrorMessage: << Command '${requestCommandName}' received error response payload: ${JSON.stringify( errorResponse )}` ) @@ -1693,7 +1723,7 @@ export class ChargingStation extends EventEmitter { this.performanceStatistics?.addRequestStatistic(commandName, messageType) } logger.debug( - `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( + `${this.logPrefix()} ${moduleName}.handleIncomingMessage: << Command '${commandName}' received request payload: ${JSON.stringify( request )}` ) @@ -1730,7 +1760,7 @@ export class ChargingStation extends EventEmitter { } const [responseCallback, , requestCommandName, requestPayload] = cachedRequest logger.debug( - `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify( + `${this.logPrefix()} ${moduleName}.handleResponseMessage: << Command '${requestCommandName}' received response payload: ${JSON.stringify( response )}` ) @@ -1740,7 +1770,7 @@ export class ChargingStation extends EventEmitter { private handleUnsupportedVersion (version: OCPPVersion | undefined): void { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions const errorMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.handleUnsupportedVersion: ${errorMsg}`) throw new BaseError(errorMsg) } @@ -1748,7 +1778,7 @@ export class ChargingStation extends EventEmitter { const stationTemplate = this.getTemplateFromFile() if (stationTemplate == null) { const errorMsg = `Failed to read charging station template file ${this.templateFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.initialize: ${errorMsg}`) throw new BaseError(errorMsg) } checkTemplate(stationTemplate, this.logPrefix(), this.templateFile) @@ -1800,7 +1830,7 @@ export class ChargingStation extends EventEmitter { const bootNotificationRequest = buildBootNotificationRequest(this.stationInfo) if (bootNotificationRequest == null) { const errorMsg = 'Error while creating boot notification request' - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.initialize: ${errorMsg}`) throw new BaseError(errorMsg) } this.bootNotificationRequest = bootNotificationRequest @@ -1822,12 +1852,14 @@ export class ChargingStation extends EventEmitter { private initializeConnectorsFromTemplate (stationTemplate: ChargingStationTemplate): void { if (stationTemplate.Connectors == null && isEmpty(this.connectors)) { const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error( + `${this.logPrefix()} ${moduleName}.initializeConnectorsFromTemplate: ${errorMsg}` + ) throw new BaseError(errorMsg) } if (stationTemplate.Connectors?.[0] == null) { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeConnectorsFromTemplate: Charging station information from template ${ this.templateFile } with no connector id 0 configuration` ) @@ -1872,7 +1904,7 @@ export class ChargingStation extends EventEmitter { this.saveConnectorsStatus() } else { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeConnectorsFromTemplate: Charging station information from template ${ this.templateFile } with no connectors configuration defined, cannot create connectors` ) @@ -1880,7 +1912,7 @@ export class ChargingStation extends EventEmitter { } } else { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeConnectorsFromTemplate: Charging station information from template ${ this.templateFile } with no connectors configuration defined, using already defined connectors` ) @@ -1934,11 +1966,15 @@ export class ChargingStation extends EventEmitter { } } else if (configuration.evsesStatus != null && configuration.connectorsStatus != null) { const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error( + `${this.logPrefix()} ${moduleName}.initializeConnectorsOrEvsesFromFile: ${errorMsg}` + ) throw new BaseError(errorMsg) } else { const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error( + `${this.logPrefix()} ${moduleName}.initializeConnectorsOrEvsesFromFile: ${errorMsg}` + ) throw new BaseError(errorMsg) } } @@ -1950,11 +1986,15 @@ export class ChargingStation extends EventEmitter { this.initializeEvsesFromTemplate(stationTemplate) } else if (stationTemplate.Evses != null && stationTemplate.Connectors != null) { const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error( + `${this.logPrefix()} ${moduleName}.initializeConnectorsOrEvsesFromTemplate: ${errorMsg}` + ) throw new BaseError(errorMsg) } else { const errorMsg = `No connectors or evses defined in template file ${this.templateFile}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error( + `${this.logPrefix()} ${moduleName}.initializeConnectorsOrEvsesFromTemplate: ${errorMsg}` + ) throw new BaseError(errorMsg) } } @@ -1962,26 +2002,26 @@ export class ChargingStation extends EventEmitter { private initializeEvsesFromTemplate (stationTemplate: ChargingStationTemplate): void { if (stationTemplate.Evses == null && isEmpty(this.evses)) { const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: ${errorMsg}`) throw new BaseError(errorMsg) } if (stationTemplate.Evses?.[0] == null) { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: Charging station information from template ${ this.templateFile } with no evse id 0 configuration` ) } if (stationTemplate.Evses?.[0]?.Connectors[0] == null) { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: Charging station information from template ${ this.templateFile } with evse id 0 with no connector id 0 configuration` ) } if (Object.keys(stationTemplate.Evses?.[0]?.Connectors as object).length > 1) { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: Charging station information from template ${ this.templateFile } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used` ) @@ -2015,7 +2055,7 @@ export class ChargingStation extends EventEmitter { this.saveEvsesStatus() } else { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: Charging station information from template ${ this.templateFile } with no evses configuration defined, cannot create evses` ) @@ -2023,7 +2063,7 @@ export class ChargingStation extends EventEmitter { } } else { logger.warn( - `${this.logPrefix()} Charging station information from template ${ + `${this.logPrefix()} ${moduleName}.initializeEvsesFromTemplate: Charging station information from template ${ this.templateFile } with no evses configuration defined, using already defined evses` ) @@ -2113,7 +2153,7 @@ export class ChargingStation extends EventEmitter { ) } else { logger.error( - `${this.logPrefix()} initializeOcppConfiguration: maximumAmperage is ${ + `${this.logPrefix()} ${moduleName}.initializeOcppConfiguration: maximumAmperage is ${ maximumAmperage?.toString() ?? 'undefined' }, cannot set amperage limitation configuration key` ) @@ -2210,7 +2250,7 @@ export class ChargingStation extends EventEmitter { case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: case WebSocketCloseEventStatusCode.CLOSE_NORMAL: logger.info( - `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString( + `${this.logPrefix()} ${moduleName}.onClose: WebSocket normally closed with status '${getWebSocketCloseEventStatusString( code )}' and reason '${reason.toString()}'` ) @@ -2219,7 +2259,7 @@ export class ChargingStation extends EventEmitter { // Abnormal close default: logger.error( - `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString( + `${this.logPrefix()} ${moduleName}.onClose: WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString( code )}' and reason '${reason.toString()}'` ) @@ -2230,7 +2270,10 @@ export class ChargingStation extends EventEmitter { return undefined }) .catch((error: unknown) => - logger.error(`${this.logPrefix()} Error while reconnecting:`, error) + logger.error( + `${this.logPrefix()} ${moduleName}.onClose: Error while reconnecting:`, + error + ) ) break } @@ -2238,7 +2281,7 @@ export class ChargingStation extends EventEmitter { private onError (error: WSError): void { this.closeWSConnection() - logger.error(`${this.logPrefix()} WebSocket error:`, error) + logger.error(`${this.logPrefix()} ${moduleName}.onError: WebSocket error:`, error) } private async onMessage (data: RawData): Promise { @@ -2268,7 +2311,7 @@ export class ChargingStation extends EventEmitter { default: // eslint-disable-next-line @typescript-eslint/restrict-template-expressions errorMsg = `Wrong message type ${messageType}` - logger.error(`${this.logPrefix()} ${errorMsg}`) + logger.error(`${this.logPrefix()} ${moduleName}.onMessage: ${errorMsg}`) throw new OCPPError( this.stationInfo?.ocppVersion !== OCPPVersion.VERSION_16 ? ErrorType.MESSAGE_TYPE_NOT_SUPPORTED @@ -2289,8 +2332,11 @@ export class ChargingStation extends EventEmitter { } catch (error) { if (!Array.isArray(request)) { const e = ensureError(error) - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - logger.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, e) + logger.error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${this.logPrefix()} ${moduleName}.onMessage: Incoming message '${request}' parsing error:`, + e + ) // OCPP 2.0.1 §4.2.3: respond with CALLERROR using messageId "-1" if (this.stationInfo?.ocppVersion !== OCPPVersion.VERSION_16) { await this.ocppRequestService @@ -2308,7 +2354,7 @@ export class ChargingStation extends EventEmitter { ) .catch((sendError: unknown) => { logger.error( - `${this.logPrefix()} Error sending RpcFrameworkError CALLERROR:`, + `${this.logPrefix()} ${moduleName}.onMessage: Error sending RpcFrameworkError CALLERROR:`, sendError ) }) @@ -2346,7 +2392,7 @@ export class ChargingStation extends EventEmitter { } if (!(error instanceof OCPPError)) { logger.warn( - `${this.logPrefix()} Error thrown at incoming OCPP command ${ + `${this.logPrefix()} ${moduleName}.onMessage: Error thrown at incoming OCPP command ${ commandName ?? requestCommandName ?? OCPPConstants.UNKNOWN_OCPP_COMMAND // eslint-disable-next-line @typescript-eslint/no-base-to-string } message '${data.toString()}' handling is not an OCPPError:`, @@ -2354,7 +2400,7 @@ export class ChargingStation extends EventEmitter { ) } logger.error( - `${this.logPrefix()} Incoming OCPP command '${ + `${this.logPrefix()} ${moduleName}.onMessage: Incoming OCPP command '${ commandName ?? requestCommandName ?? OCPPConstants.UNKNOWN_OCPP_COMMAND // eslint-disable-next-line @typescript-eslint/no-base-to-string }' message '${data.toString()}'${ @@ -2374,7 +2420,7 @@ export class ChargingStation extends EventEmitter { this.emitChargingStationEvent(ChargingStationEvents.connected) this.emitChargingStationEvent(ChargingStationEvents.updated) logger.info( - `${this.logPrefix()} Connection to OCPP server through ${ + `${this.logPrefix()} ${moduleName}.onOpen: Connection to OCPP server through ${ this.wsConnectionUrl.href } succeeded` ) @@ -2414,7 +2460,7 @@ export class ChargingStation extends EventEmitter { if (!this.inAcceptedState()) { logger.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount.toString()}) or retry disabled (${this.stationInfo?.registrationMaxRetries?.toString()})` + `${this.logPrefix()} ${moduleName}.onOpen: Registration failure: maximum retries reached (${registrationRetryCount.toString()}) or retry disabled (${this.stationInfo?.registrationMaxRetries?.toString()})` ) } else { await flushQueuedTransactionMessages(this) @@ -2422,17 +2468,21 @@ export class ChargingStation extends EventEmitter { this.emitChargingStationEvent(ChargingStationEvents.updated) } else { logger.warn( - `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} failed` + `${this.logPrefix()} ${moduleName}.onOpen: Connection to OCPP server through ${this.wsConnectionUrl.href} failed` ) } } private onPing (): void { - logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`) + logger.debug( + `${this.logPrefix()} ${moduleName}.onPing: Received a WS ping (rfc6455) from the server` + ) } private onPong (): void { - logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`) + logger.debug( + `${this.logPrefix()} ${moduleName}.onPong: Received a WS pong (rfc6455) from the server` + ) } private async reconnect (): Promise { @@ -2447,11 +2497,11 @@ export class ChargingStation extends EventEmitter { ? reconnectDelay - Constants.DEFAULT_WS_RECONNECT_TIMEOUT_OFFSET_MS : 0 logger.error( - `${this.logPrefix()} WebSocket connection retry in ${formatDurationMilliSeconds(reconnectDelay)}, timeout ${formatDurationMilliSeconds(reconnectTimeout)}` + `${this.logPrefix()} ${moduleName}.reconnect: WebSocket connection retry in ${formatDurationMilliSeconds(reconnectDelay)}, timeout ${formatDurationMilliSeconds(reconnectTimeout)}` ) await sleep(reconnectDelay) logger.error( - `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}` + `${this.logPrefix()} ${moduleName}.reconnect: WebSocket connection retry #${this.wsConnectionRetryCount.toString()}` ) this.openWSConnection( { @@ -2462,7 +2512,7 @@ export class ChargingStation extends EventEmitter { } else if (this.stationInfo?.autoReconnectMaxRetries !== -1) { logger.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${this.wsConnectionRetryCount.toString()}) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries?.toString()})` + `${this.logPrefix()} ${moduleName}.reconnect: WebSocket connection retries failure: maximum retries reached (${this.wsConnectionRetryCount.toString()}) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries?.toString()})` ) } } @@ -2554,7 +2604,7 @@ export class ChargingStation extends EventEmitter { }) } else { logger.debug( - `${this.logPrefix()} Not saving unchanged charging station configuration file ${ + `${this.logPrefix()} ${moduleName}.saveConfiguration: Not saving unchanged charging station configuration file ${ this.configurationFile }` ) @@ -2569,7 +2619,7 @@ export class ChargingStation extends EventEmitter { } } else { logger.error( - `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` + `${this.logPrefix()} ${moduleName}.saveConfiguration: Trying to save charging station configuration to undefined configuration file` ) } } @@ -2602,7 +2652,7 @@ export class ChargingStation extends EventEmitter { parsedMessage = JSON.parse(message) as ErrorResponse | OutgoingRequest | Response } catch (error) { logger.error( - `${this.logPrefix()} Error while parsing buffered OCPP message '${message}' to JSON:`, + `${this.logPrefix()} ${moduleName}.sendMessageBuffer: Error while parsing buffered OCPP message '${message}' to JSON:`, error ) this.messageQueue.shift() @@ -2621,12 +2671,12 @@ export class ChargingStation extends EventEmitter { } if (error == null) { logger.debug( - `${this.logPrefix()} >> Buffered ${getMessageTypeString(messageType)} OCPP message sent '${message}'` + `${this.logPrefix()} ${moduleName}.sendMessageBuffer: >> Buffered ${getMessageTypeString(messageType)} OCPP message sent '${message}'` ) this.messageQueue.shift() } else { logger.error( - `${this.logPrefix()} Error while sending buffered ${getMessageTypeString(messageType)} OCPP message '${message}':`, + `${this.logPrefix()} ${moduleName}.sendMessageBuffer: Error while sending buffered ${getMessageTypeString(messageType)} OCPP message '${message}':`, error ) } @@ -2719,19 +2769,19 @@ export class ChargingStation extends EventEmitter { clampToSafeTimerValue(secondsToMilliseconds(webSocketPingInterval)) ) logger.info( - `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds( + `${this.logPrefix()} ${moduleName}.startWebSocketPing: WebSocket ping started every ${formatDurationSeconds( webSocketPingInterval )}` ) } else if (this.wsPingSetInterval != null) { logger.info( - `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds( + `${this.logPrefix()} ${moduleName}.startWebSocketPing: WebSocket ping already started every ${formatDurationSeconds( webSocketPingInterval )}` ) } else { logger.error( - `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval.toString()}, not starting the WebSocket ping` + `${this.logPrefix()} ${moduleName}.startWebSocketPing: WebSocket ping interval set to ${webSocketPingInterval.toString()}, not starting the WebSocket ping` ) } } diff --git a/src/charging-station/ConfigurationKeyUtils.ts b/src/charging-station/ConfigurationKeyUtils.ts index 3d1080c3..7ef6cb93 100644 --- a/src/charging-station/ConfigurationKeyUtils.ts +++ b/src/charging-station/ConfigurationKeyUtils.ts @@ -272,7 +272,7 @@ export const setConfigurationKeyValue = ( return keyFound } logger.error( - `${chargingStation.logPrefix()} Trying to set a value on a non existing configuration key: %j`, + `${chargingStation.logPrefix()} Trying to set a value on a non-existent configuration key: %j`, { key, value } ) return undefined diff --git a/src/charging-station/Helpers.ts b/src/charging-station/Helpers.ts index e75341e5..568927da 100644 --- a/src/charging-station/Helpers.ts +++ b/src/charging-station/Helpers.ts @@ -257,7 +257,9 @@ export const checkChargingStationState = ( logPrefix: string ): boolean => { if (!chargingStation.started && !chargingStation.starting) { - logger.warn(`${logPrefix} charging station is stopped, cannot proceed`) + logger.warn( + `${logPrefix} ${moduleName}.checkChargingStationState: Charging station is stopped, cannot proceed` + ) return false } return true @@ -324,17 +326,17 @@ export const checkTemplate = ( ): void => { if (stationTemplate == null) { const errorMsg = `Failed to read charging station template file ${templateFile}` - logger.error(`${logPrefix} ${errorMsg}`) + logger.error(`${logPrefix} ${moduleName}.checkTemplate: ${errorMsg}`) throw new BaseError(errorMsg) } if (isEmpty(stationTemplate)) { const errorMsg = `Empty charging station information from template file ${templateFile}` - logger.error(`${logPrefix} ${errorMsg}`) + logger.error(`${logPrefix} ${moduleName}.checkTemplate: ${errorMsg}`) throw new BaseError(errorMsg) } if (stationTemplate.idTagsFile == null || isEmpty(stationTemplate.idTagsFile)) { logger.warn( - `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator` + `${logPrefix} ${moduleName}.checkTemplate: Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator` ) } } @@ -346,12 +348,12 @@ export const checkConfiguration = ( ): void => { if (stationConfiguration == null) { const errorMsg = `Failed to read charging station configuration file ${configurationFile}` - logger.error(`${logPrefix} ${errorMsg}`) + logger.error(`${logPrefix} ${moduleName}.checkConfiguration: ${errorMsg}`) throw new BaseError(errorMsg) } if (isEmpty(stationConfiguration)) { const errorMsg = `Empty charging station configuration from file ${configurationFile}` - logger.error(`${logPrefix} ${errorMsg}`) + logger.error(`${logPrefix} ${moduleName}.checkConfiguration: ${errorMsg}`) throw new BaseError(errorMsg) } } @@ -376,7 +378,7 @@ export const checkConnectorsConfiguration = ( stationTemplate.randomConnectors !== true ) { logger.warn( - `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation` + `${logPrefix} ${moduleName}.checkConnectorsConfiguration: Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation` ) stationTemplate.randomConnectors = true } @@ -426,7 +428,7 @@ export const checkStationInfoConnectorStatus = ( ): void => { if (connectorStatus.status != null) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId.toString()} status configuration defined, undefine it` + `${logPrefix} ${moduleName}.checkStationInfoConnectorStatus: Charging station information from template ${templateFile} with connector id ${connectorId.toString()} status configuration defined, removing it` ) delete connectorStatus.status } @@ -492,7 +494,7 @@ export const buildConnectorsMap = ( } } else { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map` + `${logPrefix} ${moduleName}.buildConnectorsMap: Charging station information from template ${templateFile} with no connectors, cannot build connectors map` ) } return connectorsMap @@ -506,7 +508,7 @@ export const initializeConnectorsMapStatus = ( if (connectorId > 0 && connectorStatus.transactionStarted === true) { logger.warn( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${logPrefix} Connector id ${connectorId.toString()} at initialization has a transaction started with id ${connectorStatus.transactionId?.toString()}` + `${logPrefix} ${moduleName}.initializeConnectorsMapStatus: Connector id ${connectorId.toString()} at initialization has a transaction started with id ${connectorStatus.transactionId?.toString()}` ) } if (connectorId === 0) { @@ -860,7 +862,7 @@ export const getDefaultVoltageOut = ( defaultVoltageOut = Voltage.VOLTAGE_400 break default: - logger.error(`${logPrefix} ${errorMsg}`) + logger.error(`${logPrefix} ${moduleName}.getDefaultVoltageOut: ${errorMsg}`) throw new BaseError(errorMsg) } return defaultVoltageOut @@ -924,7 +926,7 @@ const checkConfiguredMaxConnectors = ( ): void => { if (configuredMaxConnectors <= 0) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors.toString()} connectors` + `${logPrefix} ${moduleName}.checkConfiguredMaxConnectors: Charging station information from template ${templateFile} with ${configuredMaxConnectors.toString()} connectors` ) } } @@ -936,11 +938,11 @@ const checkTemplateMaxConnectors = ( ): void => { if (templateMaxConnectors === 0) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration` + `${logPrefix} ${moduleName}.checkTemplateMaxConnectors: Charging station information from template ${templateFile} with empty connectors configuration` ) } else if (templateMaxConnectors < 0) { logger.error( - `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined` + `${logPrefix} ${moduleName}.checkTemplateMaxConnectors: Charging station information from template ${templateFile} with no connectors configuration defined` ) } } @@ -967,7 +969,7 @@ const warnDeprecatedTemplateKey = ( const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${ isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}` : '' }` - logger.warn(`${logPrefix} ${logMsg}`) + logger.warn(`${logPrefix} ${moduleName}.warnDeprecatedTemplateKey: ${logMsg}`) } } diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index bd3700b0..329fd3e1 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -721,7 +721,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const { connectorId, type } = commandPayload if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestChangeAvailability: Trying to change the availability of a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestChangeAvailability: Trying to change the availability of a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED } @@ -885,7 +885,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (connectorId != null) { if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestClearChargingProfile: Trying to clear a charging profile(s) to a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestClearChargingProfile: Trying to clear a charging profile(s) to a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN } @@ -971,7 +971,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const { chargingRateUnit, connectorId, duration } = commandPayload if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Trying to get composite schedule to a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Trying to get composite schedule to a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_RESPONSE_REJECTED } @@ -1384,7 +1384,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const { connectorId, idTag, reservationId } = commandPayload if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestReserveNow: Trying to reserve a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestReserveNow: Trying to reserve a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED } @@ -1579,7 +1579,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const { connectorId, csChargingProfiles } = commandPayload if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestSetChargingProfile: Trying to set charging profile(s) to a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestSetChargingProfile: Trying to set charging profile(s) to a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED } @@ -1678,7 +1678,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const { connectorId } = commandPayload if (!chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleRequestUnlockConnector: Trying to unlock a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleRequestUnlockConnector: Trying to unlock a non-existent connector id ${connectorId.toString()}` ) return OCPP16Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED } diff --git a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts index d4333032..444c5124 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts @@ -264,7 +264,7 @@ export class OCPP16ResponseService extends OCPPResponseService { const { connectorId } = requestPayload if (connectorId === 0 || !chargingStation.hasConnector(connectorId)) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleResponseStartTransaction: Trying to start a transaction on a non existing connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleResponseStartTransaction: Trying to start a transaction on a non-existent connector id ${connectorId.toString()}` ) return } @@ -486,7 +486,7 @@ export class OCPP16ResponseService extends OCPPResponseService { ) if (transactionConnectorId == null) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.handleResponseStopTransaction: Trying to stop a non existing transaction with id ${requestPayload.transactionId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.handleResponseStopTransaction: Trying to stop a non-existent transaction with id ${requestPayload.transactionId.toString()}` ) return } diff --git a/src/charging-station/ocpp/OCPPServiceOperations.ts b/src/charging-station/ocpp/OCPPServiceOperations.ts index 6f78b481..a2afb70d 100644 --- a/src/charging-station/ocpp/OCPPServiceOperations.ts +++ b/src/charging-station/ocpp/OCPPServiceOperations.ts @@ -21,6 +21,8 @@ import { OCPPAuthServiceFactory, } from './auth/index.js' +const moduleName = 'OCPPServiceOperations' + /** * Starts a transaction on a specific connector using the appropriate OCPP version handler. * @param chargingStation - Target charging station @@ -114,7 +116,7 @@ export const stopRunningTransactions = async ( default: logger.warn( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${chargingStation.logPrefix()} stopRunningTransactions: unsupported OCPP version ${chargingStation.stationInfo?.ocppVersion}, no transactions stopped` + `${chargingStation.logPrefix()} ${moduleName}.stopRunningTransactions: Unsupported OCPP version ${chargingStation.stationInfo?.ocppVersion}, no transactions stopped` ) } } @@ -141,7 +143,7 @@ export const startUpdatedMeterValues = ( default: logger.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `${chargingStation.logPrefix()} startUpdatedMeterValues: unsupported OCPP version ${chargingStation.stationInfo?.ocppVersion}` + `${chargingStation.logPrefix()} ${moduleName}.startUpdatedMeterValues: Unsupported OCPP version ${chargingStation.stationInfo?.ocppVersion}` ) } } @@ -185,7 +187,7 @@ export const flushQueuedTransactionMessages = async ( await OCPP20ServiceUtils.sendQueuedTransactionEvents(chargingStation, connectorId).catch( (error: unknown) => { logger.error( - `${chargingStation.logPrefix()} flushQueuedTransactionMessages: Error flushing queued TransactionEvents:`, + `${chargingStation.logPrefix()} ${moduleName}.flushQueuedTransactionMessages: Error flushing queued TransactionEvents:`, error ) } @@ -206,7 +208,7 @@ export const isIdTagAuthorized = async ( ): Promise => { try { logger.debug( - `${chargingStation.logPrefix()} Authorizing idTag '${truncateId(idTag)}' on connector ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.isIdTagAuthorized: Authorizing idTag '${truncateId(idTag)}' on connector ${connectorId.toString()}` ) const authService = OCPPAuthServiceFactory.getInstance(chargingStation) @@ -223,7 +225,7 @@ export const isIdTagAuthorized = async ( }) logger.debug( - `${chargingStation.logPrefix()} Authorization result for idTag '${truncateId(idTag)}': ${authResult.status} using ${authResult.method} method` + `${chargingStation.logPrefix()} ${moduleName}.isIdTagAuthorized: Authorization result for idTag '${truncateId(idTag)}': ${authResult.status} using ${authResult.method} method` ) if (authResult.status === AuthStatus.ACCEPTED) { @@ -247,7 +249,10 @@ export const isIdTagAuthorized = async ( return false } catch (error) { - logger.error(`${chargingStation.logPrefix()} Authorization failed`, error) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.isIdTagAuthorized: Authorization failed`, + error + ) return false } } diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index 4ec22802..eaefda7b 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -656,7 +656,9 @@ const buildPowerMeasurandValue = ( }, cannot calculate ${ powerTemplate.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER } measurand value` - logger.error(`${chargingStation.logPrefix()} ${errorMsg}`) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.buildPowerMeasurandValue: ${errorMsg}` + ) throw new OCPPError(ErrorType.INTERNAL_ERROR, errorMsg, RequestCommand.METER_VALUES) } } @@ -855,7 +857,9 @@ const buildCurrentMeasurandValue = ( }, cannot calculate ${ currentTemplate.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER } measurand value` - logger.error(`${chargingStation.logPrefix()} ${errorMsg}`) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.buildCurrentMeasurandValue: ${errorMsg}` + ) throw new OCPPError(ErrorType.INTERNAL_ERROR, errorMsg, RequestCommand.METER_VALUES) } } @@ -1295,13 +1299,17 @@ const checkMeasurandPowerDivider = ( const errorMsg = `MeterValues measurand ${ measurandType ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER }: powerDivider is undefined` - logger.error(`${chargingStation.logPrefix()} ${errorMsg}`) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.checkMeasurandPowerDivider: ${errorMsg}` + ) throw new OCPPError(ErrorType.INTERNAL_ERROR, errorMsg, RequestCommand.METER_VALUES) } else if (chargingStation.powerDivider <= 0) { const errorMsg = `MeterValues measurand ${ measurandType ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER - }: powerDivider have zero or below value ${chargingStation.powerDivider.toString()}` - logger.error(`${chargingStation.logPrefix()} ${errorMsg}`) + }: powerDivider has a value of zero or less ${chargingStation.powerDivider.toString()}` + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.checkMeasurandPowerDivider: ${errorMsg}` + ) throw new OCPPError(ErrorType.INTERNAL_ERROR, errorMsg, RequestCommand.METER_VALUES) } } @@ -1367,7 +1375,7 @@ export const getSampledValueTemplate = ( const onPhaseStr = phase != null ? `on phase ${phase} ` : '' if (!isMeasurandSupported(measurand)) { logger.warn( - `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.getSampledValueTemplate: Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` ) return } @@ -1376,7 +1384,7 @@ export const getSampledValueTemplate = ( getConfigurationKey(chargingStation, measurandsKey)?.value?.includes(measurand) === false ) { logger.debug( - `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()} not found in sampled data OCPP parameter` + `${chargingStation.logPrefix()} ${moduleName}.getSampledValueTemplate: Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()} not found in sampled data OCPP parameter` ) return } @@ -1410,7 +1418,7 @@ export const getSampledValueTemplate = ( ) ) { logger.warn( - `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.getSampledValueTemplate: Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` ) } else if ( phase != null && @@ -1436,11 +1444,13 @@ export const getSampledValueTemplate = ( } if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { const errorMsg = `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId.toString()}` - logger.error(`${chargingStation.logPrefix()} ${errorMsg}`) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.getSampledValueTemplate: ${errorMsg}` + ) throw new BaseError(errorMsg) } logger.debug( - `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.getSampledValueTemplate: No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId.toString()}` ) } @@ -1644,7 +1654,7 @@ export function isConnectorIdValid ( ): boolean { if (connectorId < 0) { logger.error( - `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} ${moduleName}.isConnectorIdValid: ${ocppCommand} incoming request received with invalid connector id ${connectorId.toString()}` ) return false } @@ -1673,7 +1683,9 @@ export function isIncomingRequestCommandSupported ( ) { return chargingStation.stationInfo.commandsSupport.incomingCommands[command] } - logger.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`) + logger.warn( + `${chargingStation.logPrefix()} ${moduleName}.isIncomingRequestCommandSupported: Unknown incoming OCPP command '${command}'` + ) return false } @@ -1697,8 +1709,8 @@ export function isMessageTriggerSupported ( ) { return chargingStation.stationInfo.messageTriggerSupport[messageTrigger] } - logger.error( - `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'` + logger.warn( + `${chargingStation.logPrefix()} ${moduleName}.isMessageTriggerSupported: Unknown incoming OCPP message trigger '${messageTrigger}'` ) return false } @@ -1721,7 +1733,9 @@ export function isRequestCommandSupported ( ) { return chargingStation.stationInfo.commandsSupport.outgoingCommands[command] } - logger.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`) + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.isRequestCommandSupported: Unknown outgoing OCPP command '${command}'` + ) return false } diff --git a/src/charging-station/ocpp/auth/strategies/LocalAuthStrategy.ts b/src/charging-station/ocpp/auth/strategies/LocalAuthStrategy.ts index 669a572b..28c85c88 100644 --- a/src/charging-station/ocpp/auth/strategies/LocalAuthStrategy.ts +++ b/src/charging-station/ocpp/auth/strategies/LocalAuthStrategy.ts @@ -190,7 +190,7 @@ export class LocalAuthStrategy implements AuthStrategy { * Cleanup strategy resources */ public cleanup (): void { - logger.info(`${moduleName}: Cleaning up...`) + logger.info(`${moduleName}: Cleaning up`) // Reset internal state this.isInitialized = false @@ -245,7 +245,7 @@ export class LocalAuthStrategy implements AuthStrategy { */ public initialize (config: AuthConfiguration): void { try { - logger.info(`${moduleName}: Initializing...`) + logger.info(`${moduleName}: Initializing`) if (config.localAuthListEnabled && !this.localAuthListManager) { logger.warn(`${moduleName}: Local auth list enabled but no manager provided`) diff --git a/src/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.ts b/src/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.ts index 1243e09c..8252dc84 100644 --- a/src/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.ts +++ b/src/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.ts @@ -200,7 +200,7 @@ export class RemoteAuthStrategy implements AuthStrategy { * Cleanup strategy resources */ public cleanup (): void { - logger.info(`${moduleName}: Cleaning up...`) + logger.info(`${moduleName}: Cleaning up`) // Reset internal state this.isInitialized = false @@ -270,7 +270,7 @@ export class RemoteAuthStrategy implements AuthStrategy { */ public initialize (config: AuthConfiguration): void { try { - logger.info(`${moduleName}: Initializing...`) + logger.info(`${moduleName}: Initializing`) // Validate that we have an adapter if (this.adapter == null) { diff --git a/src/charging-station/ui-server/UIServerFactory.ts b/src/charging-station/ui-server/UIServerFactory.ts index 1afc6959..f07e8527 100644 --- a/src/charging-station/ui-server/UIServerFactory.ts +++ b/src/charging-station/ui-server/UIServerFactory.ts @@ -15,6 +15,8 @@ import { UIMCPServer } from './UIMCPServer.js' import { isLoopback } from './UIServerUtils.js' import { UIWebSocketServer } from './UIWebSocketServer.js' +const moduleName = 'UIServerFactory' + // eslint-disable-next-line @typescript-eslint/no-extraneous-class export class UIServerFactory { private constructor () { @@ -55,7 +57,7 @@ export class UIServerFactory { !isLoopback(uiServerConfiguration.options?.host ?? '') ) { const logMsg = `Non loopback address in '${ConfigurationSection.uiServer}' configuration section without authentication enabled. This is not recommended` - logger.warn(`${UIServerFactory.logPrefix()} ${logMsg}`) + logger.warn(`${UIServerFactory.logPrefix(moduleName, 'getUIServerImplementation')} ${logMsg}`) } if ( (uiServerConfiguration.type === ApplicationProtocol.WS || @@ -63,7 +65,7 @@ export class UIServerFactory { uiServerConfiguration.version !== ApplicationProtocolVersion.VERSION_11 ) { const logMsg = `Only version ${ApplicationProtocolVersion.VERSION_11} with application protocol type '${uiServerConfiguration.type}' is supported in '${ConfigurationSection.uiServer}' configuration section. Falling back to version ${ApplicationProtocolVersion.VERSION_11}` - logger.warn(`${UIServerFactory.logPrefix()} ${logMsg}`) + logger.warn(`${UIServerFactory.logPrefix(moduleName, 'getUIServerImplementation')} ${logMsg}`) uiServerConfiguration.version = ApplicationProtocolVersion.VERSION_11 } if ( @@ -78,7 +80,9 @@ export class UIServerFactory { switch (uiServerConfiguration.type) { case ApplicationProtocol.HTTP: { const logMsg = `Application protocol type '${uiServerConfiguration.type}' is deprecated in '${ConfigurationSection.uiServer}' configuration section. Use '${ApplicationProtocol.MCP}' instead` - logger.warn(`${UIServerFactory.logPrefix()} ${logMsg}`) + logger.warn( + `${UIServerFactory.logPrefix(moduleName, 'getUIServerImplementation')} ${logMsg}` + ) // eslint-disable-next-line @typescript-eslint/no-deprecated return new UIHttpServer(uiServerConfiguration, bootstrap) } @@ -98,7 +102,9 @@ export class UIServerFactory { }' configuration section from values '${ApplicationProtocol.toString()}', defaulting to '${ ApplicationProtocol.WS }'` - logger.warn(`${UIServerFactory.logPrefix()} ${logMsg}`) + logger.warn( + `${UIServerFactory.logPrefix(moduleName, 'getUIServerImplementation')} ${logMsg}` + ) } return new UIWebSocketServer(uiServerConfiguration, bootstrap) } diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 269fa58c..79a94450 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -39,6 +39,8 @@ import { std, } from '../utils/index.js' +const moduleName = 'PerformanceStatistics' + export class PerformanceStatistics { private static readonly instances: Map = new Map< string, @@ -73,7 +75,7 @@ export class PerformanceStatistics { public static deleteInstance (objId: string | undefined): boolean { if (objId == null) { const errorMsg = 'Cannot delete performance statistics instance without specifying object id' - logger.error(`${PerformanceStatistics.logPrefix()} ${errorMsg}`) + logger.error(`${PerformanceStatistics.logPrefix()} ${moduleName}.deleteInstance: ${errorMsg}`) throw new BaseError(errorMsg) } return PerformanceStatistics.instances.delete(objId) @@ -100,17 +102,17 @@ export class PerformanceStatistics { ): PerformanceStatistics | undefined { if (objId == null) { const errorMsg = 'Cannot get performance statistics instance without specifying object id' - logger.error(`${PerformanceStatistics.logPrefix()} ${errorMsg}`) + logger.error(`${PerformanceStatistics.logPrefix()} ${moduleName}.getInstance: ${errorMsg}`) throw new BaseError(errorMsg) } if (objName == null) { const errorMsg = 'Cannot get performance statistics instance without specifying object name' - logger.error(`${PerformanceStatistics.logPrefix()} ${errorMsg}`) + logger.error(`${PerformanceStatistics.logPrefix()} ${moduleName}.getInstance: ${errorMsg}`) throw new BaseError(errorMsg) } if (uri == null) { const errorMsg = 'Cannot get performance statistics instance without specifying object uri' - logger.error(`${PerformanceStatistics.logPrefix()} ${errorMsg}`) + logger.error(`${PerformanceStatistics.logPrefix()} ${moduleName}.getInstance: ${errorMsg}`) throw new BaseError(errorMsg) } if (!PerformanceStatistics.instances.has(objId)) { @@ -165,8 +167,10 @@ export class PerformanceStatistics { break } default: - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - logger.error(`${this.logPrefix()} wrong message type ${messageType}`) + logger.error( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${this.logPrefix()} ${moduleName}.addRequestStatistic: Wrong message type ${messageType}` + ) break } } @@ -184,7 +188,7 @@ export class PerformanceStatistics { ) if (performanceStorageConfiguration.enabled === true) { logger.info( - `${this.logPrefix()} storage enabled: type ${ + `${this.logPrefix()} ${moduleName}.start: Storage enabled: type ${ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions performanceStorageConfiguration.type // eslint-disable-next-line @typescript-eslint/restrict-template-expressions @@ -272,7 +276,7 @@ export class PerformanceStatistics { } private logStatistics (): void { - logger.info(this.logPrefix(), { + logger.info(`${this.logPrefix()} ${moduleName}.logStatistics:`, { ...this.statistics, statisticsData: JSON.parse( JSONStringify(this.statistics.statisticsData, undefined, MapStringifyFormat.object) @@ -291,15 +295,15 @@ export class PerformanceStatistics { this.logStatistics() }, secondsToMilliseconds(logStatisticsInterval)) logger.info( - `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}` + `${this.logPrefix()} ${moduleName}.startLogStatisticsInterval: Logged every ${formatDurationSeconds(logStatisticsInterval)}` ) } else if (this.displayInterval != null) { logger.info( - `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}` + `${this.logPrefix()} ${moduleName}.startLogStatisticsInterval: Already logged every ${formatDurationSeconds(logStatisticsInterval)}` ) } else if (logConfiguration.enabled === true) { logger.info( - `${this.logPrefix()} log interval is set to ${logStatisticsInterval.toString()}. Not logging statistics` + `${this.logPrefix()} ${moduleName}.startLogStatisticsInterval: Log interval is set to ${logStatisticsInterval.toString()}. Not logging statistics` ) } } diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index c8c84e92..756931ea 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -6,6 +6,8 @@ import { ensureError, handleFileException } from './ErrorUtils.js' import { logger } from './Logger.js' import { isNotEmptyString } from './Utils.js' +const moduleName = 'FileUtils' + export const watchJsonFile = ( file: string, fileType: FileType, @@ -21,6 +23,8 @@ export const watchJsonFile = ( }) } } else { - logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`) + logger.info( + `${logPrefix} ${moduleName}.watchJsonFile: No ${fileType} file to watch given. Not monitoring its changes` + ) } }