Skip to content

Commit

Permalink
#3040 - Provide additional logging (#3375)
Browse files Browse the repository at this point in the history
* #3040 - Add KetcherLogger

* #3040 - Add default logInfo

* #3040 - Raname variables and add default logging settings

* #3040 - Rename variables

* #3040 - Apply suggestions from reviews
  • Loading branch information
nanoblit authored Sep 29, 2023
1 parent f8c04df commit 077e78c
Show file tree
Hide file tree
Showing 45 changed files with 314 additions and 74 deletions.
1 change: 1 addition & 0 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const App = () => {
structServiceProvider={structServiceProvider}
onInit={(ketcher: Ketcher) => {
window.ketcher = ketcher;

window.parent.postMessage(
{
eventType: 'init',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* limitations under the License.
***************************************************************************/

import { KetcherLogger } from 'utilities';
import { SupportedFormat } from './structFormatter.types';

export function identifyStructFormat(
Expand All @@ -26,7 +27,9 @@ export function identifyStructFormat(
if (JSON.parse(sanitizedString)) {
return SupportedFormat.ket;
}
} catch (er) {} // eslint-disable-line
} catch (e) {
KetcherLogger.error('identifyStructFormat.ts::identifyStructFromat', e);
} // eslint-disable-line

const isRXN = sanitizedString.includes('$RXN');
const isSDF = sanitizedString.includes('\n$$$$');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { StructFormatter, SupportedFormat } from './structFormatter.types';
import { KetSerializer } from 'domain/serializers';
import { Struct } from 'domain/entities';
import { getPropertiesByFormat } from './formatProperties';
import { KetcherLogger } from 'utilities';

type ConvertPromise = (
data: ConvertData,
Expand Down Expand Up @@ -70,13 +71,14 @@ export class ServerFormatter implements StructFormatter {
);

return convertResult.struct;
} catch (error: any) {
} catch (e: any) {
let message;
if (error.message === 'Server is not compatible') {
if (e.message === 'Server is not compatible') {
message = `${formatProperties.name} is not supported.`;
} else {
message = `Convert error!\n${error.message || error}`;
message = `Convert error!\n${e.message || e}`;
}
KetcherLogger.error('serverFormatter.ts::getStructureFromStructAsync', e);
throw new Error(message);
}
}
Expand Down Expand Up @@ -107,9 +109,13 @@ export class ServerFormatter implements StructFormatter {
parsedStruct.rescale();
}
return parsedStruct;
} catch (error: any) {
if (error.message !== 'Server is not compatible') {
throw Error(`Convert error!\n${error.message || error}`);
} catch (e: any) {
if (e.message !== 'Server is not compatible') {
KetcherLogger.error(
'serverFormatter.ts::getStructureFromStringAsync',
e,
);
throw Error(`Convert error!\n${e.message || e}`);
}

const formatError =
Expand Down
8 changes: 7 additions & 1 deletion packages/ketcher-core/src/application/ketcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { KetSerializer, MolfileFormat } from 'domain/serializers';
import { Struct } from 'domain/entities';
import assert from 'assert';
import { EventEmitter } from 'events';
import { runAsyncAction } from 'utilities';
import { LogSettings, LogLevel, runAsyncAction } from 'utilities';

const allowedApiSettings = {
'general.dearomatize-on-load': 'dearomatize-on-load',
Expand Down Expand Up @@ -80,6 +80,7 @@ function getStructure(
}

export class Ketcher {
logging: LogSettings;
#structService: StructService;
#formatterFactory: FormatterFactory;
#editor: Editor;
Expand Down Expand Up @@ -108,6 +109,11 @@ export class Ketcher {
this.#formatterFactory = formatterFactory;
this.#indigo = new Indigo(this.#structService);
this.#eventBus = new EventEmitter();
this.logging = {
enabled: false,
level: LogLevel.ERROR,
showTrace: false,
};
}

get indigo() {
Expand Down
2 changes: 2 additions & 0 deletions packages/ketcher-core/src/application/render/raphaelRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import defaultOptions from './options';
import draw from './draw';
import { RenderOptions } from './render.types';
import _ from 'lodash';
import { KetcherLogger } from 'utilities';

const notifyRenderComplete = _.debounce(() => {
const event = new Event('renderComplete');
Expand Down Expand Up @@ -64,6 +65,7 @@ export class Render {
return this.options;
}
} catch (e) {
KetcherLogger.error('raphaelRenderer.ts::updateOptions', e);
console.log('Not a valid settings object');
}
return false;
Expand Down
2 changes: 2 additions & 0 deletions packages/ketcher-core/src/domain/entities/sgroupForest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { Pile } from './pile';
import { SGroup } from './sgroup';
import assert from 'assert';
import { Struct } from './struct';
import { KetcherLogger } from 'utilities';

export class SGroupForest {
/** node id -> parent id */
Expand Down Expand Up @@ -147,6 +148,7 @@ export class SGroupForest {
assert(this.parent.has(id), 'sgid is not in the forest');
assert(this.children.has(id), 'sgid is not in the forest');
} catch (e) {
KetcherLogger.error('sgroupForest.ts::SGroupForest::remove', e);
console.info('error: sgid is not in the forest');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import assert from 'assert';
import { polymerBondToDrawingEntity } from 'domain/serializers/ket/fromKet/polymerBondToDrawingEntity';
import { getMonomerUniqueKey } from 'domain/helpers/monomers';
import { monomerFactory } from 'application/editor/operations/monomer/monomerFactory';
import { KetcherLogger } from 'utilities';

function parseNode(node: any, struct: any) {
const type = node.type;
Expand Down Expand Up @@ -193,7 +194,11 @@ export class KetSerializer implements Serializer<Struct> {
let parsedFileContent: IKetMacromoleculesContent;
try {
parsedFileContent = JSON.parse(fileContent);
} catch (error) {
} catch (e) {
KetcherLogger.error(
'ketSerializer.ts::KetSerializer::parseAndValidateMacromolecules',
e,
);
editor.events.error.dispatch('Error during file parsing');
return { error: true };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { MolSerializerOptions } from './mol.types';
import { Molfile } from './molfile';
import { Serializer } from '../serializers.types';
import { Struct } from 'domain/entities';
import { KetcherLogger } from 'utilities';

export class MolSerializer implements Serializer<Struct> {
static DefaultOptions: MolSerializerOptions = {
Expand Down Expand Up @@ -46,7 +47,8 @@ export class MolSerializer implements Serializer<Struct> {

try {
return molfile.parseCTFile(parseCTFileParams);
} catch (ex) {
} catch (e) {
KetcherLogger.error('molSerializer::MolSerializer::deserialize', e);
if (this.options.badHeaderRecover) {
try {
// check whether there's an extra empty line on top
Expand All @@ -55,8 +57,8 @@ export class MolSerializer implements Serializer<Struct> {
...parseCTFileParams,
molfileLines: lines.slice(1),
});
} catch (ex1) {
//
} catch (e1) {
KetcherLogger.error('molSerializer::MolSerializer::deserialize', e1);
}
try {
// check for a missing first line
Expand All @@ -65,11 +67,11 @@ export class MolSerializer implements Serializer<Struct> {
...parseCTFileParams,
molfileLines: [''].concat(lines),
});
} catch (ex2) {
//
} catch (e2) {
KetcherLogger.error('molSerializer::MolSerializer::deserialize', e2);
}
}
throw ex;
throw e;
}
}

Expand Down
8 changes: 5 additions & 3 deletions packages/ketcher-core/src/domain/serializers/mol/molfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import { Elements } from 'domain/constants';
import common from './common';
import utils from './utils';
import { KetcherLogger } from 'utilities';

const END_V2000 = '2D 1 1.00000 0.00000 0';

Expand Down Expand Up @@ -88,9 +89,10 @@ export class Molfile {

try {
common.prepareForSaving[sgroup.type](sgroup, mol);
} catch (ex: any) {
if (!skipErrors || typeof ex.id !== 'number') {
throw new Error(`Error: ${ex.message}`);
} catch (e: any) {
KetcherLogger.error('molfile.ts::Molfile::prepareSGroups', e);
if (!skipErrors || typeof e.id !== 'number') {
throw new Error(`Error: ${e.message}`);
}
errorIgnore = true;
}
Expand Down
9 changes: 6 additions & 3 deletions packages/ketcher-core/src/domain/serializers/smi/smiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
***************************************************************************/

import { Atom, Bond, Pile, SGroup } from 'domain/entities';
import { KetcherLogger } from 'utilities';

import CisTrans from './cis_trans';
import Dfs from './dfs';
Expand Down Expand Up @@ -70,8 +71,9 @@ Smiles.prototype.saveMolecule = function (struct, ignoreErrors) {
if (sg.type === 'MUL') {
try {
SGroup.prepareMulForSaving(sg, struct);
} catch (ex) {
throw Error('Bad s-group (' + ex.message + ')');
} catch (error) {
KetcherLogger.error('smiles.js::Smiles.prototype.saveMolecule', error);
throw Error('Bad s-group (' + error.message + ')');
}
}
// 'SMILES data format doesn\'t support s-groups'
Expand Down Expand Up @@ -246,7 +248,8 @@ Smiles.prototype.saveMolecule = function (struct, ignoreErrors) {
this.atoms[atomIdx].chirality = 1;
} else this.atoms[atomIdx].chirality = 2;
});
} catch (ex) {
} catch (e) {
KetcherLogger.error('smiles.js::Smiles.prototype.saveMolecule', e);
// TODO: add error handler call
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
StructService,
StructServiceOptions,
} from 'domain/services';
import { KetcherLogger } from 'utilities';

function pollDeferred(process, complete, timeGap, startTimeGap) {
return new Promise((resolve, reject) => {
Expand All @@ -50,8 +51,9 @@ function pollDeferred(process, complete, timeGap, startTimeGap) {
try {
if (complete(val)) resolve(val);
else setTimeout(iterate, timeGap);
} catch (e) {
reject(e);
} catch (error) {
KetcherLogger.error('remoteStructService.ts::pollDeferred', error);
reject(error);
}
},
(err) => reject(err),
Expand Down Expand Up @@ -168,6 +170,10 @@ export class RemoteStructService implements StructService {
imagoVersions = response.imago_versions;
isAvailable = true;
} catch (e) {
KetcherLogger.error(
'remoteStructService.ts::RemoteStructService::info',
e,
);
indigoVersion = '';
imagoVersions = [];
isAvailable = false;
Expand Down
84 changes: 84 additions & 0 deletions packages/ketcher-core/src/utilities/KetcherLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
export enum LogLevel {
ERROR = 0,
WARN = 1,
INFO = 2,
LOG = 3,
}

export interface LogSettings {
enabled?: boolean;
showTrace?: boolean;
level?: LogLevel;
}

export class KetcherLogger {
static get settings(): LogSettings {
if (!window?.ketcher) {
throw new Error(
'Ketcher needs to be initialized before KetcherLogger is used',
);
}

return window.ketcher.logging;
}

static set settings(newSettings: LogSettings) {
for (const [settingName, settingValue] of Object.entries(newSettings)) {
this.settings[settingName] = settingValue;
}
}

static log(...messages: unknown[]): void {
if (!this.isMinimumLogLevel(LogLevel.LOG)) {
return;
}

const { showTrace } = this.settings;

if (showTrace) {
window.console.trace(messages);
} else {
window.console.log(messages);
}
}

static info(...messages: unknown[]): void {
if (!this.isMinimumLogLevel(LogLevel.INFO)) {
return;
}

const { showTrace } = this.settings;

if (showTrace) {
window.console.trace(messages);
} else {
window.console.info(messages);
}
}

static warn(...warnings: unknown[]): void {
if (!this.isMinimumLogLevel(LogLevel.WARN)) {
return;
}

window.console.warn(warnings);
}

static error(...errors: unknown[]): void {
if (!this.isMinimumLogLevel(LogLevel.ERROR)) {
return;
}

window.console.error(errors);
}

private static isMinimumLogLevel(minimumLevel: LogLevel): boolean {
const { enabled, level } = this.settings;

if (!enabled || level == null) {
return false;
}

return level >= minimumLevel;
}
}
1 change: 1 addition & 0 deletions packages/ketcher-core/src/utilities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ export * from './tfx';
export * from './runAsyncAction';
export * from './b64toBlob';
export * from './emitEventRequestIsFinished';
export * from './KetcherLogger';
4 changes: 3 additions & 1 deletion packages/ketcher-core/src/utilities/runAsyncAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
***************************************************************************/

import EventEmitter from 'events';
import { KetcherLogger } from './KetcherLogger';

export enum KetcherAsyncEvents {
LOADING = 'LOADING',
Expand All @@ -31,7 +32,8 @@ export const runAsyncAction = async <T = any>(
const res = await action();
eventEmitter.emit(KetcherAsyncEvents.SUCCESS);
return res;
} catch {
} catch (e) {
KetcherLogger.error('runAsyncAction.ts::runAsyncAction', e);
eventEmitter.emit(KetcherAsyncEvents.FAILURE);
return undefined;
}
Expand Down
Loading

0 comments on commit 077e78c

Please sign in to comment.