Skip to content

Commit

Permalink
implemented proper logging, log file rotation
Browse files Browse the repository at this point in the history
  • Loading branch information
majorlue committed Jan 3, 2024
1 parent a731468 commit 8d5083b
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 37 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@quasar/extras": "^1.16.4",
"axios": "^1.2.1",
"dayjs": "^1.11.10",
"electron-log": "^5.0.3",
"pinia": "^2.0.11",
"quasar": "^2.14.2",
"tar-pack": "^3.4.1",
Expand Down Expand Up @@ -52,4 +53,4 @@
"npm": ">= 6.13.4",
"yarn": ">= 1.21.1"
}
}
}
39 changes: 30 additions & 9 deletions src-electron/electron-main.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
import dayjs from 'dayjs';
import { app, BrowserWindow, ipcMain } from 'electron';
// import path from 'path';
import path from 'path';
// import * as fs from 'fs';
// const path = require('path');
// import os from 'os';
// const os = require('os');
import log from 'electron-log';
import Listeners from './ipcListeners';
// needed in case process is undefined under Linux
// const platform = process.platform || os.platform();
const path = require('path');
const os = require('os');
const fs = require('fs');

// app.allowRendererProcessReuse = true;
// Optional, initialize the logger for any renderer process
log.initialize();
const currDate = dayjs().format('DD-MM-YYYY');

const logFolder = path.join(
process.platform === 'win32' ? app.getPath('appData') : os.homedir(),
'Drehmal Installer',
'logs'
);

const getLogFileName: () => string = () => {
let index = 1;
let name = `${currDate}_${index}-installer.log`;
while (true) {
if (!fs.existsSync(path.join(logFolder, name))) break;
else name = `${currDate}_${index++}-installer.log`;
}
return name;
};
// can't use function call in resolve path as it'll create a new file for each logger instance
const logFileName = getLogFileName();
log.transports.file.resolvePathFn = () => path.join(logFolder, logFileName);
log.transports.file.format = '[{h}:{i}:{s}.{ms}] [{label}] {text}';

log.info('Logger initialised');

let mainWindow: BrowserWindow | undefined;

Expand Down
2 changes: 1 addition & 1 deletion src-electron/ipcListeners.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ipcMain, BrowserWindow, app as ElectronApp } from 'electron';
// import path from 'path';
// console.log('IPC Listener');
// log.info('IPC Listener');
let browserWindow: BrowserWindow;
let app: typeof ElectronApp;

Expand Down
5 changes: 3 additions & 2 deletions src/components/FolderSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</template>

<script setup lang="ts">
import log from 'electron-log';
import { storeToRefs } from 'pinia';
import { useInstallerStore } from 'src/stores/InstallerStore';
import { ref } from 'vue';
Expand All @@ -28,7 +29,7 @@ filePath.value = minecraftDir.value;
// let firstFilePath = folderPath.value.split('\\');
// firstFilePath.pop();
// installerStore.setMinecraftDir(filePath)
// console.log(`Minecraft Path updated to ${installerStore.minecraftDir.value}`)
// log.info(`Minecraft Path updated to ${installerStore.minecraftDir.value}`)
// return path.join(...firstFilePath);
// });
Expand All @@ -43,7 +44,7 @@ const folderSelectChange = async (event: any) => {
filePath.value = path.join(...firstFilePath);
// installerStore.setMinecraftDir(filePath.value)
minecraftDir.value = filePath.value;
console.log(`Minecraft Path updated to ${minecraftDir.value}`);
log.info(`Minecraft Path updated to ${minecraftDir.value}`);
};
</script>

Expand Down
12 changes: 8 additions & 4 deletions src/components/MapDownload.vue
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,18 @@
</template>

