import { YLSdkInterface } from './sdkinterface' import { AddonLogSeverity, NativeAddonLogConfig } from './common-types' import { isNodeJs } from "./help"; let ylSdkInterface: YLSdkInterface; if (isNodeJs()) { let bindings = require('bindings'); ylSdkInterface = bindings('sdkinterface'); } export function NativeLogInfo(caller: string, msg: string | Error | (() => string), ...args: (string | object | boolean | number | Array | (() => string))[]): void { NativeAddonLog(AddonLogSeverity.info, caller, msg); } export function NativeLogError(caller: string, msg: string | Error | (() => string), ...args: (string | object | boolean | number | Array | (() => string))[]): void { NativeAddonLog(AddonLogSeverity.error, caller, msg); } export function NativeLogVerbose(caller: string, msg: string | Error | (() => string), ...args: (string | object | boolean | number | Array | (() => string))[]): void { NativeAddonLog(AddonLogSeverity.verbose, caller, msg); } export function NativeAddonLog(severity: AddonLogSeverity, caller: string, msg: string | Error | (() => string), ...args: (string | object | boolean | number | Array | (() => string))[]): void { try { const config = GetNativeAddonLogConfig(); const maxSeverity = config ? config.maxSeverity : AddonLogSeverity.verbose; if (severity <= maxSeverity) { let totalMessage = mapLogValue(msg); if (args.length > 0) { const argsStr = args.map(arg => mapLogValue(arg)).join(", "); totalMessage = totalMessage + " : " + argsStr; } return ylSdkInterface.NativeAddonLog(severity, caller, totalMessage); } } catch (e) { // Make sure any exceptions does not propagate. // If the console is up, shown internal error: console.error("Could not add message " + (caller || "?") + " : " + (msg || "?") + " to native log. Got error " + e); } } function mapLogValue(value: any): string | Error { if (typeof value === 'string' || value instanceof Error) { return value; } else if (typeof value === "function") { // Support lazy evaluation of messages if the msg is a function. return mapLogValue(value()); } else if (value === null) { return ""; } else if (value === undefined) { return "" } else if (value instanceof String || (value !== Object(value)) || value.hasOwnProperty('toString')) { return value.toString(); } else { return JSON.stringify(value); } } let cachedLogConfig: NativeAddonLogConfig | undefined = undefined; export function GetNativeAddonLogConfig(): NativeAddonLogConfig | undefined { if (cachedLogConfig) { return cachedLogConfig; } else { try { const config = ylSdkInterface.GetNativeAddonLogConfig(); cachedLogConfig = config; return config; } catch (e) { // Make sure any exceptions does not propagate. // If the console is up, show internal error: console.error("Could not read log configuration. Got error " + e); return undefined; } } }