diff --git a/docs/transports/file.md b/docs/transports/file.md index 01788c4..547fee0 100644 --- a/docs/transports/file.md +++ b/docs/transports/file.md @@ -125,4 +125,8 @@ Reads content of all log files. Be careful, if you use multiple log directories through overriding resolvePath, it won't return all the files. +#### `setAppName(appName: string)` + +Overrides appName used for resolving the log path + diff --git a/src/index.d.ts b/src/index.d.ts index 819bd5a..9949f08 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -261,6 +261,12 @@ declare namespace Logger { */ resolvePathFn: (variables: PathVariables, message?: LogMessage) => string; + /** + * Override appName used for resolving log path + * @param appName + */ + setAppName(appName: string): void; + /** * Whether to write a log file synchronously. Default to true */ diff --git a/src/main/ElectronExternalApi.js b/src/main/ElectronExternalApi.js index 29c8a7a..b37eb58 100644 --- a/src/main/ElectronExternalApi.js +++ b/src/main/ElectronExternalApi.js @@ -21,7 +21,9 @@ class ElectronExternalApi extends NodeExternalApi { getAppName() { let appName; try { - appName = this.electron.app?.name || this.electron.app?.getName(); + appName = this.appName + || this.electron.app?.name + || this.electron.app?.getName(); } catch { // fallback to default value below } diff --git a/src/node/NodeExternalApi.js b/src/node/NodeExternalApi.js index 7c5359f..6dc36f3 100644 --- a/src/node/NodeExternalApi.js +++ b/src/node/NodeExternalApi.js @@ -21,7 +21,17 @@ class NodeExternalApi { } getAppName() { - return this.appName || this.getAppPackageJson()?.name; + const appName = this.appName || this.getAppPackageJson()?.name; + if (!appName) { + throw new Error( + 'electron-log can\'t determine the app name. It tried these methods:\n' + + '1. Use `electron.app.name`\n' + + '2. Use productName or name from the nearest package.json`\n' + + 'You can also set it through log.transports.file.setAppName()', + ); + } + + return appName; } /** @@ -181,6 +191,10 @@ class NodeExternalApi { }); } + setAppName(appName) { + this.appName = appName; + } + setPlatform(platform) { this.platform = platform; } diff --git a/src/node/transports/file/index.js b/src/node/transports/file/index.js index 0df6639..aaf18d0 100644 --- a/src/node/transports/file/index.js +++ b/src/node/transports/file/index.js @@ -54,6 +54,10 @@ function fileTransportFactory( resolvePathFn(vars) { return path.join(vars.libraryDefaultDir, vars.fileName); }, + + setAppName(name) { + logger.dependencies.externalApi.setAppName(name); + }, }); function transport(message) {