Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frontend global loggers #192

Merged
merged 9 commits into from Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierrc.js
@@ -0,0 +1 @@
// intentionally blank
14 changes: 12 additions & 2 deletions src-electron/main-process/electron-main.js
Expand Up @@ -26,7 +26,11 @@ let installUpdate = false;

const title = `${productName} v${version}`;

const selectionMenu = Menu.buildFromTemplate([{ role: "copy" }, { type: "separator" }, { role: "selectall" }]);
const selectionMenu = Menu.buildFromTemplate([
{ role: "copy" },
{ type: "separator" },
{ role: "selectall" }
]);

const inputMenu = Menu.buildFromTemplate([
{ role: "cut" },
Expand Down Expand Up @@ -54,7 +58,13 @@ function createWindow() {
minWidth: 640,
minHeight: 480,
icon: require("path").join(__statics, "icon_512x512.png"),
title
title,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
// anything we want preloaded, e.g. global vars
preload: path.resolve(__dirname, "electron-preload.js")
}
});

mainWindow.on("close", e => {
Expand Down
4 changes: 4 additions & 0 deletions src-electron/main-process/electron-preload.js
@@ -0,0 +1,4 @@
console.log("preloading");
const path = require("upath");

require(path.resolve(__dirname, "logging.js"));
Mikunj marked this conversation as resolved.
Show resolved Hide resolved
89 changes: 89 additions & 0 deletions src-electron/main-process/logging.js
@@ -0,0 +1,89 @@
// create global logging functions for the frontend. It sends messages to the main
// process which then log to file

const electron = require("electron");

const _ = require("lodash");

console.log("yeah basically required all that bs");

// Default Bunyan levels: https://github.com/trentm/node-bunyan#levels
// To make it easier to visually scan logs, we make all levels the same length

const ipc = electron.ipcRenderer;

function log(...args) {
logAtLevel("info", "INFO ", ...args);
}

if (window.console) {
console._log = console.log;
console.log = log;
console._trace = console.trace;
console._debug = console.debug;
console._info = console.info;
console._warn = console.warn;
console._error = console.error;
console._fatal = console.error;
}

// To avoid [Object object] in our log since console.log handles non-strings
// smoothly
function cleanArgsForIPC(args) {
const str = args.map(item => {
if (typeof item !== "string") {
try {
return JSON.stringify(item);
} catch (error) {
return item;
}
}

return item;
});

return str.join(" ");
}

// Backwards-compatible logging, simple strings and no level (defaulted to INFO)
function now() {
const date = new Date();
return date.toJSON();
}

// The Bunyan API: https://github.com/trentm/node-bunyan#log-method-api
function logAtLevel(level, prefix, ...args) {
console._log("the level is: " + level);
// do some different shit for dev
// if (development) {
const fn = `_${level}`;
console[fn](prefix, now(), ...args);

console._log("hey, the console fn actually worked");
// } else {
// console._log(prefix, now(), ...args);
// }

const logText = cleanArgsForIPC(args);
ipc.send(`log-${level}`, logText);
}

window.log = {
fatal: _.partial(logAtLevel, "fatal", "FATAL"),
error: _.partial(logAtLevel, "error", "ERROR"),
warn: _.partial(logAtLevel, "warn", "WARN "),
info: _.partial(logAtLevel, "info", "INFO "),
debug: _.partial(logAtLevel, "debug", "DEBUG"),
trace: _.partial(logAtLevel, "trace", "TRACE")
};

// window.onerror = (message, script, line, col, error) => {
// const errorInfo = error && error.stack ? error.stack : JSON.stringify(error);
// window.log.error(`Top-level unhandled error: ${errorInfo}`);
// };

// window.addEventListener("unhandledrejection", rejectionEvent => {
// const error = rejectionEvent.reason;
// const errorInfo = error && error.stack ? error.stack : error;
// window.log.error("Top-level unhandled promise rejection:", errorInfo);
// });
18 changes: 15 additions & 3 deletions src-electron/main-process/modules/backend.js
Expand Up @@ -8,11 +8,16 @@ import { version } from "../../../package.json";
const bunyan = require("bunyan");

const WebSocket = require("ws");
const electron = require("electron");
const os = require("os");
const fs = require("fs-extra");
const path = require("upath");
const objectAssignDeep = require("object-assign-deep");

const { ipcMain: ipc } = electron;

const LOG_LEVELS = ["fatal", "error", "warn", "info", "debug", "trace"];

export class Backend {
constructor(mainWindow) {
this.mainWindow = mainWindow;
Expand Down Expand Up @@ -355,12 +360,20 @@ export class Backend {
name: "log",
streams: [
{
level: "debug",
path: path.join(logPath, "electron.log")
type: "rotating-file",
path: path.join(logPath, "electron.log"),
period: "1d", // daily rotation
count: 4 // keep 4 days of logs
}
]
});

LOG_LEVELS.forEach(level => {
ipc.on(`log-${level}`, (first, ...rest) => {
log[level](...rest);
});
});

this.log = log;

process.on("uncaughtException", error => {
Expand Down Expand Up @@ -493,7 +506,6 @@ export class Backend {
fs.mkdirpSync(log_dir);
}

console.log("About to init the logger with log_dir: " + log_dir);
this.initLogger(log_dir);

this.daemon = new Daemon(this);
Expand Down
50 changes: 36 additions & 14 deletions src-electron/main-process/modules/wallet-rpc.js
Expand Up @@ -336,15 +336,17 @@ export class WalletRPC {
params.amount,
params.address,
params.payment_id,
params.priority
params.priority,
!!params.isSweepAll
);
break;
case "relay_tx":
this.relayTransaction(
params.metadataList,
params.isBlink,
params.addressSave,
params.note
params.note,
!!params.isSweepAll
);
break;
case "purchase_lns":
Expand Down Expand Up @@ -1348,8 +1350,17 @@ export class WalletRPC {
}

// submits the transaction to the blockchain, irreversible from here
async relayTransaction(metadataList, isBlink, addressSave, note) {
const { address, payment_id, address_book } = addressSave;
async relayTransaction(metadataList, isBlink, addressSave, note, isSweepAll) {
// for a sweep these don't exist
let address = "";
let payment_id = "";
let address_book = "";
if (addressSave) {
address = addressSave.address;
payment_id = addressSave.payment_id;
address_book = addressSave.address_book;
}

let failed = false;
let errorMessage = "Failed to relay transaction";

Expand Down Expand Up @@ -1383,8 +1394,13 @@ export class WalletRPC {
}
}

// for updating state on the correct page
const gatewayEndpoint = isSweepAll
? "set_sweep_all_status"
: "set_tx_status";

if (!failed) {
this.sendGateway("set_tx_status", {
this.sendGateway(gatewayEndpoint, {
code: 0,
i18n: "notification.positive.sendSuccess",
sending: false
Expand All @@ -1401,7 +1417,7 @@ export class WalletRPC {
return;
}

this.sendGateway("set_tx_status", {
this.sendGateway(gatewayEndpoint, {
code: -1,
message: errorMessage,
sending: false
Expand All @@ -1410,7 +1426,8 @@ export class WalletRPC {

// prepares params and provides a "confirm" popup to allow the user to check
// send address and tx fees before sending
transfer(password, amount, address, payment_id, priority) {
// isSweepAll refers to if it's the sweep from service nodes page
transfer(password, amount, address, payment_id, priority, isSweepAll) {
const cryptoCallback = (err, password_hash) => {
if (err) {
this.sendGateway("set_tx_status", {
Expand All @@ -1434,10 +1451,10 @@ export class WalletRPC {
// if sending "All" the funds, then we need to send all - fee (sweep_all)
// To be amended after the hardfork, v8.
// https://github.com/loki-project/loki-electron-gui-wallet/issues/181
const isSweepAll = amount == this.wallet_state.unlocked_balance;
const rpc_endpoint = isSweepAll ? "sweep_all" : "transfer_split";
const isSweepAllRPC = amount == this.wallet_state.unlocked_balance;
const rpc_endpoint = isSweepAllRPC ? "sweep_all" : "transfer_split";

const rpcSpecificParams = isSweepAll
const rpcSpecificParams = isSweepAllRPC
? {
address,
account_index: 0
Expand All @@ -1456,6 +1473,11 @@ export class WalletRPC {
params.payment_id = payment_id;
}

// for updating state on the correct page
const gatewayEndpoint = isSweepAll
? "set_sweep_all_status"
: "set_tx_status";

this.sendRPC(rpc_endpoint, params)
.then(data => {
if (data.hasOwnProperty("error") || !data.hasOwnProperty("result")) {
Expand All @@ -1467,7 +1489,7 @@ export class WalletRPC {
} else {
error = `Incorrect result from ${rpc_endpoint} RPC call`;
}
this.sendGateway("set_tx_status", {
this.sendGateway(gatewayEndpoint, {
code: -1,
message: error,
sending: false
Expand All @@ -1476,14 +1498,14 @@ export class WalletRPC {
}

// update state to show a confirm popup
this.sendGateway("set_tx_status", {
this.sendGateway(gatewayEndpoint, {
code: 1,
i18n: "strings.awaitingConfirmation",
sending: false,
txData: {
// target address for a sweep all
address: data.params.address,
isSweepAll: isSweepAll,
isSweepAll: isSweepAllRPC,
amountList: data.result.amount_list,
metadataList: data.result.tx_metadata_list,
feeList: data.result.fee_list,
Expand All @@ -1494,7 +1516,7 @@ export class WalletRPC {
});
})
.catch(err => {
this.sendGateway("set_tx_status", {
this.sendGateway(gatewayEndpoint, {
code: -1,
message: err.message,
sending: false
Expand Down