<script setup lang="ts">
import log from 'electron-log';
import { storeToRefs } from 'pinia';
import MiniProgressBar from 'src/components/MiniProgressBar.vue';
import ProgressBox from 'src/components/ProgressBox.vue';
import { ProgressBox as ProgressBoxType, Shard } from 'src/components/models';
import { downloadFile } from 'src/providers/DownloadFile';
import { extractTargz } from 'src/providers/ExtractFile';
import { downloadResourcePack } from 'src/providers/InstallFabric';
import { downloadMods, installFabric } from 'src/providers/InstallFabric';
import {
downloadMods,
downloadResourcePack,
installFabric,
} from 'src/providers/InstallFabric';
import { useInstallerStore } from 'src/stores/InstallerStore';
import { useSourcesStore } from 'src/stores/SourcesStore';
import { ref } from 'vue';
Expand Down Expand Up @@ -128,7 +132,7 @@ const downloadShards = async () => {
shardsDir.value,
`${versionFileName}-${index}.tar.gz`
);
console.log(`Downloading map shard to ${filePath}`);
log.info(`Downloading map shard to ${filePath}`);
downloadFile(url, filePath, shardRef).then(() => {
downloaded++;
if (downloaded === map.value.shards.length)
Expand All @@ -137,7 +141,7 @@ const downloadShards = async () => {
if (!fs.existsSync(mapDir)) fs.mkdirSync(mapDir, { recursive: true });
shardRef.value.label = 'Extracting files. . .';
console.log(`Extracting map to ${mapDir}`);
log.info(`Extracting map to ${mapDir}`);
extractTargz(filePath, mapDir, shardRef).then(() => {
extracted++;
Expand Down
4 changes: 2 additions & 2 deletions src/pages/IndexPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
</template>

<script setup lang="ts">
// import { ipcRenderer } from 'electron';
import log from 'electron-log';
import { storeToRefs } from 'pinia';
import NextButton from 'src/components/NextButton.vue';
import { useInstallerStore } from 'src/stores/InstallerStore';
Expand Down Expand Up @@ -65,7 +65,7 @@ ipcRenderer.invoke('getAppDataPath').then((appData) => {
shardsDir.value = path.join(appDir.value, 'shards');
memory.value = 4;
console.log(
log.info(
'Defaults loaded: ',
JSON.stringify({
homeDir: homeDir.value,
Expand Down
6 changes: 4 additions & 2 deletions src/pages/InstallPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<div class="footer">
<div class="nav-footer">
<back-button path="/path/"></back-button>
<!-- <next-button path="/install/"></next-button> -->
<!-- <next-button path="/complete/"></next-button> -->
</div>
</div>
</div>
Expand All @@ -36,16 +36,18 @@

<!-- <script setup> -->
<script setup lang="ts">
import log from 'electron-log';
import { storeToRefs } from 'pinia';
import MapDownload from 'src/components/MapDownload.vue';
import { Shard } from 'src/components/models';
import { useSourcesStore } from 'src/stores/SourcesStore';
import { ref } from 'vue';
import BackButton from '../components/BackButton.vue';
import NextButton from '../components/NextButton.vue';

Check warning on line 46 in src/pages/InstallPage.vue

View workflow job for this annotation

GitHub Actions / Building linux

'NextButton' is defined but never used

Check warning on line 46 in src/pages/InstallPage.vue

View workflow job for this annotation

GitHub Actions / Building win

'NextButton' is defined but never used

Check warning on line 46 in src/pages/InstallPage.vue

View workflow job for this annotation

GitHub Actions / Building osx

'NextButton' is defined but never used

const { map } = storeToRefs(useSourcesStore());

console.log(map);
log.info(map);
const versionFileName = map.value.versionName
.toLowerCase()
.split(' ')
Expand Down
10 changes: 6 additions & 4 deletions src/providers/DownloadFile.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const https = require('https');
const fs = require('fs');
import log from 'electron-log';
import { Ref } from 'vue';
const path = require('path');

function downloadFile(url: string, savePath: string, ref?: Ref): Promise<void> {
return new Promise((resolve, reject) => {

Check warning on line 8 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building linux

'reject' is defined but never used

Check warning on line 8 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building win

'reject' is defined but never used

Check warning on line 8 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building osx

'reject' is defined but never used
const name = savePath.split(path.sep).pop();
const file = fs.createWriteStream(savePath);
file.on('error', (err: any) => {

Check warning on line 11 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building linux

Unexpected any. Specify a different type

Check warning on line 11 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building win

Unexpected any. Specify a different type

Check warning on line 11 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building osx

Unexpected any. Specify a different type
console.log(`file error on ${name} ${url}`, err);
log.info(`file error on ${name} ${url}`, err);
});

const options = {
Expand Down Expand Up @@ -58,14 +60,14 @@ function downloadFile(url: string, savePath: string, ref?: Ref): Promise<void> {
})
.on('end', function () {
file.end();
console.log(`${name} downloaded successfully. ${Date.now()}`);
log.info(`${name} downloaded successfully. ${Date.now()}`);
resolve();
})
.on('error', (err: any) => {

Check warning on line 66 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building linux

Unexpected any. Specify a different type

Check warning on line 66 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building win

Unexpected any. Specify a different type

Check warning on line 66 in src/providers/DownloadFile.ts

View workflow job for this annotation

GitHub Actions / Building osx

Unexpected any. Specify a different type
console.log(`download error on ${name} ${url}`, err);
log.info(`download error on ${name} ${url}`, err);
})
.on('timeout', () => {
console.log('got timeout event');
log.info('got timeout event');
});
});
});
Expand Down
3 changes: 2 additions & 1 deletion src/providers/ExtractFile.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import log from 'electron-log';
import { Ref } from 'vue';
const fs = require('fs');
const tarpack = require('tar-pack');
Expand All @@ -17,7 +18,7 @@ export function extractTargz(
else {
if (ref) {
ref.value.label = 'Files successfully extracted!';
console.log(`Extraction complete. Removing ${archivePath}`);
log.info(`Extraction complete. Removing ${archivePath}`);
fs.unlinkSync(archivePath);
resolve();
}
Expand Down
19 changes: 10 additions & 9 deletions src/providers/InstallFabric.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import log from 'electron-log';
import { storeToRefs } from 'pinia';
import { useInstallerStore } from 'src/stores/InstallerStore';
import { useSourcesStore } from 'src/stores/SourcesStore';
Expand All @@ -19,7 +20,7 @@ export async function installFabric(ref: Ref) {
'fabric-installer-' + launcher.value.fabric.version + '.jar'
);

console.log(`Downloading Fabric installer to ${fabricPath}`);
log.info(`Downloading Fabric installer to ${fabricPath}`);

ref.value.label = 'Downloading Fabric installer';
ref.value.progress = 0.25;
Expand All @@ -28,7 +29,7 @@ export async function installFabric(ref: Ref) {
ref.value.label = 'Installing Fabric';
ref.value.progress = 0.5;
ref.value.percent = 50;
console.log('Calling Fabric installer');
log.info('Calling Fabric installer');
const fabricProc = spawn('java', [
'-jar',
fabricPath,
Expand All @@ -39,15 +40,15 @@ export async function installFabric(ref: Ref) {
'1.17.1',
]);
fabricProc.stdout.on('data', (data: any) => {
console.log(`stdout: ${data}`);
log.info(`stdout: ${data}`);
});
fabricProc.stderr.on('data', (data: any) => {
console.error(`stderr: ${data}`);
});

fabricProc.on('close', (code: any) => {
const taken = Date.now() - startTime;
console.log(`child process exited with code ${code} in ${taken}ms`);
log.info(`child process exited with code ${code} in ${taken}ms`);
fs.unlinkSync(fabricPath);

ref.value.label = 'Fabric successfully installed!';
Expand Down Expand Up @@ -76,7 +77,7 @@ export async function installFabric(ref: Ref) {
] = `-Xmx${memory.value}G`;

fs.writeFileSync(profileFilePath, JSON.stringify(data), 'utf-8');
console.log('readFileSync complete');
log.info('readFileSync complete');

ref.value.label = 'Minecraft profile created!';
ref.value.progress = 1;
Expand Down Expand Up @@ -105,7 +106,7 @@ export async function downloadMods(ref: Ref) {
const { name, mod_version, mc_version, source } = mod;
const modName =
name + ' - ' + modLoader + mod_version + '-' + mc_version + '.jar';
console.log(`Downloading ${modName} to ${modsPath}`);
log.info(`Downloading ${modName} to ${modsPath}`);
const modPath = path.join(modsPath, modName);
await downloadFile(source, modPath);
downloaded++;
Expand All @@ -118,7 +119,7 @@ export async function downloadMods(ref: Ref) {
ref.value.label = `Downloading: ${name}`;

const taken = Date.now() - startTime;
console.log(`downloaded mod ${downloaded}/${totalMods} in ${taken}ms`);
log.info(`downloaded mod ${downloaded}/${totalMods} in ${taken}ms`);
}
}
await processArray(modList);
Expand All @@ -135,7 +136,7 @@ export async function downloadResourcePack(mapPath: string, ref?: Ref) {
const filePath = path.join(minecraftDir.value, 'resourcepacks', rpName);

fs.copyFileSync(path.join(mapPath, 'resources.zip'), filePath);
console.log(`Copied resource pack to ${filePath}`);
log.info(`Copied resource pack to ${filePath}`);

const optionsFilePath = path.join(minecraftDir.value, 'options.txt');
const data = fs.readFileSync(optionsFilePath).toString().split('\n');
Expand All @@ -147,5 +148,5 @@ export async function downloadResourcePack(mapPath: string, ref?: Ref) {
] = `resourcePacks:["vanilla","Fabric Mods","file/${rpName}"]`;

fs.writeFileSync(optionsFilePath, data.join('\n'), 'utf-8');
console.log('Updated Resource Pack order');
log.info('Updated Resource Pack order');
}
3 changes: 2 additions & 1 deletion src/stores/InstallerStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import log from 'electron-log';
const path = require('path');
const os = require('os');

Expand All @@ -11,7 +12,7 @@ export const useInstallerStore = defineStore('installer', () => {

const minecraftDir = ref(path.join('', '.minecraft'));
const minecraftDirIsDefault = ref(true);
console.log(`Home: ${os.homedir()}`);
log.info(`Home: ${os.homedir()}`);

const memory = ref(
parseInt(process.env.MINECRAFT_MEMORY ? process.env.MINECRAFT_MEMORY : '4')
Expand Down
7 changes: 6 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,7 @@ csstype@^3.1.3:

dayjs@^1.11.10:
version "1.11.10"
resolved "https://registry.npmjs.org/dayjs/-/dayjs-1.11.10.tgz"
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.10.tgz#68acea85317a6e164457d6d6947564029a6a16a0"
integrity sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==

[email protected], debug@^2.2.0:
Expand Down Expand Up @@ -1651,6 +1651,11 @@ electron-builder@^24.3.0:
simple-update-notifier "2.0.0"
yargs "^17.6.2"

electron-log@^5.0.3:
version "5.0.3"
resolved "https://registry.yarnpkg.com/electron-log/-/electron-log-5.0.3.tgz#972e088df24bf09dca980067df48e4eec0e2ec82"
integrity sha512-jUgAuRjfpCD9tmH1F6fb195YsFfM/DkqkZLhFeo0VAAstantn11bxmgx63uE6KG/JljHG7sIkgM2QEjDimJI0g==

electron-packager@^17.1.1:
version "17.1.2"
resolved "https://registry.npmjs.org/electron-packager/-/electron-packager-17.1.2.tgz"
Expand Down

0 comments on commit 8d5083b

Please sign in to comment.