From 68ed8b758d70c9346322ec5960dca12ddffeef19 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 14:54:44 +0100 Subject: [PATCH 1/8] Add logger improvement usign class instead of object --- config/default.json | 3 +- core/lib/logger.ts | 125 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 108 insertions(+), 20 deletions(-) diff --git a/config/default.json b/config/default.json index 5acb5c8941..1b68153af0 100644 --- a/config/default.json +++ b/config/default.json @@ -20,7 +20,8 @@ "useUrlDispatcher": false }, "console": { - "verbosityLevel": "only-errors" + "showErrorOnProduction" : true, + "verbosityLevel": "display-everything" }, "redis": { "host": "localhost", diff --git a/core/lib/logger.ts b/core/lib/logger.ts index eaf6d7d6f8..b64642f328 100644 --- a/core/lib/logger.ts +++ b/core/lib/logger.ts @@ -1,7 +1,94 @@ import { isServer } from '@vue-storefront/core/helpers' +import buildTimeConfig from 'config' + +const bgColorStyle = (color) => `color: white; background: ${color}; padding: 4px; font-weight: bold; font-size: 0.8em'` /** VS message logger. By default works only on dev mode */ -const Logger = { +class Logger +{ + + /** + * Logger verbosity level + */ + verbosityLevel: string; + + /** + * Is production environment + */ + isProduction: boolean; + + /** + * Force to show error on production + */ + showErrorOnProduction: boolean; + + /** + * Logger constructor + * + * @param verbosityLevel + * @param showErrorOnProduction + */ + constructor(verbosityLevel: string = 'display-everything', showErrorOnProduction: boolean = false) { + this.verbosityLevel = verbosityLevel; + this.showErrorOnProduction = showErrorOnProduction; + this.isProduction = process.env.NODE_ENV === 'production'; + } + + /** + * Check if method can print into console + * + * @param string method + */ + canPrint(method: string) { + let allowedMethods = []; + + if (this.verbosityLevel === 'display-everything' && this.isProduction === false) { + allowedMethods = ['info', 'warn', 'error', 'debug'] + } else if (this.verbosityLevel === 'only-errors' && (this.isProduction === false || this.showErrorOnProduction === true )) { + allowedMethods = ['error'] + } else if (this.verbosityLevel === 'no-console' || (this.isProduction === true && this.showErrorOnProduction === false)) { + allowedMethods = [] + } + + if (allowedMethods.indexOf(method) === -1) { + return false; + } + + return true; + } + + /** + * Inform about debug events happening in the app + * Don't forget to invoke created function after passing arguments to keep context + * `Logger.debug(...args)()` + * @param message + * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) + * @param context meaningful data related to this message + */ + debug (message: string, tag: string = null, context: any = null) : () => void { + if (!isServer && this.canPrint('debug')) { + if (tag) { + return console.debug.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('white'), 'color: inherit', bgColorStyle('gray'), 'font-weight: normal', context); + } else { + return console.debug.bind(window.console, '%cVSF%c ' + message, bgColorStyle('white'), 'font-weight: normal', context); + } + } else { + return function () {} + } + } + + /** + * Inform about log events happening in the app + * Don't forget to invoke created function after passing arguments to keep context + * `Logger.log(...args)()` + * @param message + * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) + * @param context meaningful data related to this message + */ + log (message: string, tag: string = null, context: any = null) : () => void { + return this.info(message, tag, context); + } + /** * Inform about succesful events happening in the app * Don't forget to invoke created function after passing arguments to keep context @@ -10,18 +97,18 @@ const Logger = { * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ - info : function (message: string, tag: string = null, context: any = null) : () => void { - if (!isServer) { + info (message: string, tag: string = null, context: any = null) : () => void { + if (!isServer && this.canPrint('info')) { if (tag) { - let msg ='%cVSF%c %c' + tag +'%c ' + message - return console.log.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('green'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', { context }); + return console.log.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('green'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', context); } else { - return console.log.bind(window.console, '%cVSF%c ' + message, bgColorStyle('green'), 'font-weight: bold', { context }); + return console.log.bind(window.console, '%cVSF%c ' + message, bgColorStyle('green'), 'font-weight: bold', context); } } else { return function () {} } - }, + } + /** * Inform about potential problems that may be a cause of app break * Don't forget to invoke created function after passing arguments to keep context @@ -30,17 +117,18 @@ const Logger = { * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ - warn: function (message: string, tag: string = null, context: any = null) : () => void { - if (!isServer) { + warn (message: string, tag: string = null, context: any = null) : () => void { + if (!isServer && this.canPrint('warn')) { if (tag) { - return console.warn.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('orange'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', { context }); + return console.warn.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('orange'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', context); } else { - return console.warn.bind(window.console, '%cVSF%c ' + message, bgColorStyle('orange'), 'font-weight: bold', { context }); + return console.warn.bind(window.console, '%cVSF%c ' + message, bgColorStyle('orange'), 'font-weight: bold', context); } } else { return function () {} } - }, + } + /** * Inform about errors that will break the app * Don't forget to invoke created function after passing arguments to keep context @@ -49,12 +137,12 @@ const Logger = { * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ - error: function (message: string, tag: string = null, context: any = null) : () => void { - if (!isServer) { + error (message: string, tag: string = null, context: any = null) : () => void { + if (!isServer && this.canPrint('error')) { if (tag) { - return console.error.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('red'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', { context }); + return console.error.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('red'), 'color: inherit', bgColorStyle('gray'), 'font-weight: bold', context); } else { - return console.error.bind(window.console, '%cVSF%c ' + message, bgColorStyle('red'), 'font-weight: bold', { context }); + return console.error.bind(window.console, '%cVSF%c ' + message, bgColorStyle('red'), 'font-weight: bold', context); } } else { return function () {} @@ -62,6 +150,5 @@ const Logger = { } } -const bgColorStyle = (color) => `color: white; background: ${color}; padding: 4px; font-weight: bold; font-size: 0.8em'` - -export { Logger } +const logger = new Logger(buildTimeConfig.console.verbosityLevel); +export {logger as Logger} From b5150c40e34f0cd0b0edbe5e8ceeb84c3869170d Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 14:55:11 +0100 Subject: [PATCH 2/8] Override console with logger --- core/app.ts | 8 +-- core/client-entry.ts | 48 ++++++++--------- core/helpers/index.ts | 3 +- core/i18n/index.ts | 3 +- core/lib/sync/index.ts | 8 +-- core/lib/sync/task.ts | 30 +++++------ core/mixins/composite.js | 9 ++-- core/modules/cart/store/actions.ts | 42 +++++++-------- .../components/ProductBundleOptions.ts | 3 +- .../components/ProductCustomOptions.ts | 3 +- core/modules/catalog/components/Search.ts | 4 +- core/modules/catalog/helpers/index.ts | 39 +++++++------- core/modules/catalog/helpers/tax.ts | 10 ++-- .../catalog/store/attribute/mutations.ts | 7 +-- .../modules/catalog/store/category/actions.ts | 22 ++++---- .../catalog/store/category/mutations.ts | 7 +-- core/modules/catalog/store/product/actions.ts | 51 +++++++++---------- core/modules/catalog/store/stock/actions.ts | 10 ++-- core/modules/catalog/store/tax/actions.ts | 4 +- core/modules/catalog/store/tax/mutations.ts | 3 +- .../checkout/components/OrderReview.ts | 3 +- .../checkout/store/checkout/actions.ts | 5 +- core/modules/cms/store/block/actions.ts | 5 +- core/modules/cms/store/hierarchy/actions.ts | 3 +- core/modules/cms/store/page/actions.ts | 3 +- core/modules/cms/store/plugin.ts | 7 +-- core/modules/compare/store/plugin.ts | 5 +- .../offline-order/components/CancelOrders.ts | 5 +- .../helpers/onNetworkStatusChange.ts | 4 +- core/modules/order/store/mutations.ts | 7 +-- core/modules/recently-viewed/store/plugin.ts | 1 + core/modules/review/store/actions.ts | 3 +- core/modules/user/components/Login.ts | 3 +- core/modules/user/components/Register.ts | 5 +- core/modules/user/store/actions.ts | 20 ++++---- core/modules/user/store/mutations.ts | 3 +- core/modules/wishlist/store/plugin.ts | 5 +- core/pages/Category.js | 16 +++--- core/pages/Checkout.js | 5 +- core/pages/CmsPage.js | 3 +- core/pages/Error.js | 3 +- core/pages/Home.js | 4 +- core/pages/MyAccount.js | 3 +- core/pages/PageNotFound.js | 5 +- core/pages/Product.js | 11 ++-- core/scripts/cache.js | 18 ++++--- core/scripts/resolvers/resolveGraphQL.js | 7 +-- core/server-entry.ts | 2 +- core/service-worker/registration.js | 11 ++-- core/store/lib/storage.ts | 22 ++++---- docker-compose.yml | 6 +-- docs/guide/basics/ssr-cache.md | 4 +- docs/guide/core-themes/core-components.md | 2 +- docs/guide/modules/introduction.md | 2 +- src/modules/claims/store/actions.ts | 7 +-- src/modules/index.ts | 6 +-- src/modules/magento-2-cms/store/index.js | 5 +- .../hooks/afterRegistration.ts | 6 ++- .../hooks/beforeRegistration.ts | 2 +- .../module-template/router/afterEach.ts | 5 +- .../module-template/router/beforeEach.ts | 5 +- src/modules/module-template/store/plugin.ts | 7 +-- src/modules/promoted-offers/store/actions.ts | 5 +- .../hooks/afterRegistration.ts | 4 +- 64 files changed, 307 insertions(+), 270 deletions(-) diff --git a/core/app.ts b/core/app.ts index ae1a675cd4..a393fda71e 100755 --- a/core/app.ts +++ b/core/app.ts @@ -3,6 +3,7 @@ import RootState from '@vue-storefront/core/types/RootState' import Vue from 'vue' import buildTimeConfig from 'config' import { isServer } from '@vue-storefront/core/helpers' +import { Logger } from '@vue-storefront/core/lib/logger' // Plugins import i18n from '@vue-storefront/i18n' @@ -59,13 +60,6 @@ let router: VueRouter = null Vue.use(VueRouter) -// Will be depreciated in 1.7. Now we are using Logger instead of logs -if (buildTimeConfig.console.verbosityLevel !== 'display-everything' && process.env.NODE_ENV === 'production') { - once('__TAKE_OVER_CONSOLE__', () => { - takeOverConsole(buildTimeConfig.console.verbosityLevel) - }) -} - const createApp = async (ssrContext, config): Promise<{app: Vue, router: VueRouter, store: Store}> => { router = createRouter() // sync router with vuex 'router' store diff --git a/core/client-entry.ts b/core/client-entry.ts index 0cc47e8347..bec05f40a4 100755 --- a/core/client-entry.ts +++ b/core/client-entry.ts @@ -14,6 +14,8 @@ import { prepareStoreView, storeCodeFromRoute, currentStoreView, localizedRoute import { onNetworkStatusChange } from '@vue-storefront/core/modules/offline-order/helpers/onNetworkStatusChange' import '@vue-storefront/core/service-worker/registration' // register the service worker import { AsyncDataLoader } from './lib/asyncdataloader' +import { Logger } from '@vue-storefront/core/lib/logger' + declare var window: any const invokeClientEntry = async () => { @@ -103,7 +105,7 @@ const invokeClientEntry = async () => { }) if (c.asyncData) { c.asyncData({ store, route: to }).then(result => { // always execute the asyncData() from the top most component first - console.debug('Top-most asyncData executed') + Logger.debug('Top-most asyncData executed') _ssrHydrateSubcomponents(components, next, to) }).catch(next) } else { @@ -119,7 +121,7 @@ const invokeClientEntry = async () => { * @example * const urls = ['/url1', '/url2', '/url3'] * serial(urls.map(url => () => $.ajax(url))) - * .then(console.log.bind(console)) + * .then(Logger.log.bind(Logger)) */ const serial = funcs => funcs.reduce((promise, func) => @@ -129,7 +131,7 @@ const invokeClientEntry = async () => { // TODO: move to external file EventBus.$on('order/PROCESS_QUEUE', event => { if (typeof navigator !== 'undefined' && navigator.onLine) { - console.log('Sending out orders queue to server ...') + Logger.log('Sending out orders queue to server ...') const storeView = currentStoreView() const dbNamePrefix = storeView.storeCode ? storeView.storeCode + '-' : '' @@ -153,7 +155,7 @@ const invokeClientEntry = async () => { const orderData = order const orderId = id - console.log('Pushing out order ' + orderId) + Logger.log('Pushing out order ' + orderId) return fetch(config.orders.endpoint, { method: 'POST', @@ -165,17 +167,17 @@ const invokeClientEntry = async () => { return response.json() } else { orderMutex[id] = false - console.error('Error with response - bad content-type!') + Logger.error('Error with response - bad content-type!') } }) .then(jsonResponse => { if (jsonResponse && jsonResponse.code === 200) { - console.info('SearchResponse for: ' + orderId + ' = ' + jsonResponse.result) + Logger.info('Response for: ' + orderId + ' = ' + jsonResponse.result) orderData.transmited = true orderData.transmited_at = new Date() ordersCollection.setItem(orderId.toString(), orderData) } else { - console.error(jsonResponse) + Logger.error(jsonResponse) } orderMutex[id] = false }).catch(err => { @@ -183,31 +185,31 @@ const invokeClientEntry = async () => { navigator.serviceWorker.ready.then(registration => { registration.sync.register('orderSync') .then(() => { - console.log('Order sync registered') + Logger.log('Order sync registered') }) .catch(error => { - console.log('Unable to sync', error) + Logger.log('Unable to sync', error) }) }) } - console.error('Error sending order: ' + orderId, err) + Logger.error('Error sending order: ' + orderId, err) orderMutex[id] = false }) }) } }, (err, result) => { - if (err) console.error(err) - console.log('Iteration has completed') + if (err) Logger.error(err) + Logger.log('Iteration has completed') // execute them serially serial(fetchQueue) .then(res => { - console.info('Processing orders queue has finished') + Logger.info('Processing orders queue has finished') // store.dispatch('cart/serverPull', { forceClientState: false }) }) }).catch(err => { // This code runs if there were any errors - console.log(err) + Logger.log(err) }) } }) @@ -239,11 +241,11 @@ const invokeClientEntry = async () => { usersCollection.getItem('current-token', (err, currentToken) => { // TODO: if current token is null we should postpone the queue and force re-login - only if the task requires LOGIN! if (err) { - console.error(err) + Logger.error(err) } cartsCollection.getItem('current-cart-token', (err, currentCartId) => { if (err) { - console.error(err) + Logger.error(err) } if (!currentCartId && store.state.cart.cartServerToken) { // this is workaround; sometimes after page is loaded indexedb returns null despite the cart token is properly set @@ -254,8 +256,8 @@ const invokeClientEntry = async () => { currentToken = store.state.user.token } const fetchQueue = [] - console.debug('Current User token = ' + currentToken) - console.debug('Current Cart token = ' + currentCartId) + Logger.debug('Current User token = ' + currentToken) + Logger.debug('Current Cart token = ' + currentCartId) syncTaskCollection.iterate((task, id, iterationNumber) => { if (task && !task.transmited && !mutex[id]) { // not sent to the server yet mutex[id] = true // mark this task as being processed @@ -265,19 +267,19 @@ const invokeClientEntry = async () => { mutex[id] = false }).catch(err => { mutex[id] = false - console.error(err) + Logger.error(err) }) }) } }, (err, result) => { - if (err) console.error(err) - console.debug('Iteration has completed') + if (err) Logger.error(err) + Logger.debug('Iteration has completed') // execute them serially serial(fetchQueue) - .then(res => console.debug('Processing sync tasks queue has finished')) + .then(res => Logger.debug('Processing sync tasks queue has finished')) }).catch(err => { // This code runs if there were any errors - console.log(err) + Logger.log(err) }) }) }) diff --git a/core/helpers/index.ts b/core/helpers/index.ts index d527711b0b..cb6baa74ec 100644 --- a/core/helpers/index.ts +++ b/core/helpers/index.ts @@ -1,6 +1,7 @@ import rootStore from '@vue-storefront/store' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import { remove as removeAccents } from 'remove-accents' +import { Logger } from '@vue-storefront/core/lib/logger' /** * Create slugify -> "create-slugify" permalink of text @@ -151,7 +152,7 @@ export function once (key, fn) { const { process = {} } = global const processKey = key + '__ONCE__' if (!process.hasOwnProperty(processKey)) { - console.debug(`Once ${key}`) + Logger.debug(`Once ${key}`, 'helper') process[processKey] = true fn() } diff --git a/core/i18n/index.ts b/core/i18n/index.ts index ef4896e210..5f1077c00b 100644 --- a/core/i18n/index.ts +++ b/core/i18n/index.ts @@ -1,6 +1,7 @@ import Vue from 'vue' import VueI18n from 'vue-i18n' import config from 'config' +import { Logger } from '@vue-storefront/core/lib/logger' Vue.use(VueI18n) @@ -27,7 +28,7 @@ export function loadLanguageAsync (lang: string): Promise { loadedLanguages.push(lang) return setI18nLanguage(lang) }).catch(err => { - console.debug('Unable to load translation') + Logger.debug('Unable to load translation') return '' }) } diff --git a/core/lib/sync/index.ts b/core/lib/sync/index.ts index 4ce97a8434..56be005aaa 100644 --- a/core/lib/sync/index.ts +++ b/core/lib/sync/index.ts @@ -14,11 +14,11 @@ function queue (task) { Logger.info('Sync task queued ' + task.url, 'sync', { task })() return new Promise((resolve, reject) => { tasksCollection.setItem(task.task_id.toString(), task, (err, resp) => { - if (err) console.error(err) + if (err) Logger.error(err, 'sync') Vue.prototype.$bus.$emit('sync/PROCESS_QUEUE', { config: rootStore.state.config }) // process checkout queue resolve(task) }).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'sync') // it doesn't work on SSR reject(reason) }) }) @@ -50,11 +50,11 @@ function execute (task) { // not offline task } else { usersCollection.getItem('current-token', (err, currentToken) => { // TODO: if current token is null we should postpone the queue and force re-login - only if the task requires LOGIN! if (err) { - console.error(err) + Logger.error(err, 'sync') } cartsCollection.getItem('current-cart-token', (err, currentCartId) => { if (err) { - console.error(err) + Logger.error(err, 'sync') } if (!currentCartId && rootStore.state.cart.cartServerToken) { // this is workaround; sometimes after page is loaded indexedb returns null despite the cart token is properly set currentCartId = rootStore.state.cart.cartServerToken diff --git a/core/lib/sync/task.ts b/core/lib/sync/task.ts index 06e077fbf5..ca5a297f3d 100644 --- a/core/lib/sync/task.ts +++ b/core/lib/sync/task.ts @@ -31,19 +31,19 @@ function _sleep (time) { function _internalExecute (resolve, reject, task: Task, currentToken, currentCartId) { if (currentToken !== null && rootStore.state.userTokenInvalidateLock > 0) { // invalidate lock set - console.log('Waiting for rootStore.state.userTokenInvalidateLock to release for', task.url) + Logger.log('Waiting for rootStore.state.userTokenInvalidateLock to release for '+ task.url, 'sync') _sleep(1000).then(() => { - console.log('Another try for rootStore.state.userTokenInvalidateLock for ', task.url) + Logger.log('Another try for rootStore.state.userTokenInvalidateLock for ' + task.url, 'sync') _internalExecute(resolve, reject, task, currentToken, currentCartId) }) return // return but not resolve } else if (rootStore.state.userTokenInvalidateLock < 0) { - console.error('Aborting the network task', task.url, rootStore.state.userTokenInvalidateLock) + Logger.error('Aborting the network task' + task.url + rootStore.state.userTokenInvalidateLock, 'sync') resolve({ code: 401, message: i18n.t('Error refreshing user token. User is not authorized to access the resource') }) return } else { if (rootStore.state.userTokenInvalidated) { - console.log('Using new user token', rootStore.state.userTokenInvalidated) + Logger.log('Using new user token' + rootStore.state.userTokenInvalidated, 'sync') currentToken = rootStore.state.userTokenInvalidated } } @@ -59,7 +59,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar return response.json() } else { const msg = i18n.t('Error with response - bad content-type!') - console.error(msg) + Logger.error(msg.toString(), 'sync') reject(msg) } }).then((jsonResponse) => { @@ -67,7 +67,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar if (parseInt(jsonResponse.code) !== 200) { let resultString = jsonResponse.result ? toString(jsonResponse.result) : null if (resultString && (resultString.indexOf(i18n.t('not authorized')) >= 0 || resultString.indexOf('not authorized')) >= 0 && currentToken !== null) { // the token is no longer valid, try to invalidate it - console.error('Invalid token - need to be revalidated', currentToken, task.url, rootStore.state.userTokenInvalidateLock) + Logger.error('Invalid token - need to be revalidated' + currentToken + task.url + rootStore.state.userTokenInvalidateLock, 'sync') if (isNaN(rootStore.state.userTokenInvalidateAttemptsCount) || isUndefined(rootStore.state.userTokenInvalidateAttemptsCount)) rootStore.state.userTokenInvalidateAttemptsCount = 0 if (isNaN(rootStore.state.userTokenInvalidateLock) || isUndefined(rootStore.state.userTokenInvalidateLock)) rootStore.state.userTokenInvalidateLock = 0 @@ -76,7 +76,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar if (!rootStore.state.userTokenInvalidateLock) { rootStore.state.userTokenInvalidateLock++ if (rootStore.state.userTokenInvalidateAttemptsCount >= AUTO_REFRESH_MAX_ATTEMPTS) { - console.error('Internal Application error while refreshing the tokens. Please clear the storage and refresh page.') + Logger.error('Internal Application error while refreshing the tokens. Please clear the storage and refresh page.', 'sync') rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) TaskQueue.clearNotTransmited() @@ -88,32 +88,32 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar }) rootStore.state.userTokenInvalidateAttemptsCount = 0 } else { - console.info('Invalidation process in progress (autoRefreshTokens is set to true)', rootStore.state.userTokenInvalidateAttemptsCount, rootStore.state.userTokenInvalidateLock) + Logger.info('Invalidation process in progress (autoRefreshTokens is set to true)' + rootStore.state.userTokenInvalidateAttemptsCount + rootStore.state.userTokenInvalidateLock, 'sync') rootStore.state.userTokenInvalidateAttemptsCount++ rootStore.dispatch('user/refresh').then((resp) => { if (resp.code === 200) { rootStore.state.userTokenInvalidateLock = 0 rootStore.state.userTokenInvalidated = resp.result - console.info('User token refreshed successfully', resp.result) + Logger.info('User token refreshed successfully' + resp.result, 'sync') } else { rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') TaskQueue.clearNotTransmited() - console.error('Error refreshing user token', resp.result) + Logger.error('Error refreshing user token' + resp.result, 'sync') } }).catch((excp) => { rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') TaskQueue.clearNotTransmited() - console.error('Error refreshing user token', excp) + Logger.error('Error refreshing user token' + excp, 'sync') }) } } if (rootStore.state.userTokenInvalidateAttemptsCount <= AUTO_REFRESH_MAX_ATTEMPTS) _internalExecute(resolve, reject, task, currentToken, currentCartId) // retry } else { - console.info('Invalidation process is disabled (autoRefreshTokens is set to false)') + Logger.info('Invalidation process is disabled (autoRefreshTokens is set to false)', 'sync') rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') } @@ -126,7 +126,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar }) } } - console.debug('SearchResponse for: ' + task.task_id + ' = ' + jsonResponse.result) + Logger.debug('Response for: ' + task.task_id + ' = ' + jsonResponse.result, 'sync') task.transmited = true task.transmited_at = new Date() task.result = jsonResponse.result @@ -146,11 +146,11 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar } } else { const msg = i18n.t('Unhandled error, wrong response format!') - console.error(msg) + Logger.error(msg.toString(), 'sync') reject(msg) } }).catch((err) => { - console.error(err) + Logger.error(err, 'sync') reject(err) }) } diff --git a/core/mixins/composite.js b/core/mixins/composite.js index 5196a7c9cd..cf8f3dd812 100644 --- a/core/mixins/composite.js +++ b/core/mixins/composite.js @@ -1,25 +1,26 @@ import EventBus from '@vue-storefront/core/compatibility/plugins/event-bus' +import { Logger } from '@vue-storefront/core/lib/logger' // to be depreciated export default { beforeCreated () { const eventName = this.$options.name.toLowerCase() + '-before-created' - console.debug(eventName) + Logger.debug(eventName, 'event') EventBus.$emit(eventName, this) }, created () { const eventName = this.$options.name.toLowerCase() + '-after-created' - console.debug(eventName) + Logger.debug(eventName, 'event') EventBus.$emit(eventName, this) }, beforeMount () { const eventName = this.$options.name.toLowerCase() + '-before-mount' - console.debug(eventName) + Logger.debug(eventName, 'event') EventBus.$emit(eventName, this) }, mounted () { const eventName = this.$options.name.toLowerCase() + '-after-mounted' - console.debug(eventName) + Logger.debug(eventName, 'event') EventBus.$emit(eventName, this) } diff --git a/core/modules/cart/store/actions.ts b/core/modules/cart/store/actions.ts index 450663baf6..50dea381d6 100644 --- a/core/modules/cart/store/actions.ts +++ b/core/modules/cart/store/actions.ts @@ -29,7 +29,7 @@ function _updateClientItem (event, clientItem) { } function _afterServerItemUpdated (event, clientItem = null) { - console.debug('Cart item server sync', event) + Logger.debug('Cart item server sync' + event, 'cart') if (clientItem === null) { rootStore.dispatch('cart/getItem', event.result.sku, { root: true }).then((cartItem) => { if (cartItem) { @@ -75,7 +75,7 @@ const actions: ActionTree = { const storeView = currentStoreView() if ((Date.now() - context.state.cartServerMethodsRefreshAt) >= CART_METHODS_INTERVAL_MS) { context.state.cartServerMethodsRefreshAt = Date.now() - console.debug('Refreshing payment & shipping methods') + Logger.debug('Refreshing payment & shipping methods', 'cart') rootStore.dispatch('cart/getPaymentMethods') if (context.state.cartItems.length > 0) { let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : storeView.tax.defaultCountry @@ -86,7 +86,7 @@ const actions: ActionTree = { } }) } else { - console.log('Too short interval for refreshing the cart or items not changed', newItemsHash, context.state.cartItemsHash) + Logger.log('Too short interval for refreshing the cart or items not changed' + newItemsHash + context.state.cartItemsHash, 'cart') } } }, @@ -105,7 +105,7 @@ const actions: ActionTree = { callback_event: 'store:cart/servercartAfterTotals' }) } else { - console.log('Too short interval for refreshing the cart totals') + Logger.log('Too short interval for refreshing the cart totals', 'cart') } } }, @@ -355,7 +355,7 @@ const actions: ActionTree = { rootStore.dispatch('payment/replaceMethods', paymentMethods, { root: true }) Vue.prototype.$bus.$emit('set-unique-payment-methods', uniqueBackendMethods) }).catch(e => { - console.error(e) + Logger.error(e, 'cart') }) } }, @@ -376,7 +376,7 @@ const actions: ActionTree = { rootStore.dispatch('shipping/replaceMethods', task.result, { root: true }) } }).catch(e => { - console.error(e) + Logger.error(e, 'cart') }) } }, @@ -421,7 +421,7 @@ const actions: ActionTree = { silent: true, callback_event: 'store:cart/servercartAfterTotals' }).catch(e => { - console.error(e) + Logger.error(e, 'cart') }) } else { context.dispatch('cart/serverTotals', {}, { root: true }) @@ -444,7 +444,7 @@ const actions: ActionTree = { resolve(task.result) } }).catch(e => { - console.error(e) + Logger.error(e, 'cart') reject(e) }) } @@ -468,7 +468,7 @@ const actions: ActionTree = { reject(false) } }).catch(e => { - console.log(e) + Logger.log(e, 'cart') reject(e) }) } @@ -477,7 +477,7 @@ const actions: ActionTree = { userAfterLoggedin () { Vue.prototype.$db.usersCollection.getItem('last-cart-bypass-ts', (err, lastCartBypassTs) => { if (err) { - console.error(err) + Logger.error(err, 'cart') } if (!rootStore.state.config.cart.bypassCartLoaderForAuthorizedUsers || (Date.now() - lastCartBypassTs) >= (1000 * 60 * 24)) { // don't refresh the shopping cart id up to 24h after last order rootStore.dispatch('cart/serverCreate', { guestCart: false }, { root: true }) @@ -494,10 +494,10 @@ const actions: ActionTree = { let resultString = event.result ? toString(event.result) : null if (resultString && (resultString.indexOf(i18n.t('not authorized')) < 0 && resultString.indexOf('not authorized')) < 0) { // not respond to unathorized errors here if (rootStore.state.cart.bypassCount < MAX_BYPASS_COUNT) { - console.log('Bypassing with guest cart', rootStore.state.cart.bypassCount) + Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart') rootStore.state.cart.bypassCount = rootStore.state.cart.bypassCount + 1 rootStore.dispatch('cart/serverCreate', { guestCart: true }, { root: true }) - console.error(event.result) + Logger.error(event.result, 'cart') } } } @@ -515,7 +515,7 @@ const actions: ActionTree = { } rootStore.commit(types.SN_CART + '/' + types.CART_UPD_TOTALS, { itemsAfterTotal: itemsAfterTotal, totals: totalsObj, platformTotalSegments: platformTotalSegments }) } else { - console.error(event.result) + Logger.error(event.result, 'cart') } }, servercartAfterPulled (context, event) { @@ -568,7 +568,7 @@ const actions: ActionTree = { } } } else if (serverItem.qty !== clientItem.qty) { - console.log('Wrong qty for ' + clientItem.sku, clientItem.qty, serverItem.qty) + Logger.log('Wrong qty for ' + clientItem.sku, clientItem.qty, serverItem.qty) diffLog.push({ 'party': 'server', 'sku': clientItem.sku, 'status': 'wrong_qty', 'client_qty': clientItem.qty, 'server_qty': serverItem.qty }) if (!event.dry_run) { if (event.force_client_state || !rootStore.state.config.cart.serverSyncCanModifyLocalItems) { @@ -589,8 +589,8 @@ const actions: ActionTree = { } } } else { - Logger.info('Server and client item with SKU ' + clientItem.sku + ' synced. Updating cart.', 'cart')() - // console.log('Updating server id to ', { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option }) + Logger.info('Server and client item with SKU ' + clientItem.sku + ' synced. Updating cart.', 'cart', 'cart') + // Logger.log('Updating server id to ', { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option }) if (!event.dry_run) { rootStore.dispatch('cart/updateItem', { product: { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option } }, { root: true }) } @@ -610,7 +610,7 @@ const actions: ActionTree = { if (event.force_client_state) { Logger.info('Removing product from cart', 'cart', serverItem)() - console.log('Removing item', serverItem.sku, serverItem.item_id) + Logger.log('Removing item' + serverItem.sku + serverItem.item_id, 'cart') serverCartUpdateRequired = true rootStore.dispatch('cart/serverDeleteItem', { sku: serverItem.sku, @@ -658,12 +658,12 @@ const actions: ActionTree = { Vue.prototype.$bus.$emit('servercart-after-diff', { diffLog: diffLog, serverItems: serverItems, clientItems: clientItems, dryRun: event.dry_run, event: event }) // send the difflog Logger.info('Client/Server cart synchronised ', 'cart', diffLog)() } else { - console.error(event.result) // override with guest cart + Logger.error(event.result, 'cart') // override with guest cart if (rootStore.state.cart.bypassCount < MAX_BYPASS_COUNT) { - console.log('Bypassing with guest cart', rootStore.state.cart.bypassCount) + Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart') rootStore.state.cart.bypassCount = rootStore.state.cart.bypassCount + 1 rootStore.dispatch('cart/serverCreate', { guestCart: true }, { root: true }) - console.error(event.result) + Logger.error(event.result, 'cart') } } }, @@ -674,7 +674,7 @@ const actions: ActionTree = { if (originalCartItem.item_id) { rootStore.dispatch('cart/getItem', originalCartItem.sku, { root: true }).then((cartItem) => { if (cartItem) { - console.log('Restoring qty after error', originalCartItem.sku, cartItem.prev_qty) + Logger.log('Restoring qty after error' + originalCartItem.sku + cartItem.prev_qty, 'cart') if (cartItem.prev_qty > 0) { rootStore.dispatch('cart/updateItem', { product: { qty: cartItem.prev_qty } }, { root: true }) // update the server_id reference Vue.prototype.$bus.$emit('cart-after-itemchanged', { item: cartItem }) diff --git a/core/modules/catalog/components/ProductBundleOptions.ts b/core/modules/catalog/components/ProductBundleOptions.ts index a508193b97..324b14c8a7 100644 --- a/core/modules/catalog/components/ProductBundleOptions.ts +++ b/core/modules/catalog/components/ProductBundleOptions.ts @@ -2,6 +2,7 @@ import { mapMutations } from 'vuex' import * as types from '../store/product/mutation-types' import rootStore from '@vue-storefront/store' import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' function _fieldName (co) { return ['bundleOption_' + co.option_id, 'bundleOptionQty_' + co.option_id] @@ -96,7 +97,7 @@ export const ProductBundleOptions = { this.product.errors['bundle_options_' + fieldName] = null } } else { - console.error('No validation rule found for ', validationRule) + Logger.error('No validation rule found for ' + validationRule, 'components-product-bundle-options') this.$set(this.validationResults, fieldName, validationResult) } } else { diff --git a/core/modules/catalog/components/ProductCustomOptions.ts b/core/modules/catalog/components/ProductCustomOptions.ts index 1c8b46e974..cc359650bf 100644 --- a/core/modules/catalog/components/ProductCustomOptions.ts +++ b/core/modules/catalog/components/ProductCustomOptions.ts @@ -2,6 +2,7 @@ import { mapMutations } from 'vuex' import * as types from '../store/product/mutation-types' import rootStore from '@vue-storefront/store' import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' function _defaultOptionValue (co) { switch (co.type) { @@ -82,7 +83,7 @@ export const ProductCustomOptions = { this.product.errors['custom_options_' + fieldName] = null } } else { - console.error('No validation rule found for ', validationRule) + Logger.error('No validation rule found for ' + validationRule, 'components-product-custom-options') this.validation.results[fieldName] = { error: false, message: '' } } } else { diff --git a/core/modules/catalog/components/Search.ts b/core/modules/catalog/components/Search.ts index 05b447e5e2..5e620773f5 100644 --- a/core/modules/catalog/components/Search.ts +++ b/core/modules/catalog/components/Search.ts @@ -40,7 +40,7 @@ export const Search = { this.start = this.start + this.size this.emptyResults = resp.items.length < 1 }).catch((err) => { - console.error(err) + Logger.error(err, 'components-search') }) } else { this.products = [] @@ -60,7 +60,7 @@ export const Search = { this.start = this.start + this.size this.emptyResults = this.products.length < 1 }).catch((err) => { - console.error(err) + Logger.error(err, 'components-search') }) } else { this.products = [] diff --git a/core/modules/catalog/helpers/index.ts b/core/modules/catalog/helpers/index.ts index 5973b5330a..816b0e31eb 100644 --- a/core/modules/catalog/helpers/index.ts +++ b/core/modules/catalog/helpers/index.ts @@ -12,6 +12,7 @@ import { optionLabel } from './optionLabel' import i18n from '@vue-storefront/i18n' import { currentStoreView } from '@vue-storefront/core/lib/multistore' import { getThumbnailPath } from '@vue-storefront/core/helpers' +import { Logger } from '@vue-storefront/core/lib/logger' function _filterRootProductByStockitem (context, stockItem, product, errorCallback) { if (stockItem) { @@ -56,7 +57,7 @@ function _filterChildrenByStockitem (context, stockItems, product, diffLog) { config[optionKey] = opt const variant = isOptionAvailableAsync(context, { product: product, configuration: config }) if (!variant) { - console.log('No variant for', opt) + Logger.log('No variant for' + opt, 'helper') Vue.prototype.$bus.$emit('product-after-removevariant', { product: product }) removedOptions++ return false @@ -65,7 +66,7 @@ function _filterChildrenByStockitem (context, stockItems, product, diffLog) { return true } }) - console.debug('Options still available', optionsAvailable, removedOptions) + Logger.debug('Options still available' + optionsAvailable + removedOptions, 'helper') context.state.current_options[optionKey] = optionsAvailable } } @@ -93,24 +94,24 @@ export function filterOutUnavailableVariants (context, product) { confChildSkus = remove(confChildSkus, (skuToCheck) => skuToCheck === confChild.sku) } } - console.debug('Cached stock items and delta', stockItems, confChildSkus) + Logger.debug('Cached stock items and delta' + stockItems + confChildSkus) if (confChildSkus.length > 0) { context.dispatch('stock/list', { skus: confChildSkus }, {root: true}).then((task) => { if (task && task.resultCode === 200) { const diffLog = [] _filterChildrenByStockitem(context, union(task.result, stockItems), product, diffLog) - console.debug('Filtered configurable_children with the network call', diffLog) + Logger.debug('Filtered configurable_children with the network call' + diffLog, 'helper') resolve() } else { - console.error('Cannot sync the availability of the product options. Please update the vue-storefront-api or switch on the Internet :)') + Logger.error('Cannot sync the availability of the product options. Please update the vue-storefront-api or switch on the Internet :)', 'helper') } }).catch(err => { - console.error(err) + Logger.error(err, 'helper') }) } else { const diffLog = [] _filterChildrenByStockitem(context, stockItems, product, diffLog) - console.debug('Filtered configurable_children without the network call', diffLog) + Logger.debug('Filtered configurable_children without the network call' + diffLog, 'helper') resolve() } } else { @@ -121,12 +122,12 @@ export function filterOutUnavailableVariants (context, product) { if (!rootStockCached) { context.dispatch('stock/list', { skus: [product.sku] }, {root: true}).then((task) => { _filterRootProductByStockitem(context, task && task.result && task.result.length ? task.result[0] : null, product, reject) - console.debug('Filtered root product stock with the network call') + Logger.debug('Filtered root product stock with the network call') _filterConfigurableHelper() }) } else { _filterRootProductByStockitem(context, rootStockCached, product, reject) - console.debug('Filtered root product stock without the network call') + Logger.debug('Filtered root product stock without the network call') _filterConfigurableHelper() } } else { @@ -156,7 +157,7 @@ export function syncProductPrice (product, backProduct) { // TODO: we probably n product.special_price = 0 // the same price as original; it's not a promotion } Vue.prototype.$bus.$emit('product-after-priceupdate', product) - // console.log(product.sku, product, backProduct) + // Logger.log(product.sku, product, backProduct) return product } /** @@ -205,7 +206,7 @@ export function doPlatformPricesSync (products) { skus = union(skus, childSkus) } if (skus && skus.length > 0) { - console.log('Starting platform prices sync for', skus) // TODO: add option for syncro and non syncro return + Logger.log('Starting platform prices sync for', skus) // TODO: add option for syncro and non syncro return rootStore.dispatch('product/syncPlatformPricesOver', { skus: skus }, { root: true }).then((syncResult) => { if (syncResult) { syncResult = syncResult.items @@ -235,7 +236,7 @@ export function doPlatformPricesSync (products) { resolve(products) } if (!rootStore.state.config.products.waitForPlatformSync && !Vue.prototype.$isServer) { - console.log('Returning products, the prices yet to come from backend!') + Logger.log('Returning products, the prices yet to come from backend!') for (let product of products) { product.price_is_current = false // in case we're syncing up the prices we should mark if we do have current or not product.price_refreshed_at = null @@ -254,7 +255,7 @@ export function doPlatformPricesSync (products) { export function calculateTaxes (products, store) { return new Promise((resolve, reject) => { if (rootStore.state.config.tax.calculateServerSide) { - console.debug('Taxes calculated server side, skipping') + Logger.debug('Taxes calculated server side, skipping') doPlatformPricesSync(products).then((products) => { resolve(products) }) @@ -298,7 +299,7 @@ export function setConfigurableProductOptionsAsync (context, { product, configur }) if (!option) { - console.error('Wrong option id for setProductOptions', configOption.attribute_code) + Logger.error('Wrong option id for setProductOptions', configOption.attribute_code) return null } let existingOption = configurable_item_options.find(cop => { @@ -318,7 +319,7 @@ export function setConfigurableProductOptionsAsync (context, { product, configur existingOption.value = configOption.label } } - // console.debug('Server product options object', product_option) + // Logger.debug('Server product options object', product_option) return product_option } else { return null @@ -359,7 +360,7 @@ export function populateProductConfigurationAsync (context, { product, selectedV if (option.attribute_id) { let attr = context.rootState.attribute.list_by_id[option.attribute_id] if (!attr) { - console.error('Wrong attribute given in configurable_options - can not find by attribute_id', option) + Logger.error('Wrong attribute given in configurable_options - can not find by attribute_id', option) continue } else { attribute_code = attr.attribute_code @@ -367,7 +368,7 @@ export function populateProductConfigurationAsync (context, { product, selectedV } } else { if (!option.attribute_code) { - console.error('Wrong attribute given in configurable_options - no attribute_code', option) + Logger.error('Wrong attribute given in configurable_options - no attribute_code', option) continue } else { // we do have attribute_code! attribute_code = option.attribute_code @@ -476,7 +477,7 @@ export function configureProductAsync (context, { product, configuration, select if (typeof navigator !== 'undefined') { if (selectedVariant && !navigator.onLine && context.state.offlineImage) { // this is fix for not preloaded images for offline selectedVariant.image = context.state.offlineImage - console.debug('Image offline fallback to ', context.state.offlineImage) + Logger.debug('Image offline fallback to ', context.state.offlineImage) } } if (selectedVariant) { @@ -497,7 +498,7 @@ export function configureProductAsync (context, { product, configuration, select selectedVariant.options = _internalMapOptions(productOption) } }/* else { - console.debug('Skipping configurable options setup', configuration) + Logger.debug('Skipping configurable options setup', configuration) } */ const fieldsToOmit = ['name'] if (selectedVariant.image === "") fieldsToOmit.push('image') diff --git a/core/modules/catalog/helpers/tax.ts b/core/modules/catalog/helpers/tax.ts index a602a86498..006ea96357 100644 --- a/core/modules/catalog/helpers/tax.ts +++ b/core/modules/catalog/helpers/tax.ts @@ -1,3 +1,5 @@ +import { Logger } from '@vue-storefront/core/lib/logger' + function isSpecialPriceActive(fromDate, toDate) { const now = new Date() fromDate = new Date(fromDate) || false @@ -124,18 +126,18 @@ export function calculateProductTax (product, taxClasses, taxCountry = 'PL', tax if (rate.tax_country_id === taxCountry && (rate.region_name === taxRegion || rate.tax_region_id === 0 || !rate.region_name)) { updateProductPrices(product, rate, sourcePriceInclTax) rateFound = true - console.debug('Tax rate ' + rate.code + ' = ' + rate.rate + '% found for ' + taxCountry + ' / ' + taxRegion) + Logger.debug('Tax rate ' + rate.code + ' = ' + rate.rate + '% found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax') break } } } else { - console.debug('No such tax class id: ' + product.tax_class_id) + Logger.debug('No such tax class id: ' + product.tax_class_id, 'helper-tax') } } else { - console.debug('No tax class set for: ' + product.sku) + Logger.debug('No tax class set for: ' + product.sku, 'helper-tax') } if (!rateFound) { - console.log('No such tax class id: ' + product.tax_class_id + ' or rate not found for ' + taxCountry + ' / ' + taxRegion) + Logger.log('No such tax class id: ' + product.tax_class_id + ' or rate not found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax') updateProductPrices(product, {rate: 0}) product.priceInclTax = product.price diff --git a/core/modules/catalog/store/attribute/mutations.ts b/core/modules/catalog/store/attribute/mutations.ts index 52cb8d02f3..27e963bdda 100644 --- a/core/modules/catalog/store/attribute/mutations.ts +++ b/core/modules/catalog/store/attribute/mutations.ts @@ -3,6 +3,7 @@ import { MutationTree } from 'vuex' import { entityKeyName } from '@vue-storefront/store/lib/entities' import * as types from './mutation-types' import AttributeState from '../../types/AttributeState' +import { Logger } from '@vue-storefront/core/lib/logger' const mutations: MutationTree = { /** @@ -22,13 +23,13 @@ const mutations: MutationTree = { const attrCollection = Vue.prototype.$db.attributesCollection try { attrCollection.setItem(entityKeyName('attribute_code', attr.attribute_code.toLowerCase()), attr).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'mutations') // it doesn't work on SSR }) // populate cache by slug attrCollection.setItem(entityKeyName('attribute_id', attr.attribute_id.toString()), attr).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'mutations') // it doesn't work on SSR }) // populate cache by id } catch (e) { - console.error(e) + Logger.error(e, 'mutations') } } Vue.set(state, 'list_by_code', attrHashByCode) diff --git a/core/modules/catalog/store/category/actions.ts b/core/modules/catalog/store/category/actions.ts index a4936ae698..cb74bddca8 100644 --- a/core/modules/catalog/store/category/actions.ts +++ b/core/modules/catalog/store/category/actions.ts @@ -110,7 +110,7 @@ const actions: ActionTree = { return } if (error) { - console.error(error) + Logger.error(error) reject(error) } @@ -138,7 +138,7 @@ const actions: ActionTree = { recurCatFinder(sc) } }).catch(err => { - console.error(err) + Logger.error(err) commit(types.CATEGORY_UPD_CURRENT_CATEGORY_PATH, currentPath) // this is the case when category is not binded to the root tree - for example 'Erin Recommends' resolve(mainCategory) }) @@ -200,13 +200,13 @@ const actions: ActionTree = { includeFields = rootStore.state.config.entities.productListWithChildren.includeFields // we need configurable_children for filters to work excludeFields = rootStore.state.config.entities.productListWithChildren.excludeFields prefetchGroupProducts = false - console.log('Using two stage caching for performance optimization - executing first stage product pre-fetching') + Logger.log('Using two stage caching for performance optimization - executing first stage product pre-fetching') } else { prefetchGroupProducts = true if (rootStore.state.twoStageCachingDisabled) { - console.log('Two stage caching is disabled runtime because of no performance gain') + Logger.log('Two stage caching is disabled runtime because of no performance gain') } else { - console.log('Two stage caching is disabled by the config') + Logger.log('Two stage caching is disabled by the config') } } let t0 = new Date().getTime() @@ -313,7 +313,7 @@ const actions: ActionTree = { } return subloaders }).catch((err) => { - console.error(err) + Logger.error(err) rootStore.dispatch('notification/spawnNotification', { type: 'warning', message: i18n.t('No products synchronized for this category. Please come back while online!'), @@ -322,7 +322,7 @@ const actions: ActionTree = { }) if (rootStore.state.config.entities.twoStageCaching && rootStore.state.config.entities.optimize && !Vue.prototype.$isServer && !rootStore.state.twoStageCachingDisabled) { // second stage - request for caching entities - console.log('Using two stage caching for performance optimization - executing second stage product caching') // TODO: in this case we can pre-fetch products in advance getting more products than set by pageSize + Logger.log('Using two stage caching for performance optimization - executing second stage product caching', 'category') // TODO: in this case we can pre-fetch products in advance getting more products than set by pageSize rootStore.dispatch('product/list', { query: precachedQuery, start: current, @@ -331,15 +331,15 @@ const actions: ActionTree = { includeFields: null, updateState: false // not update the product listing - this request is only for caching }).catch((err) => { - console.info("Problem with second stage caching - couldn't store the data") - console.info(err) + Logger.info("Problem with second stage caching - couldn't store the data", 'category') + Logger.info(err, 'category') }).then((res) => { let t2 = new Date().getTime() rootStore.state.twoStageCachingDelta2 = t2 - t0 - console.log('Using two stage caching for performance optimization - Time comparison stage1 vs stage2', rootStore.state.twoStageCachingDelta1, rootStore.state.twoStageCachingDelta2) + Logger.log('Using two stage caching for performance optimization - Time comparison stage1 vs stage2' + rootStore.state.twoStageCachingDelta1 + rootStore.state.twoStageCachingDelta2, 'category') if (rootStore.state.twoStageCachingDelta1 > rootStore.state.twoStageCachingDelta2) { // two stage caching is not making any good rootStore.state.twoStageCachingDisabled = true - console.log('Disabling two stage caching') + Logger.log('Disabling two stage caching', 'category') } }) } diff --git a/core/modules/catalog/store/category/mutations.ts b/core/modules/catalog/store/category/mutations.ts index c05fd9a5bb..498a464b9e 100644 --- a/core/modules/catalog/store/category/mutations.ts +++ b/core/modules/catalog/store/category/mutations.ts @@ -5,6 +5,7 @@ import { slugify, breadCrumbRoutes } from '@vue-storefront/core/helpers' import { entityKeyName } from '@vue-storefront/store/lib/entities' import CategoryState from '../../types/CategoryState' import rootStore from '@vue-storefront/store' +import { Logger } from '@vue-storefront/core/lib/logger' const mutations: MutationTree = { [types.CATEGORY_UPD_CURRENT_CATEGORY] (state, category) { @@ -32,13 +33,13 @@ const mutations: MutationTree = { const catCollection = Vue.prototype.$db.categoriesCollection try { catCollection.setItem(entityKeyName('slug', category.slug.toLowerCase()), category).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'category') // it doesn't work on SSR }) // populate cache by slug catCollection.setItem(entityKeyName('id', category.id), category).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'category') // it doesn't work on SSR }) // populate cache by id } catch (e) { - console.error(e) + Logger.error(e, 'category') } } } diff --git a/core/modules/catalog/store/product/actions.ts b/core/modules/catalog/store/product/actions.ts index a272eca0e7..d5c228621d 100644 --- a/core/modules/catalog/store/product/actions.ts +++ b/core/modules/catalog/store/product/actions.ts @@ -84,13 +84,13 @@ const actions: ActionTree = { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) }).catch(err => { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) - console.error(err) + Logger.error(err) }) } else { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) } }).catch(err => { - console.error(err) + Logger.error(err) }) ) } @@ -131,17 +131,17 @@ const actions: ActionTree = { if (product.type_id === 'grouped') { product.price = 0 product.priceInclTax = 0 - console.debug(product.name + ' SETUP ASSOCIATED', product.type_id) + Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id) if (product.product_links && product.product_links.length > 0) { for (let pl of product.product_links) { if (pl.link_type === 'associated' && pl.linked_product_type === 'simple') { // prefetch links - console.debug('Prefetching grouped product link for ' + pl.sku + ' = ' + pl.linked_product_sku) + Logger.debug('Prefetching grouped product link for ' + pl.sku + ' = ' + pl.linked_product_sku) subloaders.push(context.dispatch('single', { options: { sku: pl.linked_product_sku }, setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { console.error(err) }).then((asocProd) => { + }).catch(err => { Logger.error(err) }).then((asocProd) => { if (asocProd) { pl.product = asocProd pl.product.qty = 1 @@ -149,31 +149,31 @@ const actions: ActionTree = { product.priceInclTax += pl.product.priceInclTax product.tax += pl.product.tax } else { - console.error('Product link not found', pl.linked_product_sku) + Logger.error('Product link not found', pl.linked_product_sku) } })) } } } else { - console.error('Product with type grouped has no product_links set!', product) + Logger.error('Product with type grouped has no product_links set!', product) } } if (product.type_id === 'bundle') { product.price = 0 product.priceInclTax = 0 - console.debug(product.name + ' SETUP ASSOCIATED', product.type_id) + Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id) if (product.bundle_options && product.bundle_options.length > 0) { for (let bo of product.bundle_options) { let defaultOption = bo.product_links.find((p) => { return p.is_default }) if (!defaultOption) defaultOption = bo.product_links[0] for (let pl of bo.product_links) { - console.debug('Prefetching bundle product link for ' + bo.sku + ' = ' + pl.sku) + Logger.debug('Prefetching bundle product link for ' + bo.sku + ' = ' + pl.sku) subloaders.push(context.dispatch('single', { options: { sku: pl.sku }, setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { console.error(err) }).then((asocProd) => { + }).catch(err => { Logger.error(err) }).then((asocProd) => { if (asocProd) { pl.product = asocProd pl.product.qty = pl.qty @@ -184,7 +184,7 @@ const actions: ActionTree = { product.tax += pl.product.tax * pl.product.qty } } else { - console.error('Product link not found', pl.sku) + Logger.error('Product link not found', pl.sku) } })) } @@ -199,7 +199,7 @@ const actions: ActionTree = { */ checkConfigurableParent (context, {product}) { if (product.type_id === 'simple') { - console.log('Checking configurable parent') + Logger.log('Checking configurable parent') let searchQuery = new SearchQuery() searchQuery = searchQuery.applyFilter({key: 'configurable_children.sku', value: {'eq': context.state.current.sku}}) @@ -210,7 +210,7 @@ const actions: ActionTree = { context.commit(types.CATALOG_SET_PRODUCT_PARENT, parentProduct) } }).catch((err) => { - console.error(err) + Logger.error(err) }) } }, @@ -257,7 +257,7 @@ const actions: ActionTree = { let selectedVariant = context.state.current populateProductConfigurationAsync(context, { selectedVariant: selectedVariant, product: product }) }).catch(err => { - console.error(err) + Logger.error(err) })) } return Promise.all(subloaders) @@ -277,9 +277,9 @@ const actions: ActionTree = { list (context, { query, start = 0, size = 50, entityType = 'product', sort = '', cacheByKey = 'sku', prefetchGroupProducts = true, updateState = false, meta = {}, excludeFields = null, includeFields = null, configuration = null, append = false, populateRequestCacheTags = true }) { let isCacheable = (includeFields === null && excludeFields === null) if (isCacheable) { - console.debug('Entity cache is enabled for productList') + Logger.debug('Entity cache is enabled for productList') } else { - console.debug('Entity cache is disabled for productList') + Logger.debug('Entity cache is disabled for productList') } if (rootStore.state.config.entities.optimize) { @@ -330,7 +330,7 @@ const actions: ActionTree = { if (isCacheable) { // store cache only for full loads cache.setItem(cacheKey, prod) .catch((err) => { - console.error('Cannot store cache for ' + cacheKey, err) + Logger.error('Cannot store cache for ' + cacheKey, err) }) } if ((prod.type_id === 'grouped' || prod.type_id === 'bundle') && prefetchGroupProducts) { @@ -460,14 +460,11 @@ const actions: ActionTree = { cache.getItem(cacheKey, (err, res) => { // report errors if (!skipCache && err) { - console.error({ - info: 'Get item from cache in ./store/modules/product.js', - err - }) + Logger.error(err, 'product') } if (res !== null) { - console.debug('Product:single - result from localForage (for ' + cacheKey + '), ms=' + (new Date().getTime() - benchmarkTime.getTime())) + Logger.debug('Product:single - result from localForage (for ' + cacheKey + '), ms=' + (new Date().getTime() - benchmarkTime.getTime()), 'product') const _returnProductFromCacheHelper = (subresults) => { const cachedProduct = setupProduct(res) if (rootStore.state.config.products.alwaysSyncPlatformPricesOver) { @@ -565,7 +562,7 @@ const actions: ActionTree = { if (!context.state.offlineImage) { context.state.offlineImage = productThumbnailPath(productOriginal, true) - console.debug('Image offline fallback set to ', context.state.offlineImage) + Logger.debug('Image offline fallback set to ' + context.state.offlineImage, 'product') } // check if passed variant is the same as original const productUpdated = Object.assign({}, productOriginal, productVariant) @@ -574,7 +571,7 @@ const actions: ActionTree = { context.commit(types.CATALOG_UPD_GALLERY, attributeImages(productVariant)) } context.commit(types.CATALOG_SET_PRODUCT_CURRENT, productUpdated) - } else console.debug('Unable to update current product.') + } else Logger.debug('Unable to update current product.', 'product') }, /** * Set given product as original @@ -583,7 +580,7 @@ const actions: ActionTree = { */ setOriginal (context, originalProduct) { if (originalProduct && typeof originalProduct === 'object') context.commit(types.CATALOG_SET_PRODUCT_ORIGINAL, originalProduct) - else console.debug('Unable to setup original product.') + else Logger.debug('Unable to setup original product.', 'product') }, /** * Set related products @@ -674,7 +671,7 @@ const actions: ActionTree = { */ fetchAsync (context, { parentSku, childSku = null, route = null }) { if (context.state.productLoadStart && (Date.now() - context.state.productLoadStart) < PRODUCT_REENTER_TIMEOUT) { - console.log('Product is being fetched ...') + Logger.log('Product is being fetched ...', 'product') } else { context.state.productLoadPromise = new Promise((resolve, reject) => { context.state.productLoadStart = Date.now() @@ -688,7 +685,7 @@ const actions: ActionTree = { return resolve() }).catch((err) => { context.state.productLoadStart = null - console.error(err) + Logger.error(err, 'product') return resolve() }) }).catch(errs => { diff --git a/core/modules/catalog/store/stock/actions.ts b/core/modules/catalog/store/stock/actions.ts index b152a5aaf9..139a875e44 100644 --- a/core/modules/catalog/store/stock/actions.ts +++ b/core/modules/catalog/store/stock/actions.ts @@ -7,6 +7,8 @@ import RootState from '@vue-storefront/core/types/RootState' import StockState from '../../types/StockState' import rootStore from '@vue-storefront/store' import { TaskQueue } from '@vue-storefront/core/lib/sync' +import { Logger } from '@vue-storefront/core/lib/logger' + const actions: ActionTree = { /** * Reset current configuration and selected variatnts @@ -51,7 +53,7 @@ const actions: ActionTree = { } resolve(task) // if online we can return ok because it will be verified anyway }).catch((err) => { - console.error(err) + Logger.error(err, 'stock') resolve(null) }) } else { @@ -69,7 +71,7 @@ const actions: ActionTree = { if (cartItem && event.result.code !== 'ENOTFOUND') { if (!event.result.is_in_stock) { if (!rootStore.state.config.stock.allowOutOfStockInCart) { - console.log('Removing product from cart', event.product_sku) + Logger.log('Removing product from cart' + event.product_sku, 'stock') rootStore.commit('cart/' + types.CART_DEL_ITEM, { product: { sku: event.product_sku } }, {root: true}) } else { rootStore.dispatch('cart/updateItem', { product: { errors: { stock: i18n.t('Out of the stock!') }, sku: event.product_sku, is_in_stock: false } }) @@ -80,8 +82,8 @@ const actions: ActionTree = { Vue.prototype.$bus.$emit('cart-after-itemchanged', { item: cartItem }) } }) - console.debug('Stock quantity checked for ' + event.result.product_id + ', response time: ' + (event.transmited_at - event.created_at) + ' ms') - console.debug(event) + Logger.debug('Stock quantity checked for ' + event.result.product_id + ', response time: ' + (event.transmited_at - event.created_at) + ' ms', 'stock') + Logger.debug(event, 'stock') }, 500) } } diff --git a/core/modules/catalog/store/tax/actions.ts b/core/modules/catalog/store/tax/actions.ts index 54faff454f..576aaf3889 100644 --- a/core/modules/catalog/store/tax/actions.ts +++ b/core/modules/catalog/store/tax/actions.ts @@ -4,7 +4,7 @@ import { quickSearchByQuery } from '@vue-storefront/core/lib/search' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import RootState from '@vue-storefront/core/types/RootState' import TaxState from '../../types/TaxState' - +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { /** @@ -12,7 +12,7 @@ const actions: ActionTree = { */ list (context, { entityType = 'taxrule' }) { if (context.state.rules.length > 0) { - console.info('Tax rules served from local memory') + Logger.info('Tax rules served from local memory', 'tax') return new Promise((resolve, reject) => { resolve({ items: context.state.rules }) }) diff --git a/core/modules/catalog/store/tax/mutations.ts b/core/modules/catalog/store/tax/mutations.ts index e8c18795d2..0c310cd9c7 100644 --- a/core/modules/catalog/store/tax/mutations.ts +++ b/core/modules/catalog/store/tax/mutations.ts @@ -3,6 +3,7 @@ import { MutationTree } from 'vuex' import * as types from './mutation-types' import { entityKeyName } from '@vue-storefront/store/lib/entities' import TaxState from '../../types/TaxState' +import { Logger } from '@vue-storefront/core/lib/logger' const mutations: MutationTree = { [types.TAX_UPDATE_RULES] (state, taxClasses) { @@ -10,7 +11,7 @@ const mutations: MutationTree = { for (let tc of taxClasses.items) { // we store each product separately in cache to have offline acces for products/single method const cacheKey = entityKeyName('tc', tc.id) cache.setItem(cacheKey, tc).catch((err) => { - console.error('Cannot store cache for ' + cacheKey + ', ' + err) + Logger.error('Cannot store cache for ' + cacheKey + ', ' + err) }) } state.rules = taxClasses.items // extract fields from ES _source diff --git a/core/modules/checkout/components/OrderReview.ts b/core/modules/checkout/components/OrderReview.ts index 4ff8cd40e0..3432b7d342 100644 --- a/core/modules/checkout/components/OrderReview.ts +++ b/core/modules/checkout/components/OrderReview.ts @@ -1,5 +1,6 @@ import { mapGetters } from 'vuex' import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' export const OrderReview ={ name: 'OrderReview', @@ -56,7 +57,7 @@ export const OrderReview ={ } }).catch(err => { this.$bus.$emit('notification-progress-stop') - console.error(err) + Logger.error(err, 'checkout') }) } } diff --git a/core/modules/checkout/store/checkout/actions.ts b/core/modules/checkout/store/checkout/actions.ts index ac2ce098a1..5d2679d1dd 100644 --- a/core/modules/checkout/store/checkout/actions.ts +++ b/core/modules/checkout/store/checkout/actions.ts @@ -5,6 +5,7 @@ import i18n from '@vue-storefront/i18n' import rootStore from '@vue-storefront/store' import RootState from '@vue-storefront/core/types/RootState' import CheckoutState from '../../types/CheckoutState' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { /** @@ -25,14 +26,14 @@ const actions: ActionTree = { }) } catch (e) { if (e.name === 'ValidationError') { - console.error('Internal validation error; Order entity is not compliant with the schema', e.messages) + Logger.error('Internal validation error; Order entity is not compliant with the schema' + e.messages, 'checkout') rootStore.dispatch('notification/spawnNotification', { type: 'error', message: i18n.t('Internal validation error. Please check if all required fields are filled in. Please contact us on contributors@vuestorefront.io'), action1: { label: i18n.t('OK') } }) } else { - console.error(e) + Logger.error(e, 'checkout') } } }, diff --git a/core/modules/cms/store/block/actions.ts b/core/modules/cms/store/block/actions.ts index c69bfc9774..1505275241 100644 --- a/core/modules/cms/store/block/actions.ts +++ b/core/modules/cms/store/block/actions.ts @@ -4,6 +4,7 @@ import * as types from './mutation-types' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import RootState from '@vue-storefront/core/types/RootState'; import CmsBlockState from "../../types/CmsBlockState" +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { @@ -31,7 +32,7 @@ const actions: ActionTree = { return resp.items }) .catch(err => { - console.error(err) + Logger.error(err, 'cms') }) } else { return new Promise((resolve, reject) => { @@ -64,7 +65,7 @@ const actions: ActionTree = { return resp.items[0] }) .catch(err => { - console.error(err) + Logger.error(err, 'cms') }) } else { return new Promise((resolve, reject) => { diff --git a/core/modules/cms/store/hierarchy/actions.ts b/core/modules/cms/store/hierarchy/actions.ts index 1fc9fcfac6..30b5a15edf 100644 --- a/core/modules/cms/store/hierarchy/actions.ts +++ b/core/modules/cms/store/hierarchy/actions.ts @@ -3,6 +3,7 @@ import { quickSearchByQuery } from '@vue-storefront/core/lib/search' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import RootState from '@vue-storefront/core/types/RootState'; import CmsHierarchyState from "../../types/CmsHierarchyState" +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { /** @@ -23,7 +24,7 @@ const actions: ActionTree = { } return quickSearchByQuery({ query, entityType, excludeFields, includeFields }).catch(err => { - console.error(err) + Logger.error(err, 'cms') }) } } diff --git a/core/modules/cms/store/page/actions.ts b/core/modules/cms/store/page/actions.ts index 716ac47a13..81aeea6c63 100644 --- a/core/modules/cms/store/page/actions.ts +++ b/core/modules/cms/store/page/actions.ts @@ -6,6 +6,7 @@ import RootState from '@vue-storefront/core/types/RootState'; import CmsPageState from "../../types/CmsPageState" import { cacheStorage } from '../../' import { cmsPagesStorageKey } from './' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { @@ -33,7 +34,7 @@ const actions: ActionTree = { return resp.items }) .catch(err => { - console.error(err) + Logger.error(err, 'cms') }) } else { return new Promise((resolve, reject) => { diff --git a/core/modules/cms/store/plugin.ts b/core/modules/cms/store/plugin.ts index c9d4818b15..0386444936 100644 --- a/core/modules/cms/store/plugin.ts +++ b/core/modules/cms/store/plugin.ts @@ -3,19 +3,20 @@ import * as blockTypes from './block/mutation-types' import { cmsPagesStorageKey } from './page' import { cmsBlockStorageKey } from './block' import { cacheStorage } from '../' +import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { const type = mutation.type if (type.startsWith(pageTypes.SN_CMS_PAGE)) { // check if this mutation is pages related cacheStorage.setItem(cmsPagesStorageKey, state.cmsPage.items).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'cms') // it doesn't work on SSR }) } if (type.startsWith(blockTypes.SN_CMS_BLOCK)) { // check if this mutation is block related cacheStorage.setItem(cmsBlockStorageKey, state.cmsBlock.items).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'cms') // it doesn't work on SSR }) } -} \ No newline at end of file +} diff --git a/core/modules/compare/store/plugin.ts b/core/modules/compare/store/plugin.ts index b9cee23620..fd5148da3c 100644 --- a/core/modules/compare/store/plugin.ts +++ b/core/modules/compare/store/plugin.ts @@ -1,12 +1,13 @@ import * as types from './mutation-types' import { cacheStorage } from '../' +import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { const type = mutation.type if (type.startsWith(types.SN_COMPARE)) { // check if this mutation is comapre related cacheStorage.setItem('current-compare', state.compare.items).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'compare') // it doesn't work on SSR }) } -} \ No newline at end of file +} diff --git a/core/modules/offline-order/components/CancelOrders.ts b/core/modules/offline-order/components/CancelOrders.ts index 02ff6c14e7..e048ca21bd 100644 --- a/core/modules/offline-order/components/CancelOrders.ts +++ b/core/modules/offline-order/components/CancelOrders.ts @@ -2,6 +2,7 @@ import * as localForage from 'localforage' import store from '@vue-storefront/store' import UniversalStorage from '@vue-storefront/store/lib/storage' +import { Logger } from '@vue-storefront/core/lib/logger' export const CancelOrders = { methods: { @@ -17,8 +18,8 @@ export const CancelOrders = { ordersCollection.removeItem(id) } }).catch(err => { - console.error(err) - console.log('Not transmitted orders have been deleted') + Logger.error(err, 'offline-order') + Logger.log('Not transmitted orders have been deleted', 'offline-order') }) } } diff --git a/core/modules/offline-order/helpers/onNetworkStatusChange.ts b/core/modules/offline-order/helpers/onNetworkStatusChange.ts index 6e15d68bf9..10a66325e9 100644 --- a/core/modules/offline-order/helpers/onNetworkStatusChange.ts +++ b/core/modules/offline-order/helpers/onNetworkStatusChange.ts @@ -7,7 +7,7 @@ import UniversalStorage from '@vue-storefront/store/lib/storage' import { currentStoreView } from '@vue-storefront/core/lib/multistore' export function onNetworkStatusChange (store) { - console.log('Are we online: ' + navigator.onLine) + Logger.log('Are we online: ' + navigator.onLine, 'offline-order') if (typeof navigator !== 'undefined' && navigator.onLine) { EventBus.$emit('sync/PROCESS_QUEUE', { config: store.state.config }) // process checkout queue @@ -30,7 +30,7 @@ export function onNetworkStatusChange (store) { ordersToConfirm.push(order) } }).catch(err => { - console.error(err) + Logger.error(err, 'offline-order') }) if (ordersToConfirm.length > 0) { diff --git a/core/modules/order/store/mutations.ts b/core/modules/order/store/mutations.ts index 2a554d0b6b..65cdb0018c 100644 --- a/core/modules/order/store/mutations.ts +++ b/core/modules/order/store/mutations.ts @@ -4,6 +4,7 @@ import * as types from './mutation-types' import * as entities from '@vue-storefront/store/lib/entities' import OrderState from '../types/OrderState' import rootStore from '@vue-storefront/store' +import { Logger } from '@vue-storefront/core/lib/logger' const mutations: MutationTree = { /** @@ -18,13 +19,13 @@ const mutations: MutationTree = { order.updated_at = new Date() ordersCollection.setItem(orderId.toString(), order, (err, resp) => { - if (err) console.error(err) + if (err) Logger.error(err, 'order') if (!order.transmited) { Vue.prototype.$bus.$emit('order/PROCESS_QUEUE', { config: rootStore.state.config }) // process checkout queue } - console.info('Order placed, orderId = ' + orderId) + Logger.info('Order placed, orderId = ' + orderId, 'order') }).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'order') // it doesn't work on SSR }) // populate cache }, [types.ORDER_LAST_ORDER_WITH_CONFIRMATION] (state, payload) { diff --git a/core/modules/recently-viewed/store/plugin.ts b/core/modules/recently-viewed/store/plugin.ts index 6ac8d5e873..aa7cd8a955 100644 --- a/core/modules/recently-viewed/store/plugin.ts +++ b/core/modules/recently-viewed/store/plugin.ts @@ -1,5 +1,6 @@ import * as types from './mutation-types' import { cacheStorage } from '../' +import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { const type = mutation.type diff --git a/core/modules/review/store/actions.ts b/core/modules/review/store/actions.ts index b6fa11deac..9a9ade2131 100644 --- a/core/modules/review/store/actions.ts +++ b/core/modules/review/store/actions.ts @@ -10,6 +10,7 @@ import i18n from '@vue-storefront/i18n' import rootStore from '@vue-storefront/store' import Review from '@vue-storefront/core/modules/review/types/Review' import { ReviewRequest } from '@vue-storefront/core/modules/review/types/ReviewRequest' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { /** @@ -39,7 +40,7 @@ const actions: ActionTree = { quickSearchByQuery({ query, start, size, entityType, sort, excludeFields, includeFields }).then((resp) => { context.commit(types.REVIEW_UPD_REVIEWS, resp) }).catch(err => { - console.error(err) + Logger.error(err, 'review') }) }, diff --git a/core/modules/user/components/Login.ts b/core/modules/user/components/Login.ts index 3e885a7814..a97b70f217 100644 --- a/core/modules/user/components/Login.ts +++ b/core/modules/user/components/Login.ts @@ -1,4 +1,5 @@ import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' export const Login = { name: 'Login', @@ -26,7 +27,7 @@ export const Login = { this.close() } }).catch(err => { - console.error(err) + Logger.error(err, 'user') // TODO Move to theme this.$bus.$emit('notification-progress-stop') }) diff --git a/core/modules/user/components/Register.ts b/core/modules/user/components/Register.ts index 6fcc93e6ec..4aed6b36a0 100644 --- a/core/modules/user/components/Register.ts +++ b/core/modules/user/components/Register.ts @@ -1,4 +1,5 @@ import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' export const Register = { name: 'Register', @@ -25,7 +26,7 @@ export const Register = { // TODO Move to theme this.$bus.$emit('notification-progress-start', i18n.t('Registering the account ...')) this.$store.dispatch('user/register', { email: this.email, password: this.password, firstname: this.firstName, lastname: this.lastName }).then((result) => { - console.debug(result) + Logger.debug(result, 'user') // TODO Move to theme this.$bus.$emit('notification-progress-stop') if (result.code !== 200) { @@ -43,7 +44,7 @@ export const Register = { }).catch(err => { // TODO Move to theme this.$bus.$emit('notification-progress-stop') - console.error(err) + Logger.error(err, 'user') }) } } diff --git a/core/modules/user/store/actions.ts b/core/modules/user/store/actions.ts index 7c75d91699..df86b3b615 100644 --- a/core/modules/user/store/actions.ts +++ b/core/modules/user/store/actions.ts @@ -17,7 +17,7 @@ const actions: ActionTree = { const cache = Vue.prototype.$db.usersCollection cache.getItem('current-token', (err, res) => { if (err) { - console.error(err) + Logger.error(err, 'user') return } @@ -28,7 +28,7 @@ const actions: ActionTree = { if (rootStore.state.config.usePriceTiers) { Vue.prototype.$db.usersCollection.getItem('current-user', (err, userData) => { if (err) { - console.error(err) + Logger.error(err, 'user') return } @@ -47,7 +47,7 @@ const actions: ActionTree = { * Send password reset link for specific e-mail */ resetPassword (context, { email }) { - TaskQueue.execute({ url: rootStore.state.config.users.resetPassword_endpoint, + return TaskQueue.execute({ url: rootStore.state.config.users.resetPassword_endpoint, payload: { method: 'POST', mode: 'cors', @@ -57,8 +57,6 @@ const actions: ActionTree = { }, body: JSON.stringify({ email: email }) } - }).then((response) => { - return response }) }, /** @@ -120,7 +118,7 @@ const actions: ActionTree = { const usersCollection = Vue.prototype.$db.usersCollection usersCollection.getItem('current-refresh-token', (err, refreshToken) => { if (err) { - console.error(err) + Logger.error(err, 'user') } let url = rootStore.state.config.users.refresh_endpoint if (rootStore.state.config.storeViews.multistore) { @@ -177,7 +175,7 @@ const actions: ActionTree = { if (useCache === true) { // after login for example we shouldn't use cache to be sure we're loading currently logged in user cache.getItem('current-user', (err, res) => { if (err) { - console.error(err) + Logger.error(err, 'user') return } @@ -189,7 +187,7 @@ const actions: ActionTree = { resolve(res) resolvedFromCache = true - console.log('Current user served from cache') + Logger.log('Current user served from cache', 'user') } }) } @@ -313,7 +311,7 @@ const actions: ActionTree = { // TODO: Make it as an extension from users module return new Promise((resolve, reject) => { if (!context.state.token) { - console.debug('No User token, user unathorized') + Logger.debug('No User token, user unathorized', 'user') return resolve(null) } const cache = Vue.prototype.$db.ordersHistoryCollection @@ -322,7 +320,7 @@ const actions: ActionTree = { if (useCache === true) { // after login for example we shouldn't use cache to be sure we're loading currently logged in user cache.getItem('orders-history', (err, res) => { if (err) { - console.error(err) + Logger.error(err, 'user') return } @@ -332,7 +330,7 @@ const actions: ActionTree = { resolve(res) resolvedFromCache = true - console.log('Current user order history served from cache') + Logger.log('Current user order history served from cache', 'user') } }) } diff --git a/core/modules/user/store/mutations.ts b/core/modules/user/store/mutations.ts index 684268e53a..5da39ddf06 100644 --- a/core/modules/user/store/mutations.ts +++ b/core/modules/user/store/mutations.ts @@ -1,13 +1,14 @@ import { MutationTree } from 'vuex' import * as types from './mutation-types' import UserState from '../types/UserState' +import { Logger } from '@vue-storefront/core/lib/logger' const mutations: MutationTree = { [types.USER_TOKEN_CHANGED] (state, payload) { state.token = payload.newToken if (payload.meta && payload.meta.refreshToken) { state.refreshToken = payload.meta.refreshToken // store the refresh token - console.log('Refresh token is set to', state.refreshToken) + Logger.log('Refresh token is set to' + state.refreshToken, 'user') } }, [types.USER_START_SESSION] (state) { diff --git a/core/modules/wishlist/store/plugin.ts b/core/modules/wishlist/store/plugin.ts index 3a645e3654..f98fe19aef 100644 --- a/core/modules/wishlist/store/plugin.ts +++ b/core/modules/wishlist/store/plugin.ts @@ -1,12 +1,13 @@ import * as types from './mutation-types' import { cacheStorage } from '../' +import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { const type = mutation.type if (type.startsWith(types.SN_WISHLIST)) { // check if this mutation is wishlist related cacheStorage.setItem('current-wishlist', state.wishlist.items).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason, 'wishlist') // it doesn't work on SSR }) } -} \ No newline at end of file +} diff --git a/core/pages/Category.js b/core/pages/Category.js index 04d1a05719..83c5970f2a 100644 --- a/core/pages/Category.js +++ b/core/pages/Category.js @@ -67,7 +67,7 @@ export default { } }, preAsyncData ({ store, route }) { - console.log('preAsyncData query setup') + Logger.log('preAsyncData query setup') store.dispatch('category/setSearchOptions', { populateAggregations: true, store: store, @@ -91,7 +91,7 @@ export default { filterValues: defaultFilters, // TODO: assign specific filters/ attribute codes dynamicaly to specific categories includeFields: store.state.config.entities.optimize && Vue.prototype.$isServer ? store.state.config.entities.attribute.includeFields : null }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }).then((attrs) => { store.dispatch('category/single', { key: store.state.config.products.useMagentoUrlKeys ? 'url_key' : 'slug', value: route.params.slug }).then((parentCategory) => { @@ -107,29 +107,29 @@ export default { EventBus.$emitFilter('category-after-load', { store: store, route: route }).then((results) => { return resolve() }).catch((err) => { - console.error(err) + Logger.error(err) return resolve() }) }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }) } else { const err = new Error('Category query returned empty result') - console.error(err) + Logger.error(err) reject(err) } }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }) }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }) }) }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }) }) diff --git a/core/pages/Checkout.js b/core/pages/Checkout.js index 5ad6aaccde..527ad98e27 100644 --- a/core/pages/Checkout.js +++ b/core/pages/Checkout.js @@ -7,6 +7,7 @@ import { mapGetters } from 'vuex' import Composite from '@vue-storefront/core/mixins/composite' import { currentStoreView } from '@vue-storefront/core/lib/multistore' import { isServer } from '@vue-storefront/core/helpers' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'Checkout', @@ -71,7 +72,7 @@ export default { checkPromises.push(new Promise((resolve, reject) => { Vue.prototype.$db.syncTaskCollection.getItem(product.onlineStockCheckid, (err, item) => { if (err || !item) { - if (err) console.error(err) + if (err) Logger.error(err) resolve(null) } else { product.stock = item.result @@ -144,7 +145,7 @@ export default { this.confirmation = payload.confirmation this.orderPlaced = true this.$store.dispatch('checkout/setThankYouPage', true) - console.debug(payload.order) + Logger.debug(payload.order) }, onBeforeEdit (section) { this.activateSection(section) diff --git a/core/pages/CmsPage.js b/core/pages/CmsPage.js index 1fd3bb50a5..82e09745b0 100644 --- a/core/pages/CmsPage.js +++ b/core/pages/CmsPage.js @@ -1,5 +1,6 @@ import { htmlDecode } from '@vue-storefront/core/filters/html-decode' import Composite from '@vue-storefront/core/mixins/composite' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'CmsPage', @@ -21,7 +22,7 @@ export default { }).then(page => { resolve(page) }).catch(err => { - console.error(err) + Logger.error(err) reject(err) }) }) diff --git a/core/pages/Error.js b/core/pages/Error.js index 7e1ca90d9a..80bddc717a 100644 --- a/core/pages/Error.js +++ b/core/pages/Error.js @@ -1,10 +1,11 @@ import i18n from '@vue-storefront/i18n' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'Error', asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { - console.log('Calling asyncData for Error page ' + new Date()) + Logger.log('Calling asyncData for Error page ' + new Date()) if (context) { context.output.cacheTags.add(`error`) } diff --git a/core/pages/Home.js b/core/pages/Home.js index 98db8af116..b241c71adb 100644 --- a/core/pages/Home.js +++ b/core/pages/Home.js @@ -17,11 +17,11 @@ export default { }, async asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data if (context) context.output.cacheTags.add(`home`) - Logger.info('Calling asyncData in Home Page (core)')() + Logger.info('Calling asyncData in Home Page (core)') try { await EventBus.$emitFilter('home-after-load', { store: store, route: route }) } catch (e) { - console.error(e) + Logger.error(e) throw e } }, diff --git a/core/pages/MyAccount.js b/core/pages/MyAccount.js index 580037caab..e1ad89a415 100644 --- a/core/pages/MyAccount.js +++ b/core/pages/MyAccount.js @@ -1,6 +1,7 @@ import i18n from '@vue-storefront/i18n' import Composite from '@vue-storefront/core/mixins/composite' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'MyAccount', @@ -35,7 +36,7 @@ export default { this.$store.dispatch('user/update', { customer: updatedData }) } catch (err) { this.$bus.$emit('myAccount-before-remainInEditMode', this.$props.activeBlock) - console.error(err) + Logger.error(err) } } } diff --git a/core/pages/PageNotFound.js b/core/pages/PageNotFound.js index 334ac14275..fbf992050f 100644 --- a/core/pages/PageNotFound.js +++ b/core/pages/PageNotFound.js @@ -4,13 +4,14 @@ import i18n from '@vue-storefront/i18n' import EventBus from '@vue-storefront/core/compatibility/plugins/event-bus' import Composite from '@vue-storefront/core/mixins/composite' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'PageNotFound', mixins: [Composite], asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { - console.log('Entering asyncData for PageNotFound ' + new Date()) + Logger.log('Entering asyncData for PageNotFound ' + new Date()) if (context) context.output.cacheTags.add(`page-not-found`) let ourBestsellersQuery = prepareQuery({ queryConfig: 'bestSellers' }) store.dispatch('category/list', {}).then(categories => { @@ -24,7 +25,7 @@ export default { EventBus.$emitFilter('pagenotfound-after-load', { store: store, route: route }).then(results => { return resolve() }).catch(err => { - console.error(err) + Logger.error(err) return resolve() }) } diff --git a/core/pages/Product.js b/core/pages/Product.js index 3f3a0eefe7..fd21d1b2d9 100644 --- a/core/pages/Product.js +++ b/core/pages/Product.js @@ -9,6 +9,7 @@ import { AddToCompare } from '@vue-storefront/core/modules/compare/components/Ad import { isOptionAvailableAsync } from '@vue-storefront/core/modules/catalog/helpers/index' import omit from 'lodash-es/omit' import Composite from '@vue-storefront/core/mixins/composite' +import { Logger } from '@vue-storefront/core/lib/logger' export default { name: 'Product', @@ -99,12 +100,12 @@ export default { this.$store.dispatch('recently-viewed/addItem', this.product) }).catch((err) => { this.loading = false - console.error(err) + Logger.error(err) this.notifyOutStock() this.$router.back() }) } else { - console.error('Error with loading = true in Product.vue; Reload page') + Logger.error('Error with loading = true in Product.vue; Reload page') } }, addToWishlist (product) { @@ -160,7 +161,7 @@ export default { }, onStateCheck () { if (this.parentProduct && this.parentProduct.id !== this.product.id) { - console.log('Redirecting to parent, configurable product', this.parentProduct.sku) + Logger.log('Redirecting to parent, configurable product', this.parentProduct.sku) this.$router.replace({ name: 'product', params: { parentSku: this.parentProduct.sku, childSku: this.product.sku, slug: this.parentProduct.slug } }) } }, @@ -168,7 +169,7 @@ export default { if (product.sku === this.product.sku) { // join selected variant object to the store this.$store.dispatch('product/setCurrent', omit(product, ['name'])) - .catch(err => console.error({ + .catch(err => Logger.error({ info: 'Dispatch product/setCurrent in Product.vue', err })) @@ -200,7 +201,7 @@ export default { } this.notifyWrongAttributes() } - }).catch(err => console.error({ + }).catch(err => Logger.error({ info: 'Dispatch product/configure in Product.vue', err })) diff --git a/core/scripts/cache.js b/core/scripts/cache.js index 2133c429bd..c7794bca40 100644 --- a/core/scripts/cache.js +++ b/core/scripts/cache.js @@ -1,3 +1,5 @@ +import { Logger } from '@vue-storefront/core/lib/logger' + const program = require('commander') const config = require('config') const TagCache = require('redis-tag-cache').default @@ -8,9 +10,9 @@ if (config.server.useOutputCache) { redis: config.redis, defaultTimeout: config.server.outputCacheDefaultTtl // Expire records after a day (even if they weren't invalidated) }) - console.log('Redis cache set', config.redis) + Logger.log('Redis cache set', config.redis) } else { - console.error('Output cache is disabled in the config') + Logger.error('Output cache is disabled in the config') } program @@ -18,10 +20,10 @@ program .option('-t|--tag ', 'tag name, available tags: ' + config.server.availableCacheTags.join(', '), '*') .action((cmd) => { // TODO: add parallel processing if (!cmd.tag) { - console.error('error: tag must be specified') + Logger.error('error: tag must be specified') process.exit(1) } else { - console.log(`Clear cache request for [${cmd.tag}]`) + Logger.log(`Clear cache request for [${cmd.tag}]`) let tags = [] if (cmd.tag === '*') { tags = config.server.availableCacheTags @@ -34,17 +36,17 @@ program return tag.indexOf(t) === 0 })) { subPromises.push(cache.invalidate(tag).then(() => { - console.log(`Tags invalidated successfully for [${tag}]`) + Logger.log(`Tags invalidated successfully for [${tag}]`) })) } else { - console.error(`Invalid tag name ${tag}`) + Logger.error(`Invalid tag name ${tag}`) } }) Promise.all(subPromises).then(r => { - console.log(`All tags invalidated successfully [${cmd.tag}]`) + Logger.log(`All tags invalidated successfully [${cmd.tag}]`) process.exit(0) }).catch(error => { - console.error(error) + Logger.error(error) }) } }) diff --git a/core/scripts/resolvers/resolveGraphQL.js b/core/scripts/resolvers/resolveGraphQL.js index 2543a6d989..00443d9d01 100644 --- a/core/scripts/resolvers/resolveGraphQL.js +++ b/core/scripts/resolvers/resolveGraphQL.js @@ -1,5 +1,6 @@ import { server, graphql } from 'config' import Vue from 'vue' +import { Logger } from '@vue-storefront/core/lib/logger' export const getApolloProvider = async () => { if (server.api === 'graphql') { @@ -37,11 +38,11 @@ export const getApolloProvider = async () => { }, watchLoading (state, mod) { loading += mod - console.log('Global loading', loading, mod) + Logger.log('Global loading', loading, mod) }, errorHandler (error) { - console.log('Global error handler') - console.error(error) + Logger.log('Global error handler') + Logger.error(error) } }) diff --git a/core/server-entry.ts b/core/server-entry.ts index cb74990238..b7f82d449d 100755 --- a/core/server-entry.ts +++ b/core/server-entry.ts @@ -86,7 +86,7 @@ export default async context => { }) if (Component.asyncData) { Component.asyncData({ store, route: router.currentRoute, context: context }).then((result) => { // always execute the asyncData() from the top most component first - console.debug('Top-most asyncData executed') + Logger.debug('Top-most asyncData executed') _ssrHydrateSubcomponents(components, store, router, resolve, reject, app, context) }).catch((err) => { _commonErrorHandler(err, reject) diff --git a/core/service-worker/registration.js b/core/service-worker/registration.js index dbaddf34af..fa7b16dcb0 100644 --- a/core/service-worker/registration.js +++ b/core/service-worker/registration.js @@ -1,26 +1,27 @@ import { register } from 'register-service-worker' import { server } from 'config' +import { Logger } from '@vue-storefront/core/lib/logger' if (process.env.NODE_ENV === 'production' || server.devServiceWorker) { register(`/service-worker.js`, { ready () { - console.log( + Logger.log( 'App is being served from cache by a service worker.' ) }, cached () { - console.log('Content has been cached for offline use.') + Logger.log('Content has been cached for offline use.') }, updated (registration) { - console.log('New content is available, please refresh.') + Logger.log('New content is available, please refresh.') }, offline () { - console.log( + Logger.log( 'No internet connection found. App is running in offline mode.' ) }, error (error) { - console.error('Error during service worker registration:', error) + Logger.error('Error during service worker registration:', error) } }) } diff --git a/core/store/lib/storage.ts b/core/store/lib/storage.ts index 1e1db45c80..3ca56131aa 100644 --- a/core/store/lib/storage.ts +++ b/core/store/lib/storage.ts @@ -124,7 +124,7 @@ class LocalForageCacheDriver { } else { this._localForageCollection = localForage.createInstance(existingConfig) } - console.log('DB recreated with', existingConfig, destVersionNumber) + Logger.log('DB recreated with', existingConfig, destVersionNumber) } } } @@ -136,7 +136,7 @@ class LocalForageCacheDriver { const isCallbackCallable = (typeof callback !== 'undefined' && callback) let isResolved = false if (this._useLocalCacheByDefault && this._localCache[key]) { - // console.debug('Local cache fallback for GET', key) + // Logger.debug('Local cache fallback for GET', key) return new Promise((resolve, reject) => { const value = typeof this._localCache[key] !== 'undefined' ? this._localCache[key] : null if (isCallbackCallable) callback(null, value) @@ -147,7 +147,7 @@ class LocalForageCacheDriver { if (!Vue.prototype.$isServer) { if (this.cacheErrorsCount[this._collectionName] >= DISABLE_PERSISTANCE_AFTER && this._useLocalCacheByDefault) { if (!this._persistenceErrorNotified) { - console.error('Persistent cache disabled becasue of previous errors [get]', key) + Logger.error('Persistent cache disabled becasue of previous errors [get]', key) this._persistenceErrorNotified = true } return new Promise((resolve, reject) => { @@ -156,11 +156,11 @@ class LocalForageCacheDriver { }) } else { const startTime = new Date().getTime() - // console.debug('No local cache fallback for GET', key) + // Logger.debug('No local cache fallback for GET', key) const promise = this._localForageCollection.ready().then(() => this._localForageCollection.getItem(key).then(result => { const endTime = new Date().getTime() if ((endTime - startTime) >= CACHE_TIMEOUT) { - console.error('Cache promise resolved after [ms]', key, (endTime - startTime)) + Logger.error('Cache promise resolved after [ms]', key, (endTime - startTime)) } if (!this._localCache[key] && result) { this._localCache[key] = result // populate the local cache for the next call @@ -171,7 +171,7 @@ class LocalForageCacheDriver { } isResolved = true } else { - console.debug('Skipping return value as it was previously resolved') + Logger.debug('Skipping return value as it was previously resolved') } return result }).catch(err => { @@ -179,7 +179,7 @@ class LocalForageCacheDriver { if (!isResolved) { if (isCallbackCallable) callback(null, typeof this._localCache[key] !== 'undefined' ? this._localCache[key] : null) } - console.error(err) + Logger.error(err) isResolved = true })) @@ -211,7 +211,7 @@ class LocalForageCacheDriver { const isCallbackCallable = (typeof callback !== 'undefined' && callback) let globalIterationNumber = 1 if (this._useLocalCacheByDefault) { - // console.debug('Local cache iteration') + // Logger.debug('Local cache iteration') for (const localKey in this._localCache) { if (isIteratorCallable) { iterator(this._localCache[localKey], localKey, globalIterationNumber) @@ -228,7 +228,7 @@ class LocalForageCacheDriver { iterator(value, key, globalIterationNumber) globalIterationNumber++ } else { - // console.debug('Skipping iteration key because local cache executed', key) + // Logger.debug('Skipping iteration key because local cache executed', key) } } else { iterator(value, key, iterationNumber) @@ -239,7 +239,7 @@ class LocalForageCacheDriver { isResolved = true })).catch(err => { this._lastError = err - console.error(err) + Logger.error(err) if (!isResolved) { isResolved = true if (isCallbackCallable) callback(err, null) @@ -297,7 +297,7 @@ class LocalForageCacheDriver { if (!Vue.prototype.$isServer) { if (this.cacheErrorsCount[this._collectionName] >= DISABLE_PERSISTANCE_AFTER_SAVE && this._useLocalCacheByDefault) { if (!this._persistenceErrorNotified) { - console.error('Persistent cache disabled becasue of previous errors [set]', key) + Logger.error('Persistent cache disabled becasue of previous errors [set]', key) this._persistenceErrorNotified = true } return new Promise((resolve, reject) => { diff --git a/docker-compose.yml b/docker-compose.yml index 680a010a3b..9e6690307d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,14 +1,14 @@ version: '2.0' services: app: - # image: divante/vue-storefront:latest + container_name: vue-storefront build: context: . dockerfile: docker/vue-storefront/Dockerfile env_file: docker/vue-storefront/default.env environment: VS_ENV: dev - network_mode: host + network_mode: bridge volumes: - '.babelrc:/var/www/.babelrc' - './config:/var/www/config' @@ -26,4 +26,4 @@ services: tmpfs: - /var/www/dist ports: - - '3000:3000' + - '80' diff --git a/docs/guide/basics/ssr-cache.md b/docs/guide/basics/ssr-cache.md index e7a32ca95a..84c98cfb1c 100644 --- a/docs/guide/basics/ssr-cache.md +++ b/docs/guide/basics/ssr-cache.md @@ -91,11 +91,11 @@ After doing so, please add the `asyncData` method to your page code assigning th asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { if (context) context.output.cacheTags.add(`home`) - console.log('Entering asyncData for Home root ' + new Date()) + Logger.log('Entering asyncData for Home root ' + new Date()) EventBus.$emitFilter('home-after-load', { store: store, route: route }).then((results) => { return resolve() }).catch((err) => { - console.error(err) + Logger.error(err) reject(err) }) }) diff --git a/docs/guide/core-themes/core-components.md b/docs/guide/core-themes/core-components.md index 160f67aba0..586ee9cb7f 100644 --- a/docs/guide/core-themes/core-components.md +++ b/docs/guide/core-themes/core-components.md @@ -64,7 +64,7 @@ Since core components are just plain JavaScript objects you can easly modify the ```js import YourCorePage from '@vue-storefront/core/pages/YourCorePage' -YourCorePage.methods.foo = function () { console.log('Overrided method foo') +YourCorePage.methods.foo = function () { Logger.log('Overrided method foo') export default { ... diff --git a/docs/guide/modules/introduction.md b/docs/guide/modules/introduction.md index 4c2f8637df..0609dfce1d 100644 --- a/docs/guide/modules/introduction.md +++ b/docs/guide/modules/introduction.md @@ -271,4 +271,4 @@ export const registerModules: VueStorefrontModule[] = [Cart] ## Contributions -Please introduce every new feature as a standalone, encapsulated module. We also need your help in rewriting Vue Storefront to modular approach - [here](https://github.com/DivanteLtd/vue-storefront/issues?q=is%3Aissue+is%3Aopen+label%3A%22API+Module%22) you can find tasks related to this architectural change and [here](https://github.com/DivanteLtd/vue-storefront/blob/master/doc/api-modules/refactoring-to-modules.md) is the tutorial how to approach applying this changes. \ No newline at end of file +Please introduce every new feature as a standalone, encapsulated module. We also need your help in rewriting Vue Storefront to modular approach - [here](https://github.com/DivanteLtd/vue-storefront/issues?q=is%3Aissue+is%3Aopen+label%3A%22API+Module%22) you can find tasks related to this architectural change and [here](https://github.com/DivanteLtd/vue-storefront/blob/master/doc/api-modules/refactoring-to-modules.md) is the tutorial how to approach applying this changes. diff --git a/src/modules/claims/store/actions.ts b/src/modules/claims/store/actions.ts index 90d38baeb4..54180bcfb2 100644 --- a/src/modules/claims/store/actions.ts +++ b/src/modules/claims/store/actions.ts @@ -2,6 +2,7 @@ import Vue from 'vue' import { ActionTree } from 'vuex' import RootState from '@vue-storefront/core/types/RootState' import ClaimsState from '../types/ClaimsState' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { set (context, { claimCode, value, description }) { @@ -12,21 +13,21 @@ const actions: ActionTree = { value: value, description: description }).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason) // it doesn't work on SSR }) }, unset (context, { claimCode }) { const claimCollection = Vue.prototype.$db.claimsCollection claimCollection.removeItem(claimCode).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason) // it doesn't work on SSR }) }, check (context, { claimCode }) { const claimCollection = Vue.prototype.$db.claimsCollection return claimCollection.getItem(claimCode).catch((reason) => { - console.error(reason) // it doesn't work on SSR + Logger.error(reason) // it doesn't work on SSR }) } } diff --git a/src/modules/index.ts b/src/modules/index.ts index d6af578c01..28cb2c9466 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -27,7 +27,7 @@ import { Magento2CMS } from './magento-2-cms' // const extendCartVuex = { // actions: { // load () { -// console.info('New load function') +// Logger.info('New load function') // } // } // } @@ -35,7 +35,7 @@ import { Magento2CMS } from './magento-2-cms' // const cartExtend = { // key: 'cart', // afterRegistration: function(isServer, config) { -// console.info('New afterRegistration hook') +// Logger.info('New afterRegistration hook') // }, // store: { modules: [{ key: 'cart', module: extendCartVuex }] }, // } @@ -71,4 +71,4 @@ export const registerModules: VueStorefrontModule[] = [ RawOutputExample, AmpRenderer/*, Example*/ -] \ No newline at end of file +] diff --git a/src/modules/magento-2-cms/store/index.js b/src/modules/magento-2-cms/store/index.js index 001d186dd7..4032fc47a5 100644 --- a/src/modules/magento-2-cms/store/index.js +++ b/src/modules/magento-2-cms/store/index.js @@ -1,4 +1,5 @@ import fetch from 'isomorphic-fetch' +import { Logger } from '@vue-storefront/core/lib/logger' const state = { cmsPages: [], @@ -35,8 +36,8 @@ const actions = { } }) .catch((err) => { - console.log(err) - console.error('You need to install a custom Magento module from Snow.dog to make the CMS magick happen. Please go to https://github.com/SnowdogApps/magento2-cms-api and follow the instructions') + Logger.log(err) + Logger.error('You need to install a custom Magento module from Snow.dog to make the CMS magick happen. Please go to https://github.com/SnowdogApps/magento2-cms-api and follow the instructions') }) } } diff --git a/src/modules/module-template/hooks/afterRegistration.ts b/src/modules/module-template/hooks/afterRegistration.ts index 10609a1d2b..25a148074a 100644 --- a/src/modules/module-template/hooks/afterRegistration.ts +++ b/src/modules/module-template/hooks/afterRegistration.ts @@ -1,4 +1,6 @@ +import { Logger } from '@vue-storefront/core/lib/logger' + // This function will be fired both on server and client side context after registering other parts of the module export function afterRegistration(Vue, config, store, isServer){ - if (!Vue.prototype.$isServer) console.info('This will be called after extension registration and only on client side') -} \ No newline at end of file + if (!Vue.prototype.$isServer) Logger.info('This will be called after extension registration and only on client side') +} diff --git a/src/modules/module-template/hooks/beforeRegistration.ts b/src/modules/module-template/hooks/beforeRegistration.ts index 7e541480c9..84be7d9cc4 100644 --- a/src/modules/module-template/hooks/beforeRegistration.ts +++ b/src/modules/module-template/hooks/beforeRegistration.ts @@ -15,4 +15,4 @@ export function beforeRegistration(Vue, config, store, isServer) { }) } }) -} \ No newline at end of file +} diff --git a/src/modules/module-template/router/afterEach.ts b/src/modules/module-template/router/afterEach.ts index 04a7ec74b5..710e09b91e 100644 --- a/src/modules/module-template/router/afterEach.ts +++ b/src/modules/module-template/router/afterEach.ts @@ -1,7 +1,8 @@ // This function will be executed after entering each route. // See https://router.vuejs.org/guide/advanced/navigation-guards.html#global-after-hooks import { Route } from 'vue-router' +import { Logger } from '@vue-storefront/core/lib/logger' export function afterEach(to: Route, from: Route) { - console.info(`We have just entered ${to.name} from ${from.name}.`) -} \ No newline at end of file + Logger.info(`We have just entered ${to.name} from ${from.name}.`) +} diff --git a/src/modules/module-template/router/beforeEach.ts b/src/modules/module-template/router/beforeEach.ts index 9b277311ca..e2a1480535 100644 --- a/src/modules/module-template/router/beforeEach.ts +++ b/src/modules/module-template/router/beforeEach.ts @@ -2,8 +2,9 @@ // It's important to have 'next()'. It enables navigation to new route. // See https://router.vuejs.org/guide/advanced/navigation-guards.html#global-guards import { Route } from 'vue-router' +import { Logger } from '@vue-storefront/core/lib/logger' export function beforeEach(to: Route, from: Route, next) { - console.info('We are going to visit', to.name) + Logger.info('We are going to visit' + to.name) next() -} \ No newline at end of file +} diff --git a/src/modules/module-template/store/plugin.ts b/src/modules/module-template/store/plugin.ts index cd44e7a70b..598ba8ee61 100644 --- a/src/modules/module-template/store/plugin.ts +++ b/src/modules/module-template/store/plugin.ts @@ -1,9 +1,10 @@ import * as types from './mutation-types' +import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { if (types[mutation.type]) { - console.info('performed mutation from this store with type', mutation.type) + Logger.info('performed mutation from this store with type' + mutation.type) } else { - console.info('performed mutation from other store with type', mutation.type) + Logger.info('performed mutation from other store with type' + mutation.type) } -} \ No newline at end of file +} diff --git a/src/modules/promoted-offers/store/actions.ts b/src/modules/promoted-offers/store/actions.ts index 04e0f469d9..2db244926d 100644 --- a/src/modules/promoted-offers/store/actions.ts +++ b/src/modules/promoted-offers/store/actions.ts @@ -1,6 +1,7 @@ import { ActionTree } from 'vuex' import RootState from '@vue-storefront/core/types/RootState' import PromotedOffersState from '../types/PromotedOffersState' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { async updatePromotedOffers ({commit, rootState}, data) { @@ -9,7 +10,7 @@ const actions: ActionTree = { const promotedOffersModule = await import(/* webpackChunkName: "vsf-promoted-offers-[request]" */ `theme/resource/${promotedBannersResource}.json`) commit('updatePromotedOffers', promotedOffersModule) } catch (err) { - console.debug('Unable to load promotedOffers', err) + Logger.debug('Unable to load promotedOffers' + err) } }, async updateHeadImage ({commit, rootState}, data) { @@ -18,7 +19,7 @@ const actions: ActionTree = { const imageModule = await import(/* webpackChunkName: "vsf-head-img-[request]" */ `theme/resource/${mainImageResource}.json`) commit('SET_HEAD_IMAGE', imageModule.image) } catch (err) { - console.debug('Unable to load headImage', err) + Logger.debug('Unable to load headImage' + err) } } } diff --git a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts index f2b6142437..2b1984ed55 100644 --- a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts +++ b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts @@ -9,7 +9,7 @@ const TEST_ENTITY_TYPE = 'testentity' export function afterRegistration (Vue, config, store, isServer) { Vue.$on('application-after-init', async () => { - console.debug('Example of custom entity graphql extension') + Logger.debug('Example of custom entity graphql extension') // create graphQl searchAdapter let searchAdapter = await getSearchAdapter('graphql') @@ -56,7 +56,7 @@ export function afterRegistration (Vue, config, store, isServer) { // apply test search searchAdapter.search(Request).then((resp) => { // we're always trying to populate cache - when online const res = searchAdapter.entities[Request.type].resultPorcessor(resp, 0, 200) - console.log('Testentity response: ', res) + Logger.log('Testentity response: ', res) }) }) } From 8f663a9e9018fcbaba5be801adfbe5cc36d0fbc6 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 14:57:58 +0100 Subject: [PATCH 3/8] Fix merge/cherrypick issues --- core/modules/catalog/components/Search.ts | 1 + core/modules/catalog/store/category/actions.ts | 1 + core/server-entry.ts | 1 + 3 files changed, 3 insertions(+) diff --git a/core/modules/catalog/components/Search.ts b/core/modules/catalog/components/Search.ts index 5e620773f5..746fa2118e 100644 --- a/core/modules/catalog/components/Search.ts +++ b/core/modules/catalog/components/Search.ts @@ -3,6 +3,7 @@ import i18n from '@vue-storefront/i18n' import onEscapePress from '@vue-storefront/core/mixins/onEscapePress' import { prepareQuickSearchQuery } from '@vue-storefront/core/modules/catalog/queries/searchPanel' import RootState from '@vue-storefront/core/types/RootState' +import { Logger } from '@vue-storefront/core/lib/logger' export const Search = { name: 'SearchPanel', diff --git a/core/modules/catalog/store/category/actions.ts b/core/modules/catalog/store/category/actions.ts index cb74bddca8..84a8a2da69 100644 --- a/core/modules/catalog/store/category/actions.ts +++ b/core/modules/catalog/store/category/actions.ts @@ -13,6 +13,7 @@ import RootState from '@vue-storefront/core/types/RootState' import CategoryState from '../../types/CategoryState' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import { currentStoreView } from '@vue-storefront/core/lib/multistore' +import { Logger } from '@vue-storefront/core/lib/logger' const actions: ActionTree = { diff --git a/core/server-entry.ts b/core/server-entry.ts index b7f82d449d..58e755cb25 100755 --- a/core/server-entry.ts +++ b/core/server-entry.ts @@ -7,6 +7,7 @@ import omit from 'lodash-es/omit' import pick from 'lodash-es/pick' import buildTimeConfig from 'config' import { AsyncDataLoader } from './lib/asyncdataloader'; +import { Logger } from '@vue-storefront/core/lib/logger' function _commonErrorHandler (err, reject) { if (err.message.indexOf('query returned empty result') > 0) { From e353a49c0c41f7c3504d72818ab1d621d4664f43 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 15:20:57 +0100 Subject: [PATCH 4/8] Reset docker-compose.yml changes --- docker-compose.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 9e6690307d..fc154f01fd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,14 +1,14 @@ version: '2.0' services: app: - container_name: vue-storefront + # image: divante/vue-storefront:latest build: context: . dockerfile: docker/vue-storefront/Dockerfile env_file: docker/vue-storefront/default.env environment: VS_ENV: dev - network_mode: bridge + network_mode: host volumes: - '.babelrc:/var/www/.babelrc' - './config:/var/www/config' @@ -18,7 +18,6 @@ services: - './.eslintrc.js:/var/www/.eslintrc.js' - './lerna.json:/var/www/lerna.json' - './tsconfig.json:/var/www/tsconfig.json' - - './tsconfig-build.json:/var/www/tsconfig-build.json' - './shims.d.ts:/var/www/shims.d.ts' - './package.json:/var/www/package.json' - './src:/var/www/src' @@ -26,4 +25,4 @@ services: tmpfs: - /var/www/dist ports: - - '80' + - '3000:3000' From 4bf88603fa85d83a7232303259a2c75ca7757b35 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 15:29:03 +0100 Subject: [PATCH 5/8] Fix Logger inclusion --- core/lib/asyncdataloader.ts | 2 +- core/modules/offline-order/helpers/onNetworkStatusChange.ts | 1 + .../sample-custom-entity-graphql/hooks/afterRegistration.ts | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/core/lib/asyncdataloader.ts b/core/lib/asyncdataloader.ts index 663f3f4864..e45afb4161 100644 --- a/core/lib/asyncdataloader.ts +++ b/core/lib/asyncdataloader.ts @@ -1,5 +1,5 @@ import { isServer } from '@vue-storefront/core/helpers' -import { Logger } from './logger' +import { Logger } from '@vue-storefront/core/lib/logger' const DEFAULT_ACTION_CATEGORY = 'asyncData' // Data loader queues all the data fetching operations and runs them at once - to be usedf for example in the `asyncData()` functions diff --git a/core/modules/offline-order/helpers/onNetworkStatusChange.ts b/core/modules/offline-order/helpers/onNetworkStatusChange.ts index 10a66325e9..62b842dd05 100644 --- a/core/modules/offline-order/helpers/onNetworkStatusChange.ts +++ b/core/modules/offline-order/helpers/onNetworkStatusChange.ts @@ -5,6 +5,7 @@ import EventBus from '@vue-storefront/core/compatibility/plugins/event-bus/index import UniversalStorage from '@vue-storefront/store/lib/storage' import { currentStoreView } from '@vue-storefront/core/lib/multistore' +import { Logger } from '@vue-storefront/core/lib/logger' export function onNetworkStatusChange (store) { Logger.log('Are we online: ' + navigator.onLine, 'offline-order') diff --git a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts index 2b1984ed55..625f52fce7 100644 --- a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts +++ b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts @@ -3,6 +3,7 @@ import { getSearchAdapter } from '@vue-storefront/core/lib/search/adapter/search import { processESResponseType } from '@vue-storefront/core/lib/search/adapter/graphql/processor/processType' import { currentStoreView } from '@vue-storefront/core/lib/multistore' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' +import { Logger } from '@vue-storefront/core/lib/logger' const EXTENSION_KEY = 'sample-custom-entity-graphql-extension' const TEST_ENTITY_TYPE = 'testentity' From bdf938133f67ee6a9a883c87982337061c519e83 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 17:20:35 +0100 Subject: [PATCH 6/8] Fix logger method syntax --- core/client-entry.ts | 48 ++++++------ core/compatibility/lib/extensions.ts | 22 +++--- core/helpers/index.ts | 2 +- core/i18n/index.ts | 2 +- core/lib/asyncdataloader.ts | 2 +- core/lib/logger.ts | 30 ++++---- core/lib/sync/index.ts | 8 +- core/lib/sync/task.ts | 34 ++++----- core/mixins/composite.js | 8 +- core/modules/cart/store/actions.ts | 44 +++++------ .../components/ProductBundleOptions.ts | 2 +- .../components/ProductCustomOptions.ts | 2 +- core/modules/catalog/components/Search.ts | 4 +- core/modules/catalog/helpers/index.ts | 38 +++++----- core/modules/catalog/helpers/tax.ts | 8 +- .../catalog/store/attribute/mutations.ts | 2 +- .../modules/catalog/store/category/actions.ts | 24 +++--- .../catalog/store/category/mutations.ts | 2 +- core/modules/catalog/store/product/actions.ts | 76 +++++++++---------- core/modules/catalog/store/stock/actions.ts | 8 +- core/modules/catalog/store/tax/actions.ts | 2 +- core/modules/catalog/store/tax/mutations.ts | 2 +- .../checkout/components/OrderReview.ts | 2 +- .../checkout/store/checkout/actions.ts | 4 +- core/modules/cms/store/block/actions.ts | 4 +- core/modules/cms/store/hierarchy/actions.ts | 2 +- core/modules/cms/store/page/actions.ts | 4 +- .../offline-order/components/CancelOrders.ts | 4 +- .../helpers/onNetworkStatusChange.ts | 4 +- core/modules/order/store/mutations.ts | 4 +- core/modules/review/store/actions.ts | 2 +- core/modules/user/components/Login.ts | 2 +- core/modules/user/components/Register.ts | 4 +- core/modules/user/store/actions.ts | 16 ++-- core/modules/user/store/mutations.ts | 2 +- core/pages/Category.js | 16 ++-- core/pages/Checkout.js | 4 +- core/pages/CmsPage.js | 2 +- core/pages/Error.js | 2 +- core/pages/Home.js | 4 +- core/pages/MyAccount.js | 2 +- core/pages/PageNotFound.js | 4 +- core/pages/Product.js | 10 +-- core/scripts/cache.js | 16 ++-- core/scripts/resolvers/resolveGraphQL.js | 6 +- core/server-entry.ts | 4 +- core/service-worker/registration.js | 10 +-- core/store/lib/storage.ts | 26 +++---- docs/guide/basics/ssr-cache.md | 4 +- docs/guide/core-themes/core-components.md | 2 +- docs/guide/integrations/payment-gateway.md | 6 +- .../hooks/beforeRegistration.ts | 2 +- src/modules/index.ts | 8 +- src/modules/magento-2-cms/store/index.js | 4 +- .../hooks/afterRegistration.ts | 2 +- .../module-template/router/afterEach.ts | 4 +- .../module-template/router/beforeEach.ts | 4 +- src/modules/module-template/store/plugin.ts | 4 +- src/modules/promoted-offers/store/actions.ts | 4 +- .../hooks/afterRegistration.ts | 4 +- 60 files changed, 290 insertions(+), 288 deletions(-) diff --git a/core/client-entry.ts b/core/client-entry.ts index bec05f40a4..ecb591898f 100755 --- a/core/client-entry.ts +++ b/core/client-entry.ts @@ -105,7 +105,7 @@ const invokeClientEntry = async () => { }) if (c.asyncData) { c.asyncData({ store, route: to }).then(result => { // always execute the asyncData() from the top most component first - Logger.debug('Top-most asyncData executed') + Logger.debug('Top-most asyncData executed')() _ssrHydrateSubcomponents(components, next, to) }).catch(next) } else { @@ -121,7 +121,7 @@ const invokeClientEntry = async () => { * @example * const urls = ['/url1', '/url2', '/url3'] * serial(urls.map(url => () => $.ajax(url))) - * .then(Logger.log.bind(Logger)) + * .then(Logger.log.bind(Logger))() */ const serial = funcs => funcs.reduce((promise, func) => @@ -131,7 +131,7 @@ const invokeClientEntry = async () => { // TODO: move to external file EventBus.$on('order/PROCESS_QUEUE', event => { if (typeof navigator !== 'undefined' && navigator.onLine) { - Logger.log('Sending out orders queue to server ...') + Logger.log('Sending out orders queue to server ...')() const storeView = currentStoreView() const dbNamePrefix = storeView.storeCode ? storeView.storeCode + '-' : '' @@ -155,7 +155,7 @@ const invokeClientEntry = async () => { const orderData = order const orderId = id - Logger.log('Pushing out order ' + orderId) + Logger.log('Pushing out order ' + orderId)() return fetch(config.orders.endpoint, { method: 'POST', @@ -167,17 +167,17 @@ const invokeClientEntry = async () => { return response.json() } else { orderMutex[id] = false - Logger.error('Error with response - bad content-type!') + Logger.error('Error with response - bad content-type!')() } }) .then(jsonResponse => { if (jsonResponse && jsonResponse.code === 200) { - Logger.info('Response for: ' + orderId + ' = ' + jsonResponse.result) + Logger.info('Response for: ' + orderId + ' = ' + jsonResponse.result)() orderData.transmited = true orderData.transmited_at = new Date() ordersCollection.setItem(orderId.toString(), orderData) } else { - Logger.error(jsonResponse) + Logger.error(jsonResponse)() } orderMutex[id] = false }).catch(err => { @@ -185,31 +185,31 @@ const invokeClientEntry = async () => { navigator.serviceWorker.ready.then(registration => { registration.sync.register('orderSync') .then(() => { - Logger.log('Order sync registered') + Logger.log('Order sync registered')() }) .catch(error => { - Logger.log('Unable to sync', error) + Logger.log('Unable to sync', error)() }) }) } - Logger.error('Error sending order: ' + orderId, err) + Logger.error('Error sending order: ' + orderId, err)() orderMutex[id] = false }) }) } }, (err, result) => { - if (err) Logger.error(err) - Logger.log('Iteration has completed') + if (err) Logger.error(err)() + Logger.log('Iteration has completed')() // execute them serially serial(fetchQueue) .then(res => { - Logger.info('Processing orders queue has finished') + Logger.info('Processing orders queue has finished')() // store.dispatch('cart/serverPull', { forceClientState: false }) }) }).catch(err => { // This code runs if there were any errors - Logger.log(err) + Logger.log(err)() }) } }) @@ -241,11 +241,11 @@ const invokeClientEntry = async () => { usersCollection.getItem('current-token', (err, currentToken) => { // TODO: if current token is null we should postpone the queue and force re-login - only if the task requires LOGIN! if (err) { - Logger.error(err) + Logger.error(err)() } cartsCollection.getItem('current-cart-token', (err, currentCartId) => { if (err) { - Logger.error(err) + Logger.error(err)() } if (!currentCartId && store.state.cart.cartServerToken) { // this is workaround; sometimes after page is loaded indexedb returns null despite the cart token is properly set @@ -256,8 +256,8 @@ const invokeClientEntry = async () => { currentToken = store.state.user.token } const fetchQueue = [] - Logger.debug('Current User token = ' + currentToken) - Logger.debug('Current Cart token = ' + currentCartId) + Logger.debug('Current User token = ' + currentToken)() + Logger.debug('Current Cart token = ' + currentCartId)() syncTaskCollection.iterate((task, id, iterationNumber) => { if (task && !task.transmited && !mutex[id]) { // not sent to the server yet mutex[id] = true // mark this task as being processed @@ -267,19 +267,21 @@ const invokeClientEntry = async () => { mutex[id] = false }).catch(err => { mutex[id] = false - Logger.error(err) + Logger.error(err)() }) }) } }, (err, result) => { - if (err) Logger.error(err) - Logger.debug('Iteration has completed') + if (err) Logger.error(err)() + Logger.debug('Iteration has completed')() // execute them serially serial(fetchQueue) - .then(res => Logger.debug('Processing sync tasks queue has finished')) + .then(res => { + Logger.debug('Processing sync tasks queue has finished')() + }) }).catch(err => { // This code runs if there were any errors - Logger.log(err) + Logger.log(err)() }) }) }) diff --git a/core/compatibility/lib/extensions.ts b/core/compatibility/lib/extensions.ts index 1b50fcc492..123404838f 100644 --- a/core/compatibility/lib/extensions.ts +++ b/core/compatibility/lib/extensions.ts @@ -1,14 +1,14 @@ import { Logger } from '@vue-storefront/core/lib/logger' -export function registerExtensions (extensions, app, router, store, config, ssrContext = null) { - for (let extEntryPoint of extensions) { - if (extEntryPoint !== null) { - if (extEntryPoint.default) extEntryPoint = extEntryPoint.default - let extDescriptor = extEntryPoint(app, router, store, config, ssrContext) // register module - if (extDescriptor != null) { +export function registerExtensions (extensions, app, router, store, config, ssrContext = null) { + for (let extEntryPoint of extensions) { + if (extEntryPoint !== null) { + if (extEntryPoint.default) extEntryPoint = extEntryPoint.default + let extDescriptor = extEntryPoint(app, router, store, config, ssrContext) // register module + if (extDescriptor != null) { Logger.warn('Extension' + extDescriptor.EXTENSION_KEY + ' registered. Extensions are depreciated and will be removed from VS core. Use modules instead')() - app.$emit('application-after-registerExtensions', extDescriptor) - } - } - } -} \ No newline at end of file + app.$emit('application-after-registerExtensions', extDescriptor) + } + } + } +} diff --git a/core/helpers/index.ts b/core/helpers/index.ts index cb6baa74ec..d18f70a954 100644 --- a/core/helpers/index.ts +++ b/core/helpers/index.ts @@ -152,7 +152,7 @@ export function once (key, fn) { const { process = {} } = global const processKey = key + '__ONCE__' if (!process.hasOwnProperty(processKey)) { - Logger.debug(`Once ${key}`, 'helper') + Logger.debug(`Once ${key}`, 'helper')() process[processKey] = true fn() } diff --git a/core/i18n/index.ts b/core/i18n/index.ts index 5f1077c00b..5d48a2ca0e 100644 --- a/core/i18n/index.ts +++ b/core/i18n/index.ts @@ -28,7 +28,7 @@ export function loadLanguageAsync (lang: string): Promise { loadedLanguages.push(lang) return setI18nLanguage(lang) }).catch(err => { - Logger.debug('Unable to load translation') + Logger.debug('Unable to load translation')() return '' }) } diff --git a/core/lib/asyncdataloader.ts b/core/lib/asyncdataloader.ts index e45afb4161..d6ed16b279 100644 --- a/core/lib/asyncdataloader.ts +++ b/core/lib/asyncdataloader.ts @@ -44,4 +44,4 @@ const AsyncDataLoader = { } } -export { AsyncDataLoader, AsyncDataLoaderActionContext, AsyncDataLoaderAction } +export { AsyncDataLoader, AsyncDataLoaderActionContext, AsyncDataLoaderAction } diff --git a/core/lib/logger.ts b/core/lib/logger.ts index b64642f328..8b7b5c4f3b 100644 --- a/core/lib/logger.ts +++ b/core/lib/logger.ts @@ -4,7 +4,7 @@ import buildTimeConfig from 'config' const bgColorStyle = (color) => `color: white; background: ${color}; padding: 4px; font-weight: bold; font-size: 0.8em'` /** VS message logger. By default works only on dev mode */ -class Logger +class Logger { /** @@ -24,9 +24,9 @@ class Logger /** * Logger constructor - * - * @param verbosityLevel - * @param showErrorOnProduction + * + * @param verbosityLevel + * @param showErrorOnProduction */ constructor(verbosityLevel: string = 'display-everything', showErrorOnProduction: boolean = false) { this.verbosityLevel = verbosityLevel; @@ -36,8 +36,8 @@ class Logger /** * Check if method can print into console - * - * @param string method + * + * @param string method */ canPrint(method: string) { let allowedMethods = []; @@ -48,7 +48,7 @@ class Logger allowedMethods = ['error'] } else if (this.verbosityLevel === 'no-console' || (this.isProduction === true && this.showErrorOnProduction === false)) { allowedMethods = [] - } + } if (allowedMethods.indexOf(method) === -1) { return false; @@ -58,10 +58,10 @@ class Logger } /** - * Inform about debug events happening in the app + * Inform about debug events happening in the app * Don't forget to invoke created function after passing arguments to keep context * `Logger.debug(...args)()` - * @param message + * @param message * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ @@ -78,10 +78,10 @@ class Logger } /** - * Inform about log events happening in the app + * Inform about log events happening in the app * Don't forget to invoke created function after passing arguments to keep context * `Logger.log(...args)()` - * @param message + * @param message * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ @@ -90,10 +90,10 @@ class Logger } /** - * Inform about succesful events happening in the app + * Inform about succesful events happening in the app * Don't forget to invoke created function after passing arguments to keep context * `Logger.info(...args)()` - * @param message + * @param message * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ @@ -113,7 +113,7 @@ class Logger * Inform about potential problems that may be a cause of app break * Don't forget to invoke created function after passing arguments to keep context * `Logger.warn(...args)()` - * @param message + * @param message * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ @@ -133,7 +133,7 @@ class Logger * Inform about errors that will break the app * Don't forget to invoke created function after passing arguments to keep context * `Logger.error(...args)()` - * @param message + * @param message * @param tag short tag specifying area where message was spawned (eg. cart, sync, module) * @param context meaningful data related to this message */ diff --git a/core/lib/sync/index.ts b/core/lib/sync/index.ts index 56be005aaa..c72dca54d4 100644 --- a/core/lib/sync/index.ts +++ b/core/lib/sync/index.ts @@ -14,11 +14,11 @@ function queue (task) { Logger.info('Sync task queued ' + task.url, 'sync', { task })() return new Promise((resolve, reject) => { tasksCollection.setItem(task.task_id.toString(), task, (err, resp) => { - if (err) Logger.error(err, 'sync') + if (err) Logger.error(err, 'sync')() Vue.prototype.$bus.$emit('sync/PROCESS_QUEUE', { config: rootStore.state.config }) // process checkout queue resolve(task) }).catch((reason) => { - Logger.error(reason, 'sync') // it doesn't work on SSR + Logger.error(reason, 'sync')() // it doesn't work on SSR reject(reason) }) }) @@ -50,11 +50,11 @@ function execute (task) { // not offline task } else { usersCollection.getItem('current-token', (err, currentToken) => { // TODO: if current token is null we should postpone the queue and force re-login - only if the task requires LOGIN! if (err) { - Logger.error(err, 'sync') + Logger.error(err, 'sync')() } cartsCollection.getItem('current-cart-token', (err, currentCartId) => { if (err) { - Logger.error(err, 'sync') + Logger.error(err, 'sync')() } if (!currentCartId && rootStore.state.cart.cartServerToken) { // this is workaround; sometimes after page is loaded indexedb returns null despite the cart token is properly set currentCartId = rootStore.state.cart.cartServerToken diff --git a/core/lib/sync/task.ts b/core/lib/sync/task.ts index ca5a297f3d..f813782bcb 100644 --- a/core/lib/sync/task.ts +++ b/core/lib/sync/task.ts @@ -29,21 +29,21 @@ function _sleep (time) { } function _internalExecute (resolve, reject, task: Task, currentToken, currentCartId) { - + if (currentToken !== null && rootStore.state.userTokenInvalidateLock > 0) { // invalidate lock set - Logger.log('Waiting for rootStore.state.userTokenInvalidateLock to release for '+ task.url, 'sync') + Logger.log('Waiting for rootStore.state.userTokenInvalidateLock to release for '+ task.url, 'sync')() _sleep(1000).then(() => { - Logger.log('Another try for rootStore.state.userTokenInvalidateLock for ' + task.url, 'sync') + Logger.log('Another try for rootStore.state.userTokenInvalidateLock for ' + task.url, 'sync')() _internalExecute(resolve, reject, task, currentToken, currentCartId) }) return // return but not resolve } else if (rootStore.state.userTokenInvalidateLock < 0) { - Logger.error('Aborting the network task' + task.url + rootStore.state.userTokenInvalidateLock, 'sync') - resolve({ code: 401, message: i18n.t('Error refreshing user token. User is not authorized to access the resource') }) + Logger.error('Aborting the network task' + task.url + rootStore.state.userTokenInvalidateLock, 'sync')() + resolve({ code: 401, message: i18n.t('Error refreshing user token. User is not authorized to access the resource') })() return } else { if (rootStore.state.userTokenInvalidated) { - Logger.log('Using new user token' + rootStore.state.userTokenInvalidated, 'sync') + Logger.log('Using new user token' + rootStore.state.userTokenInvalidated, 'sync')() currentToken = rootStore.state.userTokenInvalidated } } @@ -59,7 +59,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar return response.json() } else { const msg = i18n.t('Error with response - bad content-type!') - Logger.error(msg.toString(), 'sync') + Logger.error(msg.toString(), 'sync')() reject(msg) } }).then((jsonResponse) => { @@ -67,7 +67,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar if (parseInt(jsonResponse.code) !== 200) { let resultString = jsonResponse.result ? toString(jsonResponse.result) : null if (resultString && (resultString.indexOf(i18n.t('not authorized')) >= 0 || resultString.indexOf('not authorized')) >= 0 && currentToken !== null) { // the token is no longer valid, try to invalidate it - Logger.error('Invalid token - need to be revalidated' + currentToken + task.url + rootStore.state.userTokenInvalidateLock, 'sync') + Logger.error('Invalid token - need to be revalidated' + currentToken + task.url + rootStore.state.userTokenInvalidateLock, 'sync')() if (isNaN(rootStore.state.userTokenInvalidateAttemptsCount) || isUndefined(rootStore.state.userTokenInvalidateAttemptsCount)) rootStore.state.userTokenInvalidateAttemptsCount = 0 if (isNaN(rootStore.state.userTokenInvalidateLock) || isUndefined(rootStore.state.userTokenInvalidateLock)) rootStore.state.userTokenInvalidateLock = 0 @@ -76,7 +76,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar if (!rootStore.state.userTokenInvalidateLock) { rootStore.state.userTokenInvalidateLock++ if (rootStore.state.userTokenInvalidateAttemptsCount >= AUTO_REFRESH_MAX_ATTEMPTS) { - Logger.error('Internal Application error while refreshing the tokens. Please clear the storage and refresh page.', 'sync') + Logger.error('Internal Application error while refreshing the tokens. Please clear the storage and refresh page.', 'sync')() rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) TaskQueue.clearNotTransmited() @@ -88,32 +88,32 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar }) rootStore.state.userTokenInvalidateAttemptsCount = 0 } else { - Logger.info('Invalidation process in progress (autoRefreshTokens is set to true)' + rootStore.state.userTokenInvalidateAttemptsCount + rootStore.state.userTokenInvalidateLock, 'sync') + Logger.info('Invalidation process in progress (autoRefreshTokens is set to true)' + rootStore.state.userTokenInvalidateAttemptsCount + rootStore.state.userTokenInvalidateLock, 'sync')() rootStore.state.userTokenInvalidateAttemptsCount++ rootStore.dispatch('user/refresh').then((resp) => { if (resp.code === 200) { rootStore.state.userTokenInvalidateLock = 0 rootStore.state.userTokenInvalidated = resp.result - Logger.info('User token refreshed successfully' + resp.result, 'sync') + Logger.info('User token refreshed successfully' + resp.result, 'sync')() } else { rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') TaskQueue.clearNotTransmited() - Logger.error('Error refreshing user token' + resp.result, 'sync') + Logger.error('Error refreshing user token' + resp.result, 'sync')() } }).catch((excp) => { rootStore.state.userTokenInvalidateLock = -1 rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') TaskQueue.clearNotTransmited() - Logger.error('Error refreshing user token' + excp, 'sync') + Logger.error('Error refreshing user token' + excp, 'sync')() }) } } if (rootStore.state.userTokenInvalidateAttemptsCount <= AUTO_REFRESH_MAX_ATTEMPTS) _internalExecute(resolve, reject, task, currentToken, currentCartId) // retry } else { - Logger.info('Invalidation process is disabled (autoRefreshTokens is set to false)', 'sync') + Logger.info('Invalidation process is disabled (autoRefreshTokens is set to false)', 'sync')() rootStore.dispatch('user/logout', { silent: true }) Vue.prototype.$bus.$emit('modal-show', 'modal-signup') } @@ -126,7 +126,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar }) } } - Logger.debug('Response for: ' + task.task_id + ' = ' + jsonResponse.result, 'sync') + Logger.debug('Response for: ' + task.task_id + ' = ' + jsonResponse.result, 'sync')() task.transmited = true task.transmited_at = new Date() task.result = jsonResponse.result @@ -146,11 +146,11 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar } } else { const msg = i18n.t('Unhandled error, wrong response format!') - Logger.error(msg.toString(), 'sync') + Logger.error(msg.toString(), 'sync')() reject(msg) } }).catch((err) => { - Logger.error(err, 'sync') + Logger.error(err, 'sync')() reject(err) }) } diff --git a/core/mixins/composite.js b/core/mixins/composite.js index cf8f3dd812..6e82f86dd3 100644 --- a/core/mixins/composite.js +++ b/core/mixins/composite.js @@ -5,22 +5,22 @@ import { Logger } from '@vue-storefront/core/lib/logger' export default { beforeCreated () { const eventName = this.$options.name.toLowerCase() + '-before-created' - Logger.debug(eventName, 'event') + Logger.debug(eventName, 'event')() EventBus.$emit(eventName, this) }, created () { const eventName = this.$options.name.toLowerCase() + '-after-created' - Logger.debug(eventName, 'event') + Logger.debug(eventName, 'event')() EventBus.$emit(eventName, this) }, beforeMount () { const eventName = this.$options.name.toLowerCase() + '-before-mount' - Logger.debug(eventName, 'event') + Logger.debug(eventName, 'event')() EventBus.$emit(eventName, this) }, mounted () { const eventName = this.$options.name.toLowerCase() + '-after-mounted' - Logger.debug(eventName, 'event') + Logger.debug(eventName, 'event')() EventBus.$emit(eventName, this) } diff --git a/core/modules/cart/store/actions.ts b/core/modules/cart/store/actions.ts index d1504ba52a..7eec208418 100644 --- a/core/modules/cart/store/actions.ts +++ b/core/modules/cart/store/actions.ts @@ -29,7 +29,7 @@ function _updateClientItem (event, clientItem) { } function _afterServerItemUpdated (event, clientItem = null) { - Logger.debug('Cart item server sync' + event, 'cart') + Logger.debug('Cart item server sync' + event, 'cart')() if (clientItem === null) { rootStore.dispatch('cart/getItem', event.result.sku, { root: true }).then((cartItem) => { if (cartItem) { @@ -75,7 +75,7 @@ const actions: ActionTree = { const storeView = currentStoreView() if ((Date.now() - context.state.cartServerMethodsRefreshAt) >= CART_METHODS_INTERVAL_MS) { context.state.cartServerMethodsRefreshAt = Date.now() - Logger.debug('Refreshing payment & shipping methods', 'cart') + Logger.debug('Refreshing payment & shipping methods', 'cart')() rootStore.dispatch('cart/getPaymentMethods') if (context.state.cartItems.length > 0) { let country = rootStore.state.checkout.shippingDetails.country ? rootStore.state.checkout.shippingDetails.country : storeView.tax.defaultCountry @@ -86,7 +86,7 @@ const actions: ActionTree = { } }) } else { - Logger.log('Too short interval for refreshing the cart or items not changed' + newItemsHash + context.state.cartItemsHash, 'cart') + Logger.log('Too short interval for refreshing the cart or items not changed' + newItemsHash + context.state.cartItemsHash, 'cart')() } } }, @@ -105,7 +105,7 @@ const actions: ActionTree = { callback_event: 'store:cart/servercartAfterTotals' }) } else { - Logger.log('Too short interval for refreshing the cart totals', 'cart') + Logger.log('Too short interval for refreshing the cart totals', 'cart')() } } }, @@ -355,7 +355,7 @@ const actions: ActionTree = { rootStore.dispatch('payment/replaceMethods', paymentMethods, { root: true }) Vue.prototype.$bus.$emit('set-unique-payment-methods', uniqueBackendMethods) }).catch(e => { - Logger.error(e, 'cart') + Logger.error(e, 'cart')() }) } }, @@ -376,7 +376,7 @@ const actions: ActionTree = { rootStore.dispatch('shipping/replaceMethods', task.result, { root: true }) } }).catch(e => { - Logger.error(e, 'cart') + Logger.error(e, 'cart')() }) } }, @@ -421,7 +421,7 @@ const actions: ActionTree = { silent: true, callback_event: 'store:cart/servercartAfterTotals' }).catch(e => { - Logger.error(e, 'cart') + Logger.error(e, 'cart')() }) } else { context.dispatch('cart/serverTotals', {}, { root: true }) @@ -444,7 +444,7 @@ const actions: ActionTree = { resolve(task.result) } }).catch(e => { - Logger.error(e, 'cart') + Logger.error(e, 'cart')() reject(e) }) } @@ -468,7 +468,7 @@ const actions: ActionTree = { reject(false) } }).catch(e => { - Logger.log(e, 'cart') + Logger.log(e, 'cart')() reject(e) }) } @@ -477,7 +477,7 @@ const actions: ActionTree = { userAfterLoggedin () { Vue.prototype.$db.usersCollection.getItem('last-cart-bypass-ts', (err, lastCartBypassTs) => { if (err) { - Logger.error(err, 'cart') + Logger.error(err, 'cart')() } if (!rootStore.state.config.cart.bypassCartLoaderForAuthorizedUsers || (Date.now() - lastCartBypassTs) >= (1000 * 60 * 24)) { // don't refresh the shopping cart id up to 24h after last order rootStore.dispatch('cart/serverCreate', { guestCart: false }, { root: true }) @@ -494,10 +494,10 @@ const actions: ActionTree = { let resultString = event.result ? toString(event.result) : null if (resultString && (resultString.indexOf(i18n.t('not authorized')) < 0 && resultString.indexOf('not authorized')) < 0) { // not respond to unathorized errors here if (rootStore.state.cart.bypassCount < MAX_BYPASS_COUNT) { - Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart') + Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart')() rootStore.state.cart.bypassCount = rootStore.state.cart.bypassCount + 1 rootStore.dispatch('cart/serverCreate', { guestCart: true }, { root: true }) - Logger.error(event.result, 'cart') + Logger.error(event.result, 'cart')() } } } @@ -515,7 +515,7 @@ const actions: ActionTree = { } rootStore.commit(types.SN_CART + '/' + types.CART_UPD_TOTALS, { itemsAfterTotal: itemsAfterTotal, totals: totalsObj, platformTotalSegments: platformTotalSegments }) } else { - Logger.error(event.result, 'cart') + Logger.error(event.result, 'cart')() } }, servercartAfterPulled (context, event) { @@ -549,7 +549,7 @@ const actions: ActionTree = { }) if (!serverItem) { - Logger.warn('No server item with sku ' + clientItem.sku + ' on stock.', 'cart') + Logger.warn('No server item with sku ' + clientItem.sku + ' on stock.', 'cart')() diffLog.push({ 'party': 'server', 'sku': clientItem.sku, 'status': 'no_item' }) if (!event.dry_run) { if (event.force_client_state || !rootStore.state.config.cart.serverSyncCanRemoveLocalItems) { @@ -568,7 +568,7 @@ const actions: ActionTree = { } } } else if (serverItem.qty !== clientItem.qty) { - Logger.log('Wrong qty for ' + clientItem.sku, clientItem.qty, serverItem.qty) + Logger.log('Wrong qty for ' + clientItem.sku, clientItem.qty, serverItem.qty)() diffLog.push({ 'party': 'server', 'sku': clientItem.sku, 'status': 'wrong_qty', 'client_qty': clientItem.qty, 'server_qty': serverItem.qty }) if (!event.dry_run) { if (event.force_client_state || !rootStore.state.config.cart.serverSyncCanModifyLocalItems) { @@ -589,8 +589,8 @@ const actions: ActionTree = { } } } else { - Logger.info('Server and client item with SKU ' + clientItem.sku + ' synced. Updating cart.', 'cart', 'cart') - // Logger.log('Updating server id to ', { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option }) + Logger.info('Server and client item with SKU ' + clientItem.sku + ' synced. Updating cart.', 'cart', 'cart')() + // Logger.log('Updating server id to ', { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option })() if (!event.dry_run) { rootStore.dispatch('cart/updateItem', { product: { sku: clientItem.sku, server_cart_id: serverItem.quote_id, server_item_id: serverItem.item_id, product_option: serverItem.product_option } }, { root: true }) } @@ -610,7 +610,7 @@ const actions: ActionTree = { if (event.force_client_state) { Logger.info('Removing product from cart', 'cart', serverItem)() - Logger.log('Removing item' + serverItem.sku + serverItem.item_id, 'cart') + Logger.log('Removing item' + serverItem.sku + serverItem.item_id, 'cart')() serverCartUpdateRequired = true rootStore.dispatch('cart/serverDeleteItem', { sku: serverItem.sku, @@ -658,12 +658,12 @@ const actions: ActionTree = { Vue.prototype.$bus.$emit('servercart-after-diff', { diffLog: diffLog, serverItems: serverItems, clientItems: clientItems, dryRun: event.dry_run, event: event }) // send the difflog Logger.info('Client/Server cart synchronised ', 'cart', diffLog)() } else { - Logger.error(event.result, 'cart') // override with guest cart + Logger.error(event.result, 'cart') // override with guest cart() if (rootStore.state.cart.bypassCount < MAX_BYPASS_COUNT) { - Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart') + Logger.log('Bypassing with guest cart' + rootStore.state.cart.bypassCount, 'cart')() rootStore.state.cart.bypassCount = rootStore.state.cart.bypassCount + 1 rootStore.dispatch('cart/serverCreate', { guestCart: true }, { root: true }) - Logger.error(event.result, 'cart') + Logger.error(event.result, 'cart')() } } }, @@ -674,7 +674,7 @@ const actions: ActionTree = { if (originalCartItem.item_id) { rootStore.dispatch('cart/getItem', originalCartItem.sku, { root: true }).then((cartItem) => { if (cartItem) { - Logger.log('Restoring qty after error' + originalCartItem.sku + cartItem.prev_qty, 'cart') + Logger.log('Restoring qty after error' + originalCartItem.sku + cartItem.prev_qty, 'cart')() if (cartItem.prev_qty > 0) { rootStore.dispatch('cart/updateItem', { product: { qty: cartItem.prev_qty } }, { root: true }) // update the server_id reference Vue.prototype.$bus.$emit('cart-after-itemchanged', { item: cartItem }) diff --git a/core/modules/catalog/components/ProductBundleOptions.ts b/core/modules/catalog/components/ProductBundleOptions.ts index 324b14c8a7..d76641ffec 100644 --- a/core/modules/catalog/components/ProductBundleOptions.ts +++ b/core/modules/catalog/components/ProductBundleOptions.ts @@ -97,7 +97,7 @@ export const ProductBundleOptions = { this.product.errors['bundle_options_' + fieldName] = null } } else { - Logger.error('No validation rule found for ' + validationRule, 'components-product-bundle-options') + Logger.error('No validation rule found for ' + validationRule, 'components-product-bundle-options')() this.$set(this.validationResults, fieldName, validationResult) } } else { diff --git a/core/modules/catalog/components/ProductCustomOptions.ts b/core/modules/catalog/components/ProductCustomOptions.ts index cc359650bf..98d8cded25 100644 --- a/core/modules/catalog/components/ProductCustomOptions.ts +++ b/core/modules/catalog/components/ProductCustomOptions.ts @@ -83,7 +83,7 @@ export const ProductCustomOptions = { this.product.errors['custom_options_' + fieldName] = null } } else { - Logger.error('No validation rule found for ' + validationRule, 'components-product-custom-options') + Logger.error('No validation rule found for ' + validationRule, 'components-product-custom-options')() this.validation.results[fieldName] = { error: false, message: '' } } } else { diff --git a/core/modules/catalog/components/Search.ts b/core/modules/catalog/components/Search.ts index 746fa2118e..199a460935 100644 --- a/core/modules/catalog/components/Search.ts +++ b/core/modules/catalog/components/Search.ts @@ -41,7 +41,7 @@ export const Search = { this.start = this.start + this.size this.emptyResults = resp.items.length < 1 }).catch((err) => { - Logger.error(err, 'components-search') + Logger.error(err, 'components-search')() }) } else { this.products = [] @@ -61,7 +61,7 @@ export const Search = { this.start = this.start + this.size this.emptyResults = this.products.length < 1 }).catch((err) => { - Logger.error(err, 'components-search') + Logger.error(err, 'components-search')() }) } else { this.products = [] diff --git a/core/modules/catalog/helpers/index.ts b/core/modules/catalog/helpers/index.ts index 816b0e31eb..d8513644f8 100644 --- a/core/modules/catalog/helpers/index.ts +++ b/core/modules/catalog/helpers/index.ts @@ -57,7 +57,7 @@ function _filterChildrenByStockitem (context, stockItems, product, diffLog) { config[optionKey] = opt const variant = isOptionAvailableAsync(context, { product: product, configuration: config }) if (!variant) { - Logger.log('No variant for' + opt, 'helper') + Logger.log('No variant for' + opt, 'helper')() Vue.prototype.$bus.$emit('product-after-removevariant', { product: product }) removedOptions++ return false @@ -66,7 +66,7 @@ function _filterChildrenByStockitem (context, stockItems, product, diffLog) { return true } }) - Logger.debug('Options still available' + optionsAvailable + removedOptions, 'helper') + Logger.debug('Options still available' + optionsAvailable + removedOptions, 'helper')() context.state.current_options[optionKey] = optionsAvailable } } @@ -94,24 +94,24 @@ export function filterOutUnavailableVariants (context, product) { confChildSkus = remove(confChildSkus, (skuToCheck) => skuToCheck === confChild.sku) } } - Logger.debug('Cached stock items and delta' + stockItems + confChildSkus) + Logger.debug('Cached stock items and delta' + stockItems + confChildSkus)() if (confChildSkus.length > 0) { context.dispatch('stock/list', { skus: confChildSkus }, {root: true}).then((task) => { if (task && task.resultCode === 200) { const diffLog = [] _filterChildrenByStockitem(context, union(task.result, stockItems), product, diffLog) - Logger.debug('Filtered configurable_children with the network call' + diffLog, 'helper') + Logger.debug('Filtered configurable_children with the network call' + diffLog, 'helper')() resolve() } else { - Logger.error('Cannot sync the availability of the product options. Please update the vue-storefront-api or switch on the Internet :)', 'helper') + Logger.error('Cannot sync the availability of the product options. Please update the vue-storefront-api or switch on the Internet :)', 'helper')() } }).catch(err => { - Logger.error(err, 'helper') + Logger.error(err, 'helper')() }) } else { const diffLog = [] _filterChildrenByStockitem(context, stockItems, product, diffLog) - Logger.debug('Filtered configurable_children without the network call' + diffLog, 'helper') + Logger.debug('Filtered configurable_children without the network call' + diffLog, 'helper')() resolve() } } else { @@ -122,12 +122,12 @@ export function filterOutUnavailableVariants (context, product) { if (!rootStockCached) { context.dispatch('stock/list', { skus: [product.sku] }, {root: true}).then((task) => { _filterRootProductByStockitem(context, task && task.result && task.result.length ? task.result[0] : null, product, reject) - Logger.debug('Filtered root product stock with the network call') + Logger.debug('Filtered root product stock with the network call')() _filterConfigurableHelper() }) } else { _filterRootProductByStockitem(context, rootStockCached, product, reject) - Logger.debug('Filtered root product stock without the network call') + Logger.debug('Filtered root product stock without the network call')() _filterConfigurableHelper() } } else { @@ -157,7 +157,7 @@ export function syncProductPrice (product, backProduct) { // TODO: we probably n product.special_price = 0 // the same price as original; it's not a promotion } Vue.prototype.$bus.$emit('product-after-priceupdate', product) - // Logger.log(product.sku, product, backProduct) + // Logger.log(product.sku, product, backProduct)() return product } /** @@ -206,7 +206,7 @@ export function doPlatformPricesSync (products) { skus = union(skus, childSkus) } if (skus && skus.length > 0) { - Logger.log('Starting platform prices sync for', skus) // TODO: add option for syncro and non syncro return + Logger.log('Starting platform prices sync for', skus) // TODO: add option for syncro and non syncro return() rootStore.dispatch('product/syncPlatformPricesOver', { skus: skus }, { root: true }).then((syncResult) => { if (syncResult) { syncResult = syncResult.items @@ -236,7 +236,7 @@ export function doPlatformPricesSync (products) { resolve(products) } if (!rootStore.state.config.products.waitForPlatformSync && !Vue.prototype.$isServer) { - Logger.log('Returning products, the prices yet to come from backend!') + Logger.log('Returning products, the prices yet to come from backend!')() for (let product of products) { product.price_is_current = false // in case we're syncing up the prices we should mark if we do have current or not product.price_refreshed_at = null @@ -255,7 +255,7 @@ export function doPlatformPricesSync (products) { export function calculateTaxes (products, store) { return new Promise((resolve, reject) => { if (rootStore.state.config.tax.calculateServerSide) { - Logger.debug('Taxes calculated server side, skipping') + Logger.debug('Taxes calculated server side, skipping')() doPlatformPricesSync(products).then((products) => { resolve(products) }) @@ -299,7 +299,7 @@ export function setConfigurableProductOptionsAsync (context, { product, configur }) if (!option) { - Logger.error('Wrong option id for setProductOptions', configOption.attribute_code) + Logger.error('Wrong option id for setProductOptions', configOption.attribute_code)() return null } let existingOption = configurable_item_options.find(cop => { @@ -319,7 +319,7 @@ export function setConfigurableProductOptionsAsync (context, { product, configur existingOption.value = configOption.label } } - // Logger.debug('Server product options object', product_option) + // Logger.debug('Server product options object', product_option)() return product_option } else { return null @@ -360,7 +360,7 @@ export function populateProductConfigurationAsync (context, { product, selectedV if (option.attribute_id) { let attr = context.rootState.attribute.list_by_id[option.attribute_id] if (!attr) { - Logger.error('Wrong attribute given in configurable_options - can not find by attribute_id', option) + Logger.error('Wrong attribute given in configurable_options - can not find by attribute_id', option)() continue } else { attribute_code = attr.attribute_code @@ -368,7 +368,7 @@ export function populateProductConfigurationAsync (context, { product, selectedV } } else { if (!option.attribute_code) { - Logger.error('Wrong attribute given in configurable_options - no attribute_code', option) + Logger.error('Wrong attribute given in configurable_options - no attribute_code', option)() continue } else { // we do have attribute_code! attribute_code = option.attribute_code @@ -477,7 +477,7 @@ export function configureProductAsync (context, { product, configuration, select if (typeof navigator !== 'undefined') { if (selectedVariant && !navigator.onLine && context.state.offlineImage) { // this is fix for not preloaded images for offline selectedVariant.image = context.state.offlineImage - Logger.debug('Image offline fallback to ', context.state.offlineImage) + Logger.debug('Image offline fallback to ', context.state.offlineImage)() } } if (selectedVariant) { @@ -498,7 +498,7 @@ export function configureProductAsync (context, { product, configuration, select selectedVariant.options = _internalMapOptions(productOption) } }/* else { - Logger.debug('Skipping configurable options setup', configuration) + Logger.debug('Skipping configurable options setup', configuration)() } */ const fieldsToOmit = ['name'] if (selectedVariant.image === "") fieldsToOmit.push('image') diff --git a/core/modules/catalog/helpers/tax.ts b/core/modules/catalog/helpers/tax.ts index 006ea96357..067d536172 100644 --- a/core/modules/catalog/helpers/tax.ts +++ b/core/modules/catalog/helpers/tax.ts @@ -126,18 +126,18 @@ export function calculateProductTax (product, taxClasses, taxCountry = 'PL', tax if (rate.tax_country_id === taxCountry && (rate.region_name === taxRegion || rate.tax_region_id === 0 || !rate.region_name)) { updateProductPrices(product, rate, sourcePriceInclTax) rateFound = true - Logger.debug('Tax rate ' + rate.code + ' = ' + rate.rate + '% found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax') + Logger.debug('Tax rate ' + rate.code + ' = ' + rate.rate + '% found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax')() break } } } else { - Logger.debug('No such tax class id: ' + product.tax_class_id, 'helper-tax') + Logger.debug('No such tax class id: ' + product.tax_class_id, 'helper-tax')() } } else { - Logger.debug('No tax class set for: ' + product.sku, 'helper-tax') + Logger.debug('No tax class set for: ' + product.sku, 'helper-tax')() } if (!rateFound) { - Logger.log('No such tax class id: ' + product.tax_class_id + ' or rate not found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax') + Logger.log('No such tax class id: ' + product.tax_class_id + ' or rate not found for ' + taxCountry + ' / ' + taxRegion, 'helper-tax')() updateProductPrices(product, {rate: 0}) product.priceInclTax = product.price diff --git a/core/modules/catalog/store/attribute/mutations.ts b/core/modules/catalog/store/attribute/mutations.ts index 27e963bdda..8797465f28 100644 --- a/core/modules/catalog/store/attribute/mutations.ts +++ b/core/modules/catalog/store/attribute/mutations.ts @@ -29,7 +29,7 @@ const mutations: MutationTree = { Logger.error(reason, 'mutations') // it doesn't work on SSR }) // populate cache by id } catch (e) { - Logger.error(e, 'mutations') + Logger.error(e, 'mutations')() } } Vue.set(state, 'list_by_code', attrHashByCode) diff --git a/core/modules/catalog/store/category/actions.ts b/core/modules/catalog/store/category/actions.ts index 84a8a2da69..b73ef7323e 100644 --- a/core/modules/catalog/store/category/actions.ts +++ b/core/modules/catalog/store/category/actions.ts @@ -47,7 +47,7 @@ const actions: ActionTree = { if (level !== rootStore.state.config.entities.category.categoriesDynamicPrefetchLevel) // if this is the default level we're getting the results from window.__INITIAL_STATE__ not querying the server customizedQuery = true } - + if (key !== null) { searchQuery = searchQuery.applyFilter({key: key, value: {'eq': value}}) customizedQuery = true @@ -111,7 +111,7 @@ const actions: ActionTree = { return } if (error) { - Logger.error(error) + Logger.error(error)() reject(error) } @@ -139,7 +139,7 @@ const actions: ActionTree = { recurCatFinder(sc) } }).catch(err => { - Logger.error(err) + Logger.error(err)() commit(types.CATEGORY_UPD_CURRENT_CATEGORY_PATH, currentPath) // this is the case when category is not binded to the root tree - for example 'Erin Recommends' resolve(mainCategory) }) @@ -201,13 +201,13 @@ const actions: ActionTree = { includeFields = rootStore.state.config.entities.productListWithChildren.includeFields // we need configurable_children for filters to work excludeFields = rootStore.state.config.entities.productListWithChildren.excludeFields prefetchGroupProducts = false - Logger.log('Using two stage caching for performance optimization - executing first stage product pre-fetching') + Logger.log('Using two stage caching for performance optimization - executing first stage product pre-fetching')() } else { prefetchGroupProducts = true if (rootStore.state.twoStageCachingDisabled) { - Logger.log('Two stage caching is disabled runtime because of no performance gain') + Logger.log('Two stage caching is disabled runtime because of no performance gain')() } else { - Logger.log('Two stage caching is disabled by the config') + Logger.log('Two stage caching is disabled by the config')() } } let t0 = new Date().getTime() @@ -314,7 +314,7 @@ const actions: ActionTree = { } return subloaders }).catch((err) => { - Logger.error(err) + Logger.error(err)() rootStore.dispatch('notification/spawnNotification', { type: 'warning', message: i18n.t('No products synchronized for this category. Please come back while online!'), @@ -323,7 +323,7 @@ const actions: ActionTree = { }) if (rootStore.state.config.entities.twoStageCaching && rootStore.state.config.entities.optimize && !Vue.prototype.$isServer && !rootStore.state.twoStageCachingDisabled) { // second stage - request for caching entities - Logger.log('Using two stage caching for performance optimization - executing second stage product caching', 'category') // TODO: in this case we can pre-fetch products in advance getting more products than set by pageSize + Logger.log('Using two stage caching for performance optimization - executing second stage product caching', 'category') // TODO: in this case we can pre-fetch products in advance getting more products than set by pageSize() rootStore.dispatch('product/list', { query: precachedQuery, start: current, @@ -332,15 +332,15 @@ const actions: ActionTree = { includeFields: null, updateState: false // not update the product listing - this request is only for caching }).catch((err) => { - Logger.info("Problem with second stage caching - couldn't store the data", 'category') - Logger.info(err, 'category') + Logger.info("Problem with second stage caching - couldn't store the data", 'category')() + Logger.info(err, 'category')() }).then((res) => { let t2 = new Date().getTime() rootStore.state.twoStageCachingDelta2 = t2 - t0 - Logger.log('Using two stage caching for performance optimization - Time comparison stage1 vs stage2' + rootStore.state.twoStageCachingDelta1 + rootStore.state.twoStageCachingDelta2, 'category') + Logger.log('Using two stage caching for performance optimization - Time comparison stage1 vs stage2' + rootStore.state.twoStageCachingDelta1 + rootStore.state.twoStageCachingDelta2, 'category')() if (rootStore.state.twoStageCachingDelta1 > rootStore.state.twoStageCachingDelta2) { // two stage caching is not making any good rootStore.state.twoStageCachingDisabled = true - Logger.log('Disabling two stage caching', 'category') + Logger.log('Disabling two stage caching', 'category')() } }) } diff --git a/core/modules/catalog/store/category/mutations.ts b/core/modules/catalog/store/category/mutations.ts index 498a464b9e..4dc7cad990 100644 --- a/core/modules/catalog/store/category/mutations.ts +++ b/core/modules/catalog/store/category/mutations.ts @@ -39,7 +39,7 @@ const mutations: MutationTree = { Logger.error(reason, 'category') // it doesn't work on SSR }) // populate cache by id } catch (e) { - Logger.error(e, 'category') + Logger.error(e, 'category')() } } } diff --git a/core/modules/catalog/store/product/actions.ts b/core/modules/catalog/store/product/actions.ts index d5c228621d..7028e4d160 100644 --- a/core/modules/catalog/store/product/actions.ts +++ b/core/modules/catalog/store/product/actions.ts @@ -3,15 +3,15 @@ import { ActionTree } from 'vuex' import * as types from './mutation-types' import { breadCrumbRoutes, productThumbnailPath } from '@vue-storefront/core/helpers' import { currentStoreView } from '@vue-storefront/core/lib/multistore' -import { configureProductAsync, - doPlatformPricesSync, - filterOutUnavailableVariants, - calculateTaxes, - populateProductConfigurationAsync, - setCustomProductOptionsAsync, - setBundleProductOptionsAsync, - getMediaGallery, - configurableChildrenImages, +import { configureProductAsync, + doPlatformPricesSync, + filterOutUnavailableVariants, + calculateTaxes, + populateProductConfigurationAsync, + setCustomProductOptionsAsync, + setBundleProductOptionsAsync, + getMediaGallery, + configurableChildrenImages, attributeImages } from '../../helpers' import SearchQuery from '@vue-storefront/core/lib/search/searchQuery' import { entityKeyName } from '@vue-storefront/store/lib/entities' @@ -51,8 +51,8 @@ const actions: ActionTree = { name: context.rootGetters['category/getCurrentCategory'].name }) // current category at the end } - // depreciated, TODO: base on breadcrumbs module - context.state.breadcrumbs.routes = breadCrumbRoutes(path) // TODO: change to store.commit call? + // depreciated, TODO: base on breadcrumbs module + context.state.breadcrumbs.routes = breadCrumbRoutes(path) // TODO: change to store.commit call? } if (product.category && product.category.length > 0) { @@ -84,13 +84,13 @@ const actions: ActionTree = { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) }).catch(err => { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) - Logger.error(err) + Logger.error(err)() }) } else { setbrcmb(context.rootGetters['category/getCurrentCategoryPath']) } }).catch(err => { - Logger.error(err) + Logger.error(err)() }) ) } @@ -131,17 +131,17 @@ const actions: ActionTree = { if (product.type_id === 'grouped') { product.price = 0 product.priceInclTax = 0 - Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id) + Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id)() if (product.product_links && product.product_links.length > 0) { for (let pl of product.product_links) { if (pl.link_type === 'associated' && pl.linked_product_type === 'simple') { // prefetch links - Logger.debug('Prefetching grouped product link for ' + pl.sku + ' = ' + pl.linked_product_sku) + Logger.debug('Prefetching grouped product link for ' + pl.sku + ' = ' + pl.linked_product_sku)() subloaders.push(context.dispatch('single', { options: { sku: pl.linked_product_sku }, setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { Logger.error(err) }).then((asocProd) => { + }).catch(err => { Logger.error(err) }).then((asocProd) => {() if (asocProd) { pl.product = asocProd pl.product.qty = 1 @@ -149,31 +149,31 @@ const actions: ActionTree = { product.priceInclTax += pl.product.priceInclTax product.tax += pl.product.tax } else { - Logger.error('Product link not found', pl.linked_product_sku) + Logger.error('Product link not found', pl.linked_product_sku)() } })) } } } else { - Logger.error('Product with type grouped has no product_links set!', product) + Logger.error('Product with type grouped has no product_links set!', product)() } } if (product.type_id === 'bundle') { product.price = 0 product.priceInclTax = 0 - Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id) + Logger.debug(product.name + ' SETUP ASSOCIATED', product.type_id)() if (product.bundle_options && product.bundle_options.length > 0) { for (let bo of product.bundle_options) { let defaultOption = bo.product_links.find((p) => { return p.is_default }) if (!defaultOption) defaultOption = bo.product_links[0] for (let pl of bo.product_links) { - Logger.debug('Prefetching bundle product link for ' + bo.sku + ' = ' + pl.sku) + Logger.debug('Prefetching bundle product link for ' + bo.sku + ' = ' + pl.sku)() subloaders.push(context.dispatch('single', { options: { sku: pl.sku }, setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { Logger.error(err) }).then((asocProd) => { + }).catch(err => { Logger.error(err) }).then((asocProd) => {() if (asocProd) { pl.product = asocProd pl.product.qty = pl.qty @@ -184,7 +184,7 @@ const actions: ActionTree = { product.tax += pl.product.tax * pl.product.qty } } else { - Logger.error('Product link not found', pl.sku) + Logger.error('Product link not found', pl.sku)() } })) } @@ -199,7 +199,7 @@ const actions: ActionTree = { */ checkConfigurableParent (context, {product}) { if (product.type_id === 'simple') { - Logger.log('Checking configurable parent') + Logger.log('Checking configurable parent')() let searchQuery = new SearchQuery() searchQuery = searchQuery.applyFilter({key: 'configurable_children.sku', value: {'eq': context.state.current.sku}}) @@ -210,7 +210,7 @@ const actions: ActionTree = { context.commit(types.CATALOG_SET_PRODUCT_PARENT, parentProduct) } }).catch((err) => { - Logger.error(err) + Logger.error(err)() }) } }, @@ -228,7 +228,7 @@ const actions: ActionTree = { } else { attributeKey = 'attribute_code' return opt.attribute_code - } + } }) subloaders.push(context.dispatch('attribute/list', { filterValues: configurableAttrKeys, @@ -257,7 +257,7 @@ const actions: ActionTree = { let selectedVariant = context.state.current populateProductConfigurationAsync(context, { selectedVariant: selectedVariant, product: product }) }).catch(err => { - Logger.error(err) + Logger.error(err)() })) } return Promise.all(subloaders) @@ -277,9 +277,9 @@ const actions: ActionTree = { list (context, { query, start = 0, size = 50, entityType = 'product', sort = '', cacheByKey = 'sku', prefetchGroupProducts = true, updateState = false, meta = {}, excludeFields = null, includeFields = null, configuration = null, append = false, populateRequestCacheTags = true }) { let isCacheable = (includeFields === null && excludeFields === null) if (isCacheable) { - Logger.debug('Entity cache is enabled for productList') + Logger.debug('Entity cache is enabled for productList')() } else { - Logger.debug('Entity cache is disabled for productList') + Logger.debug('Entity cache is disabled for productList')() } if (rootStore.state.config.entities.optimize) { @@ -330,7 +330,7 @@ const actions: ActionTree = { if (isCacheable) { // store cache only for full loads cache.setItem(cacheKey, prod) .catch((err) => { - Logger.error('Cannot store cache for ' + cacheKey, err) + Logger.error('Cannot store cache for ' + cacheKey, err)() }) } if ((prod.type_id === 'grouped' || prod.type_id === 'bundle') && prefetchGroupProducts) { @@ -460,11 +460,11 @@ const actions: ActionTree = { cache.getItem(cacheKey, (err, res) => { // report errors if (!skipCache && err) { - Logger.error(err, 'product') + Logger.error(err, 'product')() } if (res !== null) { - Logger.debug('Product:single - result from localForage (for ' + cacheKey + '), ms=' + (new Date().getTime() - benchmarkTime.getTime()), 'product') + Logger.debug('Product:single - result from localForage (for ' + cacheKey + '), ms=' + (new Date().getTime() - benchmarkTime.getTime()), 'product')() const _returnProductFromCacheHelper = (subresults) => { const cachedProduct = setupProduct(res) if (rootStore.state.config.products.alwaysSyncPlatformPricesOver) { @@ -533,7 +533,7 @@ const actions: ActionTree = { if (errors && typeof errors === 'object') { context.commit(types.CATALOG_SET_PRODUCT_CURRENT, Object.assign({}, context.state.current, { errors: errors })) } - }, + }, /** * Assign the custom options object to the currentl product */ @@ -562,7 +562,7 @@ const actions: ActionTree = { if (!context.state.offlineImage) { context.state.offlineImage = productThumbnailPath(productOriginal, true) - Logger.debug('Image offline fallback set to ' + context.state.offlineImage, 'product') + Logger.debug('Image offline fallback set to ' + context.state.offlineImage, 'product')() } // check if passed variant is the same as original const productUpdated = Object.assign({}, productOriginal, productVariant) @@ -571,7 +571,7 @@ const actions: ActionTree = { context.commit(types.CATALOG_UPD_GALLERY, attributeImages(productVariant)) } context.commit(types.CATALOG_SET_PRODUCT_CURRENT, productUpdated) - } else Logger.debug('Unable to update current product.', 'product') + } else Logger.debug('Unable to update current product.', 'product')() }, /** * Set given product as original @@ -580,7 +580,7 @@ const actions: ActionTree = { */ setOriginal (context, originalProduct) { if (originalProduct && typeof originalProduct === 'object') context.commit(types.CATALOG_SET_PRODUCT_ORIGINAL, originalProduct) - else Logger.debug('Unable to setup original product.', 'product') + else Logger.debug('Unable to setup original product.', 'product')() }, /** * Set related products @@ -605,7 +605,7 @@ const actions: ActionTree = { if (product.visibility === 1) { // not visible individually (https://magento.stackexchange.com/questions/171584/magento-2-table-name-for-product-visibility) throw new Error(`Product query returned empty result product visibility = ${product.visibility}`) } - + let subloaders = [] if (product) { const productFields = Object.keys(product).filter(fieldName => { @@ -671,7 +671,7 @@ const actions: ActionTree = { */ fetchAsync (context, { parentSku, childSku = null, route = null }) { if (context.state.productLoadStart && (Date.now() - context.state.productLoadStart) < PRODUCT_REENTER_TIMEOUT) { - Logger.log('Product is being fetched ...', 'product') + Logger.log('Product is being fetched ...', 'product')() } else { context.state.productLoadPromise = new Promise((resolve, reject) => { context.state.productLoadStart = Date.now() @@ -685,7 +685,7 @@ const actions: ActionTree = { return resolve() }).catch((err) => { context.state.productLoadStart = null - Logger.error(err, 'product') + Logger.error(err, 'product')() return resolve() }) }).catch(errs => { diff --git a/core/modules/catalog/store/stock/actions.ts b/core/modules/catalog/store/stock/actions.ts index 139a875e44..9ead3d0c54 100644 --- a/core/modules/catalog/store/stock/actions.ts +++ b/core/modules/catalog/store/stock/actions.ts @@ -53,7 +53,7 @@ const actions: ActionTree = { } resolve(task) // if online we can return ok because it will be verified anyway }).catch((err) => { - Logger.error(err, 'stock') + Logger.error(err, 'stock')() resolve(null) }) } else { @@ -71,7 +71,7 @@ const actions: ActionTree = { if (cartItem && event.result.code !== 'ENOTFOUND') { if (!event.result.is_in_stock) { if (!rootStore.state.config.stock.allowOutOfStockInCart) { - Logger.log('Removing product from cart' + event.product_sku, 'stock') + Logger.log('Removing product from cart' + event.product_sku, 'stock')() rootStore.commit('cart/' + types.CART_DEL_ITEM, { product: { sku: event.product_sku } }, {root: true}) } else { rootStore.dispatch('cart/updateItem', { product: { errors: { stock: i18n.t('Out of the stock!') }, sku: event.product_sku, is_in_stock: false } }) @@ -82,8 +82,8 @@ const actions: ActionTree = { Vue.prototype.$bus.$emit('cart-after-itemchanged', { item: cartItem }) } }) - Logger.debug('Stock quantity checked for ' + event.result.product_id + ', response time: ' + (event.transmited_at - event.created_at) + ' ms', 'stock') - Logger.debug(event, 'stock') + Logger.debug('Stock quantity checked for ' + event.result.product_id + ', response time: ' + (event.transmited_at - event.created_at) + ' ms', 'stock')() + Logger.debug(event, 'stock')() }, 500) } } diff --git a/core/modules/catalog/store/tax/actions.ts b/core/modules/catalog/store/tax/actions.ts index 576aaf3889..c304cc6a11 100644 --- a/core/modules/catalog/store/tax/actions.ts +++ b/core/modules/catalog/store/tax/actions.ts @@ -12,7 +12,7 @@ const actions: ActionTree = { */ list (context, { entityType = 'taxrule' }) { if (context.state.rules.length > 0) { - Logger.info('Tax rules served from local memory', 'tax') + Logger.info('Tax rules served from local memory', 'tax')() return new Promise((resolve, reject) => { resolve({ items: context.state.rules }) }) diff --git a/core/modules/catalog/store/tax/mutations.ts b/core/modules/catalog/store/tax/mutations.ts index 0c310cd9c7..8c95c05f0b 100644 --- a/core/modules/catalog/store/tax/mutations.ts +++ b/core/modules/catalog/store/tax/mutations.ts @@ -11,7 +11,7 @@ const mutations: MutationTree = { for (let tc of taxClasses.items) { // we store each product separately in cache to have offline acces for products/single method const cacheKey = entityKeyName('tc', tc.id) cache.setItem(cacheKey, tc).catch((err) => { - Logger.error('Cannot store cache for ' + cacheKey + ', ' + err) + Logger.error('Cannot store cache for ' + cacheKey + ', ' + err)() }) } state.rules = taxClasses.items // extract fields from ES _source diff --git a/core/modules/checkout/components/OrderReview.ts b/core/modules/checkout/components/OrderReview.ts index 3432b7d342..9d6ce4d919 100644 --- a/core/modules/checkout/components/OrderReview.ts +++ b/core/modules/checkout/components/OrderReview.ts @@ -57,7 +57,7 @@ export const OrderReview ={ } }).catch(err => { this.$bus.$emit('notification-progress-stop') - Logger.error(err, 'checkout') + Logger.error(err, 'checkout')() }) } } diff --git a/core/modules/checkout/store/checkout/actions.ts b/core/modules/checkout/store/checkout/actions.ts index 5d2679d1dd..854585781d 100644 --- a/core/modules/checkout/store/checkout/actions.ts +++ b/core/modules/checkout/store/checkout/actions.ts @@ -26,14 +26,14 @@ const actions: ActionTree = { }) } catch (e) { if (e.name === 'ValidationError') { - Logger.error('Internal validation error; Order entity is not compliant with the schema' + e.messages, 'checkout') + Logger.error('Internal validation error; Order entity is not compliant with the schema' + e.messages, 'checkout')() rootStore.dispatch('notification/spawnNotification', { type: 'error', message: i18n.t('Internal validation error. Please check if all required fields are filled in. Please contact us on contributors@vuestorefront.io'), action1: { label: i18n.t('OK') } }) } else { - Logger.error(e, 'checkout') + Logger.error(e, 'checkout')() } } }, diff --git a/core/modules/cms/store/block/actions.ts b/core/modules/cms/store/block/actions.ts index 1505275241..ed6f61b738 100644 --- a/core/modules/cms/store/block/actions.ts +++ b/core/modules/cms/store/block/actions.ts @@ -32,7 +32,7 @@ const actions: ActionTree = { return resp.items }) .catch(err => { - Logger.error(err, 'cms') + Logger.error(err, 'cms')() }) } else { return new Promise((resolve, reject) => { @@ -65,7 +65,7 @@ const actions: ActionTree = { return resp.items[0] }) .catch(err => { - Logger.error(err, 'cms') + Logger.error(err, 'cms')() }) } else { return new Promise((resolve, reject) => { diff --git a/core/modules/cms/store/hierarchy/actions.ts b/core/modules/cms/store/hierarchy/actions.ts index 30b5a15edf..ba2608081c 100644 --- a/core/modules/cms/store/hierarchy/actions.ts +++ b/core/modules/cms/store/hierarchy/actions.ts @@ -24,7 +24,7 @@ const actions: ActionTree = { } return quickSearchByQuery({ query, entityType, excludeFields, includeFields }).catch(err => { - Logger.error(err, 'cms') + Logger.error(err, 'cms')() }) } } diff --git a/core/modules/cms/store/page/actions.ts b/core/modules/cms/store/page/actions.ts index 81aeea6c63..ffcefad130 100644 --- a/core/modules/cms/store/page/actions.ts +++ b/core/modules/cms/store/page/actions.ts @@ -34,7 +34,7 @@ const actions: ActionTree = { return resp.items }) .catch(err => { - Logger.error(err, 'cms') + Logger.error(err, 'cms')() }) } else { return new Promise((resolve, reject) => { @@ -78,7 +78,7 @@ const actions: ActionTree = { let resp = context.state.items.find(p => p[key] === value) if (resp) { if (setCurrent) context.commit(types.CMS_PAGE_SET_CURRENT, resp) - resolve(resp) + resolve(resp) } else { cacheStorage.getItem(cmsPagesStorageKey, (err, storedItems) => { if (err) reject(err) diff --git a/core/modules/offline-order/components/CancelOrders.ts b/core/modules/offline-order/components/CancelOrders.ts index e048ca21bd..7110db06b6 100644 --- a/core/modules/offline-order/components/CancelOrders.ts +++ b/core/modules/offline-order/components/CancelOrders.ts @@ -18,8 +18,8 @@ export const CancelOrders = { ordersCollection.removeItem(id) } }).catch(err => { - Logger.error(err, 'offline-order') - Logger.log('Not transmitted orders have been deleted', 'offline-order') + Logger.error(err, 'offline-order')() + Logger.log('Not transmitted orders have been deleted', 'offline-order')() }) } } diff --git a/core/modules/offline-order/helpers/onNetworkStatusChange.ts b/core/modules/offline-order/helpers/onNetworkStatusChange.ts index 62b842dd05..a022b97a6f 100644 --- a/core/modules/offline-order/helpers/onNetworkStatusChange.ts +++ b/core/modules/offline-order/helpers/onNetworkStatusChange.ts @@ -8,7 +8,7 @@ import { currentStoreView } from '@vue-storefront/core/lib/multistore' import { Logger } from '@vue-storefront/core/lib/logger' export function onNetworkStatusChange (store) { - Logger.log('Are we online: ' + navigator.onLine, 'offline-order') + Logger.log('Are we online: ' + navigator.onLine, 'offline-order')() if (typeof navigator !== 'undefined' && navigator.onLine) { EventBus.$emit('sync/PROCESS_QUEUE', { config: store.state.config }) // process checkout queue @@ -31,7 +31,7 @@ export function onNetworkStatusChange (store) { ordersToConfirm.push(order) } }).catch(err => { - Logger.error(err, 'offline-order') + Logger.error(err, 'offline-order')() }) if (ordersToConfirm.length > 0) { diff --git a/core/modules/order/store/mutations.ts b/core/modules/order/store/mutations.ts index 65cdb0018c..f1e2817f73 100644 --- a/core/modules/order/store/mutations.ts +++ b/core/modules/order/store/mutations.ts @@ -19,11 +19,11 @@ const mutations: MutationTree = { order.updated_at = new Date() ordersCollection.setItem(orderId.toString(), order, (err, resp) => { - if (err) Logger.error(err, 'order') + if (err) Logger.error(err, 'order')() if (!order.transmited) { Vue.prototype.$bus.$emit('order/PROCESS_QUEUE', { config: rootStore.state.config }) // process checkout queue } - Logger.info('Order placed, orderId = ' + orderId, 'order') + Logger.info('Order placed, orderId = ' + orderId, 'order')() }).catch((reason) => { Logger.error(reason, 'order') // it doesn't work on SSR }) // populate cache diff --git a/core/modules/review/store/actions.ts b/core/modules/review/store/actions.ts index 9a9ade2131..2e59781ad3 100644 --- a/core/modules/review/store/actions.ts +++ b/core/modules/review/store/actions.ts @@ -40,7 +40,7 @@ const actions: ActionTree = { quickSearchByQuery({ query, start, size, entityType, sort, excludeFields, includeFields }).then((resp) => { context.commit(types.REVIEW_UPD_REVIEWS, resp) }).catch(err => { - Logger.error(err, 'review') + Logger.error(err, 'review')() }) }, diff --git a/core/modules/user/components/Login.ts b/core/modules/user/components/Login.ts index a97b70f217..8e890a2f64 100644 --- a/core/modules/user/components/Login.ts +++ b/core/modules/user/components/Login.ts @@ -27,7 +27,7 @@ export const Login = { this.close() } }).catch(err => { - Logger.error(err, 'user') + Logger.error(err, 'user')() // TODO Move to theme this.$bus.$emit('notification-progress-stop') }) diff --git a/core/modules/user/components/Register.ts b/core/modules/user/components/Register.ts index 4aed6b36a0..41caa69304 100644 --- a/core/modules/user/components/Register.ts +++ b/core/modules/user/components/Register.ts @@ -26,7 +26,7 @@ export const Register = { // TODO Move to theme this.$bus.$emit('notification-progress-start', i18n.t('Registering the account ...')) this.$store.dispatch('user/register', { email: this.email, password: this.password, firstname: this.firstName, lastname: this.lastName }).then((result) => { - Logger.debug(result, 'user') + Logger.debug(result, 'user')() // TODO Move to theme this.$bus.$emit('notification-progress-stop') if (result.code !== 200) { @@ -44,7 +44,7 @@ export const Register = { }).catch(err => { // TODO Move to theme this.$bus.$emit('notification-progress-stop') - Logger.error(err, 'user') + Logger.error(err, 'user')() }) } } diff --git a/core/modules/user/store/actions.ts b/core/modules/user/store/actions.ts index df86b3b615..694e29ef9d 100644 --- a/core/modules/user/store/actions.ts +++ b/core/modules/user/store/actions.ts @@ -17,7 +17,7 @@ const actions: ActionTree = { const cache = Vue.prototype.$db.usersCollection cache.getItem('current-token', (err, res) => { if (err) { - Logger.error(err, 'user') + Logger.error(err, 'user')() return } @@ -28,7 +28,7 @@ const actions: ActionTree = { if (rootStore.state.config.usePriceTiers) { Vue.prototype.$db.usersCollection.getItem('current-user', (err, userData) => { if (err) { - Logger.error(err, 'user') + Logger.error(err, 'user')() return } @@ -118,7 +118,7 @@ const actions: ActionTree = { const usersCollection = Vue.prototype.$db.usersCollection usersCollection.getItem('current-refresh-token', (err, refreshToken) => { if (err) { - Logger.error(err, 'user') + Logger.error(err, 'user')() } let url = rootStore.state.config.users.refresh_endpoint if (rootStore.state.config.storeViews.multistore) { @@ -175,7 +175,7 @@ const actions: ActionTree = { if (useCache === true) { // after login for example we shouldn't use cache to be sure we're loading currently logged in user cache.getItem('current-user', (err, res) => { if (err) { - Logger.error(err, 'user') + Logger.error(err, 'user')() return } @@ -187,7 +187,7 @@ const actions: ActionTree = { resolve(res) resolvedFromCache = true - Logger.log('Current user served from cache', 'user') + Logger.log('Current user served from cache', 'user')() } }) } @@ -311,7 +311,7 @@ const actions: ActionTree = { // TODO: Make it as an extension from users module return new Promise((resolve, reject) => { if (!context.state.token) { - Logger.debug('No User token, user unathorized', 'user') + Logger.debug('No User token, user unathorized', 'user')() return resolve(null) } const cache = Vue.prototype.$db.ordersHistoryCollection @@ -320,7 +320,7 @@ const actions: ActionTree = { if (useCache === true) { // after login for example we shouldn't use cache to be sure we're loading currently logged in user cache.getItem('orders-history', (err, res) => { if (err) { - Logger.error(err, 'user') + Logger.error(err, 'user')() return } @@ -330,7 +330,7 @@ const actions: ActionTree = { resolve(res) resolvedFromCache = true - Logger.log('Current user order history served from cache', 'user') + Logger.log('Current user order history served from cache', 'user')() } }) } diff --git a/core/modules/user/store/mutations.ts b/core/modules/user/store/mutations.ts index 5da39ddf06..8d71c0dfac 100644 --- a/core/modules/user/store/mutations.ts +++ b/core/modules/user/store/mutations.ts @@ -8,7 +8,7 @@ const mutations: MutationTree = { state.token = payload.newToken if (payload.meta && payload.meta.refreshToken) { state.refreshToken = payload.meta.refreshToken // store the refresh token - Logger.log('Refresh token is set to' + state.refreshToken, 'user') + Logger.log('Refresh token is set to' + state.refreshToken, 'user')() } }, [types.USER_START_SESSION] (state) { diff --git a/core/pages/Category.js b/core/pages/Category.js index 83c5970f2a..aba76a0315 100644 --- a/core/pages/Category.js +++ b/core/pages/Category.js @@ -67,7 +67,7 @@ export default { } }, preAsyncData ({ store, route }) { - Logger.log('preAsyncData query setup') + Logger.log('preAsyncData query setup')() store.dispatch('category/setSearchOptions', { populateAggregations: true, store: store, @@ -91,7 +91,7 @@ export default { filterValues: defaultFilters, // TODO: assign specific filters/ attribute codes dynamicaly to specific categories includeFields: store.state.config.entities.optimize && Vue.prototype.$isServer ? store.state.config.entities.attribute.includeFields : null }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }).then((attrs) => { store.dispatch('category/single', { key: store.state.config.products.useMagentoUrlKeys ? 'url_key' : 'slug', value: route.params.slug }).then((parentCategory) => { @@ -107,29 +107,29 @@ export default { EventBus.$emitFilter('category-after-load', { store: store, route: route }).then((results) => { return resolve() }).catch((err) => { - Logger.error(err) + Logger.error(err)() return resolve() }) }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }) } else { const err = new Error('Category query returned empty result') - Logger.error(err) + Logger.error(err)() reject(err) } }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }) }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }) }) }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }) }) diff --git a/core/pages/Checkout.js b/core/pages/Checkout.js index 527ad98e27..6f3776652a 100644 --- a/core/pages/Checkout.js +++ b/core/pages/Checkout.js @@ -72,7 +72,7 @@ export default { checkPromises.push(new Promise((resolve, reject) => { Vue.prototype.$db.syncTaskCollection.getItem(product.onlineStockCheckid, (err, item) => { if (err || !item) { - if (err) Logger.error(err) + if (err) Logger.error(err)() resolve(null) } else { product.stock = item.result @@ -145,7 +145,7 @@ export default { this.confirmation = payload.confirmation this.orderPlaced = true this.$store.dispatch('checkout/setThankYouPage', true) - Logger.debug(payload.order) + Logger.debug(payload.order)() }, onBeforeEdit (section) { this.activateSection(section) diff --git a/core/pages/CmsPage.js b/core/pages/CmsPage.js index 82e09745b0..1b6027dd50 100644 --- a/core/pages/CmsPage.js +++ b/core/pages/CmsPage.js @@ -22,7 +22,7 @@ export default { }).then(page => { resolve(page) }).catch(err => { - Logger.error(err) + Logger.error(err)() reject(err) }) }) diff --git a/core/pages/Error.js b/core/pages/Error.js index 80bddc717a..a71248b9dd 100644 --- a/core/pages/Error.js +++ b/core/pages/Error.js @@ -5,7 +5,7 @@ export default { name: 'Error', asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { - Logger.log('Calling asyncData for Error page ' + new Date()) + Logger.log('Calling asyncData for Error page ' + new Date())() if (context) { context.output.cacheTags.add(`error`) } diff --git a/core/pages/Home.js b/core/pages/Home.js index b241c71adb..fba85241e3 100644 --- a/core/pages/Home.js +++ b/core/pages/Home.js @@ -17,11 +17,11 @@ export default { }, async asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data if (context) context.output.cacheTags.add(`home`) - Logger.info('Calling asyncData in Home Page (core)') + Logger.info('Calling asyncData in Home Page (core)')() try { await EventBus.$emitFilter('home-after-load', { store: store, route: route }) } catch (e) { - Logger.error(e) + Logger.error(e)() throw e } }, diff --git a/core/pages/MyAccount.js b/core/pages/MyAccount.js index e1ad89a415..f4fc098a54 100644 --- a/core/pages/MyAccount.js +++ b/core/pages/MyAccount.js @@ -36,7 +36,7 @@ export default { this.$store.dispatch('user/update', { customer: updatedData }) } catch (err) { this.$bus.$emit('myAccount-before-remainInEditMode', this.$props.activeBlock) - Logger.error(err) + Logger.error(err)() } } } diff --git a/core/pages/PageNotFound.js b/core/pages/PageNotFound.js index fbf992050f..efee26f460 100644 --- a/core/pages/PageNotFound.js +++ b/core/pages/PageNotFound.js @@ -11,7 +11,7 @@ export default { mixins: [Composite], asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { - Logger.log('Entering asyncData for PageNotFound ' + new Date()) + Logger.log('Entering asyncData for PageNotFound ' + new Date())() if (context) context.output.cacheTags.add(`page-not-found`) let ourBestsellersQuery = prepareQuery({ queryConfig: 'bestSellers' }) store.dispatch('category/list', {}).then(categories => { @@ -25,7 +25,7 @@ export default { EventBus.$emitFilter('pagenotfound-after-load', { store: store, route: route }).then(results => { return resolve() }).catch(err => { - Logger.error(err) + Logger.error(err)() return resolve() }) } diff --git a/core/pages/Product.js b/core/pages/Product.js index fd21d1b2d9..24aaeebe1b 100644 --- a/core/pages/Product.js +++ b/core/pages/Product.js @@ -100,12 +100,12 @@ export default { this.$store.dispatch('recently-viewed/addItem', this.product) }).catch((err) => { this.loading = false - Logger.error(err) + Logger.error(err)() this.notifyOutStock() this.$router.back() }) } else { - Logger.error('Error with loading = true in Product.vue; Reload page') + Logger.error('Error with loading = true in Product.vue; Reload page')() } }, addToWishlist (product) { @@ -161,7 +161,7 @@ export default { }, onStateCheck () { if (this.parentProduct && this.parentProduct.id !== this.product.id) { - Logger.log('Redirecting to parent, configurable product', this.parentProduct.sku) + Logger.log('Redirecting to parent, configurable product', this.parentProduct.sku)() this.$router.replace({ name: 'product', params: { parentSku: this.parentProduct.sku, childSku: this.product.sku, slug: this.parentProduct.slug } }) } }, @@ -169,7 +169,7 @@ export default { if (product.sku === this.product.sku) { // join selected variant object to the store this.$store.dispatch('product/setCurrent', omit(product, ['name'])) - .catch(err => Logger.error({ + .catch(err => Logger.error({() info: 'Dispatch product/setCurrent in Product.vue', err })) @@ -201,7 +201,7 @@ export default { } this.notifyWrongAttributes() } - }).catch(err => Logger.error({ + }).catch(err => Logger.error({() info: 'Dispatch product/configure in Product.vue', err })) diff --git a/core/scripts/cache.js b/core/scripts/cache.js index c7794bca40..60920a4bff 100644 --- a/core/scripts/cache.js +++ b/core/scripts/cache.js @@ -10,9 +10,9 @@ if (config.server.useOutputCache) { redis: config.redis, defaultTimeout: config.server.outputCacheDefaultTtl // Expire records after a day (even if they weren't invalidated) }) - Logger.log('Redis cache set', config.redis) + Logger.log('Redis cache set', config.redis)() } else { - Logger.error('Output cache is disabled in the config') + Logger.error('Output cache is disabled in the config')() } program @@ -20,10 +20,10 @@ program .option('-t|--tag ', 'tag name, available tags: ' + config.server.availableCacheTags.join(', '), '*') .action((cmd) => { // TODO: add parallel processing if (!cmd.tag) { - Logger.error('error: tag must be specified') + Logger.error('error: tag must be specified')() process.exit(1) } else { - Logger.log(`Clear cache request for [${cmd.tag}]`) + Logger.log(`Clear cache request for [${cmd.tag}]`)() let tags = [] if (cmd.tag === '*') { tags = config.server.availableCacheTags @@ -36,17 +36,17 @@ program return tag.indexOf(t) === 0 })) { subPromises.push(cache.invalidate(tag).then(() => { - Logger.log(`Tags invalidated successfully for [${tag}]`) + Logger.log(`Tags invalidated successfully for [${tag}]`)() })) } else { - Logger.error(`Invalid tag name ${tag}`) + Logger.error(`Invalid tag name ${tag}`)() } }) Promise.all(subPromises).then(r => { - Logger.log(`All tags invalidated successfully [${cmd.tag}]`) + Logger.log(`All tags invalidated successfully [${cmd.tag}]`)() process.exit(0) }).catch(error => { - Logger.error(error) + Logger.error(error)() }) } }) diff --git a/core/scripts/resolvers/resolveGraphQL.js b/core/scripts/resolvers/resolveGraphQL.js index 00443d9d01..c8d23f9880 100644 --- a/core/scripts/resolvers/resolveGraphQL.js +++ b/core/scripts/resolvers/resolveGraphQL.js @@ -38,11 +38,11 @@ export const getApolloProvider = async () => { }, watchLoading (state, mod) { loading += mod - Logger.log('Global loading', loading, mod) + Logger.log('Global loading', loading, mod)() }, errorHandler (error) { - Logger.log('Global error handler') - Logger.error(error) + Logger.log('Global error handler')() + Logger.error(error)() } }) diff --git a/core/server-entry.ts b/core/server-entry.ts index 58e755cb25..1c111e401a 100755 --- a/core/server-entry.ts +++ b/core/server-entry.ts @@ -29,7 +29,7 @@ function _ssrHydrateSubcomponents (components, store, router, resolve, reject, a return Promise.resolve(null) } })).then(() => { - AsyncDataLoader.flush({ store, route: router.currentRoute, context: null } /*AsyncDataLoaderActionContext*/).then((r) => { + AsyncDataLoader.flush({ store, route: router.currentRoute, context: null } /*AsyncDataLoaderActionContext*/).then((r) => { if (buildTimeConfig.ssr.useInitialStateFilter) { context.state = omit(store.state, store.state.config.ssr.initialStateFilter) } else { @@ -87,7 +87,7 @@ export default async context => { }) if (Component.asyncData) { Component.asyncData({ store, route: router.currentRoute, context: context }).then((result) => { // always execute the asyncData() from the top most component first - Logger.debug('Top-most asyncData executed') + Logger.debug('Top-most asyncData executed')() _ssrHydrateSubcomponents(components, store, router, resolve, reject, app, context) }).catch((err) => { _commonErrorHandler(err, reject) diff --git a/core/service-worker/registration.js b/core/service-worker/registration.js index fa7b16dcb0..3665696034 100644 --- a/core/service-worker/registration.js +++ b/core/service-worker/registration.js @@ -5,23 +5,23 @@ import { Logger } from '@vue-storefront/core/lib/logger' if (process.env.NODE_ENV === 'production' || server.devServiceWorker) { register(`/service-worker.js`, { ready () { - Logger.log( + Logger.log(() 'App is being served from cache by a service worker.' ) }, cached () { - Logger.log('Content has been cached for offline use.') + Logger.log('Content has been cached for offline use.')() }, updated (registration) { - Logger.log('New content is available, please refresh.') + Logger.log('New content is available, please refresh.')() }, offline () { - Logger.log( + Logger.log(() 'No internet connection found. App is running in offline mode.' ) }, error (error) { - Logger.error('Error during service worker registration:', error) + Logger.error('Error during service worker registration:', error)() } }) } diff --git a/core/store/lib/storage.ts b/core/store/lib/storage.ts index 3ca56131aa..451a620662 100644 --- a/core/store/lib/storage.ts +++ b/core/store/lib/storage.ts @@ -52,7 +52,7 @@ class LocalForageCacheDriver { this._storageQuota = storageQuota if (this._storageQuota && !Vue.prototype.$isServer) { - const storageQuota = this._storageQuota + const storageQuota = this._storageQuota const iterateFnc = this.iterate.bind(this) const removeItemFnc = this.removeItem.bind(this) setInterval(() => { @@ -65,7 +65,7 @@ class LocalForageCacheDriver { const howManyItemsToRemove = 100 const keysPurged = [] iterateFnc((item, id, number) => { - if (number < howManyItemsToRemove) { + if (number < howManyItemsToRemove) { removeItemFnc(id) keysPurged.push(id) } @@ -124,7 +124,7 @@ class LocalForageCacheDriver { } else { this._localForageCollection = localForage.createInstance(existingConfig) } - Logger.log('DB recreated with', existingConfig, destVersionNumber) + Logger.log('DB recreated with', existingConfig, destVersionNumber)() } } } @@ -136,7 +136,7 @@ class LocalForageCacheDriver { const isCallbackCallable = (typeof callback !== 'undefined' && callback) let isResolved = false if (this._useLocalCacheByDefault && this._localCache[key]) { - // Logger.debug('Local cache fallback for GET', key) + // Logger.debug('Local cache fallback for GET', key)() return new Promise((resolve, reject) => { const value = typeof this._localCache[key] !== 'undefined' ? this._localCache[key] : null if (isCallbackCallable) callback(null, value) @@ -147,7 +147,7 @@ class LocalForageCacheDriver { if (!Vue.prototype.$isServer) { if (this.cacheErrorsCount[this._collectionName] >= DISABLE_PERSISTANCE_AFTER && this._useLocalCacheByDefault) { if (!this._persistenceErrorNotified) { - Logger.error('Persistent cache disabled becasue of previous errors [get]', key) + Logger.error('Persistent cache disabled becasue of previous errors [get]', key)() this._persistenceErrorNotified = true } return new Promise((resolve, reject) => { @@ -156,11 +156,11 @@ class LocalForageCacheDriver { }) } else { const startTime = new Date().getTime() - // Logger.debug('No local cache fallback for GET', key) + // Logger.debug('No local cache fallback for GET', key)() const promise = this._localForageCollection.ready().then(() => this._localForageCollection.getItem(key).then(result => { const endTime = new Date().getTime() if ((endTime - startTime) >= CACHE_TIMEOUT) { - Logger.error('Cache promise resolved after [ms]', key, (endTime - startTime)) + Logger.error('Cache promise resolved after [ms]' + key + (endTime - startTime))() } if (!this._localCache[key] && result) { this._localCache[key] = result // populate the local cache for the next call @@ -171,7 +171,7 @@ class LocalForageCacheDriver { } isResolved = true } else { - Logger.debug('Skipping return value as it was previously resolved') + Logger.debug('Skipping return value as it was previously resolved')() } return result }).catch(err => { @@ -179,7 +179,7 @@ class LocalForageCacheDriver { if (!isResolved) { if (isCallbackCallable) callback(null, typeof this._localCache[key] !== 'undefined' ? this._localCache[key] : null) } - Logger.error(err) + Logger.error(err)() isResolved = true })) @@ -211,7 +211,7 @@ class LocalForageCacheDriver { const isCallbackCallable = (typeof callback !== 'undefined' && callback) let globalIterationNumber = 1 if (this._useLocalCacheByDefault) { - // Logger.debug('Local cache iteration') + // Logger.debug('Local cache iteration')() for (const localKey in this._localCache) { if (isIteratorCallable) { iterator(this._localCache[localKey], localKey, globalIterationNumber) @@ -228,7 +228,7 @@ class LocalForageCacheDriver { iterator(value, key, globalIterationNumber) globalIterationNumber++ } else { - // Logger.debug('Skipping iteration key because local cache executed', key) + // Logger.debug('Skipping iteration key because local cache executed', key)() } } else { iterator(value, key, iterationNumber) @@ -239,7 +239,7 @@ class LocalForageCacheDriver { isResolved = true })).catch(err => { this._lastError = err - Logger.error(err) + Logger.error(err)() if (!isResolved) { isResolved = true if (isCallbackCallable) callback(err, null) @@ -297,7 +297,7 @@ class LocalForageCacheDriver { if (!Vue.prototype.$isServer) { if (this.cacheErrorsCount[this._collectionName] >= DISABLE_PERSISTANCE_AFTER_SAVE && this._useLocalCacheByDefault) { if (!this._persistenceErrorNotified) { - Logger.error('Persistent cache disabled becasue of previous errors [set]', key) + Logger.error('Persistent cache disabled becasue of previous errors [set]', key)() this._persistenceErrorNotified = true } return new Promise((resolve, reject) => { diff --git a/docs/guide/basics/ssr-cache.md b/docs/guide/basics/ssr-cache.md index 84c98cfb1c..44258afb7e 100644 --- a/docs/guide/basics/ssr-cache.md +++ b/docs/guide/basics/ssr-cache.md @@ -91,11 +91,11 @@ After doing so, please add the `asyncData` method to your page code assigning th asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data return new Promise((resolve, reject) => { if (context) context.output.cacheTags.add(`home`) - Logger.log('Entering asyncData for Home root ' + new Date()) + Logger.log('Entering asyncData for Home root ' + new Date())() EventBus.$emitFilter('home-after-load', { store: store, route: route }).then((results) => { return resolve() }).catch((err) => { - Logger.error(err) + Logger.error(err)() reject(err) }) }) diff --git a/docs/guide/core-themes/core-components.md b/docs/guide/core-themes/core-components.md index 586ee9cb7f..09a7e93230 100644 --- a/docs/guide/core-themes/core-components.md +++ b/docs/guide/core-themes/core-components.md @@ -64,7 +64,7 @@ Since core components are just plain JavaScript objects you can easly modify the ```js import YourCorePage from '@vue-storefront/core/pages/YourCorePage' -YourCorePage.methods.foo = function () { Logger.log('Overrided method foo') +YourCorePage.methods.foo = function () { Logger.log('Overrided method foo')() export default { ... diff --git a/docs/guide/integrations/payment-gateway.md b/docs/guide/integrations/payment-gateway.md index 13af569663..c07cb3fd07 100644 --- a/docs/guide/integrations/payment-gateway.md +++ b/docs/guide/integrations/payment-gateway.md @@ -111,11 +111,11 @@ api.cart.order(null, cartId, { "additional_data":orderData.addressInformation.payment_method_additional } }, isThisAuthOrder).then(result => { - logger.info(THREAD_ID, result) + logger.info(THREAD_ID, result)() if(job) job.progress(currentStep++, TOTAL_STEPS); - logger.info(THREAD_ID + '[OK] Order placed with ORDER ID', result); - logger.debug(THREAD_ID + result) + logger.info(THREAD_ID + '[OK] Order placed with ORDER ID', result);() + logger.debug(THREAD_ID + result)() redisClient.set("order$$id$$" + orderData.order_id, JSON.stringify( { platform_order_id: result, diff --git a/src/modules/google-analytics/hooks/beforeRegistration.ts b/src/modules/google-analytics/hooks/beforeRegistration.ts index fb9f4d0317..b746d62aee 100644 --- a/src/modules/google-analytics/hooks/beforeRegistration.ts +++ b/src/modules/google-analytics/hooks/beforeRegistration.ts @@ -12,7 +12,7 @@ export function beforeRegistration(Vue, config, store, isServer) { } }) } else { - Logger.warn( + Logger.warn(() 'Google Analytics extensions is not working. Ensure Google Analytics account ID is defined in config', 'GA' )() diff --git a/src/modules/index.ts b/src/modules/index.ts index 28cb2c9466..580045c92f 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -27,7 +27,7 @@ import { Magento2CMS } from './magento-2-cms' // const extendCartVuex = { // actions: { // load () { -// Logger.info('New load function') +// Logger.info('New load function')() // } // } // } @@ -35,15 +35,15 @@ import { Magento2CMS } from './magento-2-cms' // const cartExtend = { // key: 'cart', // afterRegistration: function(isServer, config) { -// Logger.info('New afterRegistration hook') +// Logger.info('New afterRegistration hook')() // }, // store: { modules: [{ key: 'cart', module: extendCartVuex }] }, // } - + // extendModule(cartExtend) /** - * Some of the modules are registered lazily only when components from module are appearing on current page. + * Some of the modules are registered lazily only when components from module are appearing on current page. * If you want to use this modules in pages without it's components you need to remember about registering module first * In VS 1.8 this modules will be semlessly lazyLoaded after proper action dispatch * - Wishlist diff --git a/src/modules/magento-2-cms/store/index.js b/src/modules/magento-2-cms/store/index.js index 4032fc47a5..447fae7fe9 100644 --- a/src/modules/magento-2-cms/store/index.js +++ b/src/modules/magento-2-cms/store/index.js @@ -36,8 +36,8 @@ const actions = { } }) .catch((err) => { - Logger.log(err) - Logger.error('You need to install a custom Magento module from Snow.dog to make the CMS magick happen. Please go to https://github.com/SnowdogApps/magento2-cms-api and follow the instructions') + Logger.log(err)() + Logger.error('You need to install a custom Magento module from Snow.dog to make the CMS magick happen. Please go to https://github.com/SnowdogApps/magento2-cms-api and follow the instructions')() }) } } diff --git a/src/modules/module-template/hooks/afterRegistration.ts b/src/modules/module-template/hooks/afterRegistration.ts index 25a148074a..f6b78b9787 100644 --- a/src/modules/module-template/hooks/afterRegistration.ts +++ b/src/modules/module-template/hooks/afterRegistration.ts @@ -2,5 +2,5 @@ import { Logger } from '@vue-storefront/core/lib/logger' // This function will be fired both on server and client side context after registering other parts of the module export function afterRegistration(Vue, config, store, isServer){ - if (!Vue.prototype.$isServer) Logger.info('This will be called after extension registration and only on client side') + if (!Vue.prototype.$isServer) Logger.info('This will be called after extension registration and only on client side')() } diff --git a/src/modules/module-template/router/afterEach.ts b/src/modules/module-template/router/afterEach.ts index 710e09b91e..f03539a395 100644 --- a/src/modules/module-template/router/afterEach.ts +++ b/src/modules/module-template/router/afterEach.ts @@ -1,8 +1,8 @@ -// This function will be executed after entering each route. +// This function will be executed after entering each route. // See https://router.vuejs.org/guide/advanced/navigation-guards.html#global-after-hooks import { Route } from 'vue-router' import { Logger } from '@vue-storefront/core/lib/logger' export function afterEach(to: Route, from: Route) { - Logger.info(`We have just entered ${to.name} from ${from.name}.`) + Logger.info(`We have just entered ${to.name} from ${from.name}.`)() } diff --git a/src/modules/module-template/router/beforeEach.ts b/src/modules/module-template/router/beforeEach.ts index e2a1480535..3ebb631780 100644 --- a/src/modules/module-template/router/beforeEach.ts +++ b/src/modules/module-template/router/beforeEach.ts @@ -1,10 +1,10 @@ -// This function will be executed before entering each route. +// This function will be executed before entering each route. // It's important to have 'next()'. It enables navigation to new route. // See https://router.vuejs.org/guide/advanced/navigation-guards.html#global-guards import { Route } from 'vue-router' import { Logger } from '@vue-storefront/core/lib/logger' export function beforeEach(to: Route, from: Route, next) { - Logger.info('We are going to visit' + to.name) + Logger.info('We are going to visit' + to.name)() next() } diff --git a/src/modules/module-template/store/plugin.ts b/src/modules/module-template/store/plugin.ts index 598ba8ee61..b3e3bd29ee 100644 --- a/src/modules/module-template/store/plugin.ts +++ b/src/modules/module-template/store/plugin.ts @@ -3,8 +3,8 @@ import { Logger } from '@vue-storefront/core/lib/logger' export function plugin (mutation, state) { if (types[mutation.type]) { - Logger.info('performed mutation from this store with type' + mutation.type) + Logger.info('performed mutation from this store with type' + mutation.type)() } else { - Logger.info('performed mutation from other store with type' + mutation.type) + Logger.info('performed mutation from other store with type' + mutation.type)() } } diff --git a/src/modules/promoted-offers/store/actions.ts b/src/modules/promoted-offers/store/actions.ts index 2db244926d..cd10471c32 100644 --- a/src/modules/promoted-offers/store/actions.ts +++ b/src/modules/promoted-offers/store/actions.ts @@ -10,7 +10,7 @@ const actions: ActionTree = { const promotedOffersModule = await import(/* webpackChunkName: "vsf-promoted-offers-[request]" */ `theme/resource/${promotedBannersResource}.json`) commit('updatePromotedOffers', promotedOffersModule) } catch (err) { - Logger.debug('Unable to load promotedOffers' + err) + Logger.debug('Unable to load promotedOffers' + err)() } }, async updateHeadImage ({commit, rootState}, data) { @@ -19,7 +19,7 @@ const actions: ActionTree = { const imageModule = await import(/* webpackChunkName: "vsf-head-img-[request]" */ `theme/resource/${mainImageResource}.json`) commit('SET_HEAD_IMAGE', imageModule.image) } catch (err) { - Logger.debug('Unable to load headImage' + err) + Logger.debug('Unable to load headImage' + err)() } } } diff --git a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts index 625f52fce7..f111fc273b 100644 --- a/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts +++ b/src/modules/sample-custom-entity-graphql/hooks/afterRegistration.ts @@ -10,7 +10,7 @@ const TEST_ENTITY_TYPE = 'testentity' export function afterRegistration (Vue, config, store, isServer) { Vue.$on('application-after-init', async () => { - Logger.debug('Example of custom entity graphql extension') + Logger.debug('Example of custom entity graphql extension')() // create graphQl searchAdapter let searchAdapter = await getSearchAdapter('graphql') @@ -57,7 +57,7 @@ export function afterRegistration (Vue, config, store, isServer) { // apply test search searchAdapter.search(Request).then((resp) => { // we're always trying to populate cache - when online const res = searchAdapter.entities[Request.type].resultPorcessor(resp, 0, 200) - Logger.log('Testentity response: ', res) + Logger.log('Testentity response: ', res)() }) }) } From cdb54ce974d4dc7f12de3cd7ab63fd13c6229022 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 17:42:28 +0100 Subject: [PATCH 7/8] Fix substitution --- core/modules/catalog/store/product/actions.ts | 4 ++-- core/pages/Product.js | 4 ++-- core/service-worker/registration.js | 4 ++-- src/modules/google-analytics/hooks/beforeRegistration.ts | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/core/modules/catalog/store/product/actions.ts b/core/modules/catalog/store/product/actions.ts index 7028e4d160..eef6178a59 100644 --- a/core/modules/catalog/store/product/actions.ts +++ b/core/modules/catalog/store/product/actions.ts @@ -141,7 +141,7 @@ const actions: ActionTree = { setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { Logger.error(err) }).then((asocProd) => {() + }).catch(err => { Logger.error(err) }).then((asocProd) => { if (asocProd) { pl.product = asocProd pl.product.qty = 1 @@ -173,7 +173,7 @@ const actions: ActionTree = { setCurrentProduct: false, selectDefaultVariant: false, skipCache: skipCache - }).catch(err => { Logger.error(err) }).then((asocProd) => {() + }).catch(err => { Logger.error(err) }).then((asocProd) => { if (asocProd) { pl.product = asocProd pl.product.qty = pl.qty diff --git a/core/pages/Product.js b/core/pages/Product.js index 24aaeebe1b..a0c8e93167 100644 --- a/core/pages/Product.js +++ b/core/pages/Product.js @@ -169,7 +169,7 @@ export default { if (product.sku === this.product.sku) { // join selected variant object to the store this.$store.dispatch('product/setCurrent', omit(product, ['name'])) - .catch(err => Logger.error({() + .catch(err => Logger.error({ info: 'Dispatch product/setCurrent in Product.vue', err })) @@ -201,7 +201,7 @@ export default { } this.notifyWrongAttributes() } - }).catch(err => Logger.error({() + }).catch(err => Logger.error({ info: 'Dispatch product/configure in Product.vue', err })) diff --git a/core/service-worker/registration.js b/core/service-worker/registration.js index 3665696034..0d74296127 100644 --- a/core/service-worker/registration.js +++ b/core/service-worker/registration.js @@ -5,7 +5,7 @@ import { Logger } from '@vue-storefront/core/lib/logger' if (process.env.NODE_ENV === 'production' || server.devServiceWorker) { register(`/service-worker.js`, { ready () { - Logger.log(() + Logger.log( 'App is being served from cache by a service worker.' ) }, @@ -16,7 +16,7 @@ if (process.env.NODE_ENV === 'production' || server.devServiceWorker) { Logger.log('New content is available, please refresh.')() }, offline () { - Logger.log(() + Logger.log( 'No internet connection found. App is running in offline mode.' ) }, diff --git a/src/modules/google-analytics/hooks/beforeRegistration.ts b/src/modules/google-analytics/hooks/beforeRegistration.ts index b746d62aee..fb9f4d0317 100644 --- a/src/modules/google-analytics/hooks/beforeRegistration.ts +++ b/src/modules/google-analytics/hooks/beforeRegistration.ts @@ -12,7 +12,7 @@ export function beforeRegistration(Vue, config, store, isServer) { } }) } else { - Logger.warn(() + Logger.warn( 'Google Analytics extensions is not working. Ensure Google Analytics account ID is defined in config', 'GA' )() From 4d69eb9f76b78ee84b77aa6bb0e00922032a4c86 Mon Sep 17 00:00:00 2001 From: Fabio Gollinucci Date: Fri, 1 Feb 2019 17:45:26 +0100 Subject: [PATCH 8/8] Fix object pass and debug color tag --- core/client-entry.ts | 2 +- core/lib/logger.ts | 2 +- core/lib/sync/task.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/client-entry.ts b/core/client-entry.ts index ecb591898f..c89803094c 100755 --- a/core/client-entry.ts +++ b/core/client-entry.ts @@ -172,7 +172,7 @@ const invokeClientEntry = async () => { }) .then(jsonResponse => { if (jsonResponse && jsonResponse.code === 200) { - Logger.info('Response for: ' + orderId + ' = ' + jsonResponse.result)() + Logger.info('Response for: ' + orderId + ' = ' + JSON.stringify(jsonResponse.result))() orderData.transmited = true orderData.transmited_at = new Date() ordersCollection.setItem(orderId.toString(), orderData) diff --git a/core/lib/logger.ts b/core/lib/logger.ts index 8b7b5c4f3b..22830e8d65 100644 --- a/core/lib/logger.ts +++ b/core/lib/logger.ts @@ -68,7 +68,7 @@ class Logger debug (message: string, tag: string = null, context: any = null) : () => void { if (!isServer && this.canPrint('debug')) { if (tag) { - return console.debug.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('white'), 'color: inherit', bgColorStyle('gray'), 'font-weight: normal', context); + return console.debug.bind(window.console, '%cVSF%c %c' + tag +'%c ' + message, bgColorStyle('grey'), 'color: inherit', bgColorStyle('gray'), 'font-weight: normal', context); } else { return console.debug.bind(window.console, '%cVSF%c ' + message, bgColorStyle('white'), 'font-weight: normal', context); } diff --git a/core/lib/sync/task.ts b/core/lib/sync/task.ts index f813782bcb..a1d7063940 100644 --- a/core/lib/sync/task.ts +++ b/core/lib/sync/task.ts @@ -126,7 +126,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar }) } } - Logger.debug('Response for: ' + task.task_id + ' = ' + jsonResponse.result, 'sync')() + Logger.debug('Response for: ' + task.task_id + ' = ' + JSON.stringify(jsonResponse.result), 'sync')() task.transmited = true task.transmited_at = new Date() task.result = jsonResponse.result