Skip to content

Commit

Permalink
Merge pull request #2039 from filrak/vs-modules
Browse files Browse the repository at this point in the history
Remove stacktrace.js, refactored logger API
  • Loading branch information
filrak authored Nov 29, 2018
2 parents f31430e + a44b86c commit 6b12be0
Show file tree
Hide file tree
Showing 19 changed files with 68 additions and 151 deletions.
8 changes: 3 additions & 5 deletions core/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,11 @@ export function createApp (ssrContext, config): { app: Vue, router: any, store:

let registeredModules = []
enabledModules.forEach(m => registeredModules.push(m.register(store, router)))
Logger.info('VS Modules registration finished.', {
tag: 'module',
context: { label: 'Summary', value: {
Logger.info('VS Modules registration finished.', 'module', {
succesfulyRegistered: registeredModules.length + ' / ' + enabledModules.length,
registrationOrder: registeredModules
}}
})
}
)()


registerExtensions(extensions, app, router, store, config, ssrContext)
Expand Down
2 changes: 1 addition & 1 deletion core/compatibility/lib/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function registerExtensions (extensions, app, router, store, config, ssrC
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')
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)
}
}
Expand Down
123 changes: 34 additions & 89 deletions core/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,41 @@
import StackTrace from 'stacktrace-js'

const bgColorStyle = (color) => `color: white; background: ${color}; padding: 4px; font-weight: bold; font-size: 0.8em'`

class VueStorefrontLogger {
private mode: string;
constructor () {
this.mode = process.env.NODE_ENV
}
/**
* Inform about something that happened in the app (for example client/server/cache itneractions).
* Provide meaningful data into `context` for easier debugging
*/
public info (message: string, properties?: {
tag?: string
context?: { label: string, value: any }
}) : void {
if (this.mode !== 'production' && typeof window !== 'undefined') {
StackTrace.get().then(trace => {
trace.shift() // remove unnecessary stack frame to logger
if (properties && properties.tag) {
console.groupCollapsed('%cVSF%c %c' + properties.tag +'%c ' + message,
bgColorStyle('green'), 'color: inherit', bgColorStyle('gray'), 'color: inherit')
} else {
console.groupCollapsed('%cVSF%c ' + message,
bgColorStyle('green'), 'color: inherit')
}
if (trace.length > 1) {
console.log('%cSource:%c ' + 'webpack:///.'+trace[0].fileName.substring(10) + ':' + trace[0].lineNumber, 'font-weight: bold', 'font-weight: normal')
console.log('%cStack trace:', 'font-weight: bold', trace)
}
if (properties && properties.context) {
console.log('%c' + properties.context.label + ' ', 'font-weight: bold', properties.context.value)
}
console.groupEnd()
})
const Logger = {
info : function (message, tag = null, context = null) {
if (typeof window !== 'undefined') {
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 });
} else {
return console.log.bind(window.console, '%cVSF%c ' + message, bgColorStyle('green'), 'font-weight: bold', { context });
}
} else {
return function (a, b) {}
}
}

/**
* Warn develoeprs about things that may cause some problems
* Provide meaningful data into `context` for easier debugging
* */
public warn (message: string, properties?: {
tag?: string
context?: { label: string, value: any }
}) : void {
if (this.mode !== 'production' && typeof window !== 'undefined') {
StackTrace.get().then(trace => {
trace.shift() // remove unnecessary stack frame to logger
if (properties && properties.tag) {
console.groupCollapsed('%cVSF%c %c' + properties.tag +'%c ' + message,
bgColorStyle('#ff6600'), 'color: inherit', bgColorStyle('gray'), 'color: #ff6600')
} else {
console.groupCollapsed('%cVSF%c ' + message,
bgColorStyle('#ff6600'), 'color: inherit')
}
if (trace.length > 1) {
console.log('%cSource:%c ' + 'webpack:///.'+trace[0].fileName.substring(10) + ':' + trace[0].lineNumber, 'font-weight: bold', 'font-weight: normal')
console.log('%cStack trace:', 'font-weight: bold', trace)
}
if (properties && properties.context) {
console.log('%c' + properties.context.label + ' ', 'font-weight: bold', properties.context.value)
}
console.groupEnd()
})
},
warn: function (message, tag = null, context = null) {
if (typeof window !== 'undefined') {
if (tag) {
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 });
}
} else {
return function (a, b) {}
}
}
public error (message: string, properties?: {
tag?: string
context?: { label: string, value: any }
}) : void {
if (this.mode !== 'production' && typeof window !== 'undefined') {
StackTrace.get().then(trace => {
trace.shift() // remove unnecessary stack frame to logger
if (properties && properties.tag) {
console.groupCollapsed('%cVSF%c %c' + properties.tag +'%c ' + message,
bgColorStyle('red'), 'color: inherit', bgColorStyle('gray'), 'color: red')
} else {
console.groupCollapsed('%cVSF%c ' + message,
bgColorStyle('red'), 'color: inherit')
}
if (trace.length > 1) {
console.log('%cSource:%c ' + 'webpack:///.'+trace[0].fileName.substring(10) + ':' + trace[0].lineNumber, 'font-weight: bold', 'font-weight: normal')
console.log('%cStack trace:', 'font-weight: bold', trace)
}
if (properties && properties.context) {
console.log('%c' + properties.context.label + ' ', 'font-weight: bold', properties.context.value)
}
console.groupEnd()
})
},
error: function (message, tag = null, context = null) {
if (typeof window !== 'undefined') {
if (tag) {
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 });
}
} else {
return function (a, b) {}
}
}
}

export const Logger = new VueStorefrontLogger()
const bgColorStyle = (color) => `color: white; background: ${color}; padding: 4px; font-weight: bold; font-size: 0.8em'`

export { Logger }
4 changes: 2 additions & 2 deletions core/lib/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ export class VueStorefrontModule {
public extend (extendedConfig: VueStorefrontModule) {
const key = this._c.key
this._c = merge(this._c, extendedConfig.config)
Logger.info('Module "' + key + '" has been succesfully extended.', { tag: 'module'})
Logger.info('Module "' + key + '" has been succesfully extended.', 'module')()
}

public register (storeInstance, routerInstance): VueStorefrontModuleConfig | void {
let isUnique = true
if ( this._c.store) {
this._c.store.modules.forEach(store => {
if (VueStorefrontModule._doesStoreAlreadyExists(store.key)) {
Logger.error('Error during "' + this._c.key + '" module registration! Store with key "' + store.key + '" already exists!', { tag: 'module'})
Logger.error('Error during "' + this._c.key + '" module registration! Store with key "' + store.key + '" already exists!', 'module')()
isUnique = false
}
})
Expand Down
10 changes: 2 additions & 8 deletions core/lib/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import { currentStoreView } from '@vue-storefront/store/lib/multistore'
function queue (task) {
const tasksCollection = Vue.prototype.$db.syncTaskCollection
task = _prepareTask(task)
Logger.info('New sync task [queue] ' + task.url, { tag: 'sync', context: {
label: 'Task',
value: 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)
Expand All @@ -32,10 +29,7 @@ function execute (task) { // not offline task
const storeView = currentStoreView()
const dbNamePrefix = storeView.storeCode ? storeView.storeCode + '-' : ''
task = _prepareTask(task)
Logger.info('New sync task [execute] ' + task.url, { tag: 'sync', context: {
label: 'Task',
value: task
}})
// Logger.info('New sync task [execute] ' + task.url, 'sync', task)()
const usersCollection = new UniversalStorage(localForage.createInstance({
name: (rootStore.state.config.cart.multisiteCommonCart ? '' : dbNamePrefix) + 'shop',
storeName: 'user',
Expand Down
2 changes: 1 addition & 1 deletion core/lib/sync/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function _internalExecute (resolve, reject, task: Task, currentToken, currentCar
url = adjustMultistoreApiUrl(url)
}
let silentMode = false
Logger.info('Executing sync task ' + url, { tag: 'sync', context: { label: 'Task', value: task }})
Logger.info('Executing sync task ' + url, 'sync', task)()
return fetch(url, task.payload).then((response) => {
const contentType = response.headers.get('content-type')
if (contentType && contentType.includes('application/json')) {
Expand Down
22 changes: 9 additions & 13 deletions core/modules/cart/store/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,11 @@ const actions: ActionTree<CartState, RootState> = {
// TODO: if token is null create cart server side and store the token!
if (token) { // previously set token
commit(types.CART_LOAD_CART_SERVER_TOKEN, token)
Logger.info('Cart token received from cache.', { tag: 'cache', context: { label: 'Cart token', value: token} })
Logger.info('Pulling cart from server.', { tag: 'cart' })
Logger.info('Cart token received from cache.', 'cache', token)()
Logger.info('Pulling cart from server.','cart')()
context.dispatch('serverPull', { forceClientState: false, dryRun: !rootStore.state.config.cart.server_merge_by_default })
} else {
Logger.info('Creating server cart token', { tag: 'cart' })
Logger.info('Creating server cart token', 'cart')()
context.dispatch('serverCreate', { guestCart: false })
}
})
Expand Down Expand Up @@ -485,7 +485,7 @@ const actions: ActionTree<CartState, RootState> = {
servercartAfterCreated (context, event) {
const cartToken = event.result
if (event.resultCode === 200) {
Logger.info('Server cart token created: ' + cartToken, { tag: 'cart' })
Logger.info('Server cart token created.', 'cart', cartToken)()
rootStore.commit(types.SN_CART + '/' + types.CART_LOAD_CART_SERVER_TOKEN, cartToken)
rootStore.dispatch('cart/serverPull', { forceClientState: false, dryRun: !rootStore.state.config.cart.server_merge_by_default }, { root: true })
} else {
Expand All @@ -503,11 +503,7 @@ const actions: ActionTree<CartState, RootState> = {
servercartAfterTotals (context, event) {
if (event.resultCode === 200) {
const totalsObj = event.result.totals ? event.result.totals : event.result
Logger.info('Overriding server totals. ', { tag: 'cart', context: {
label: 'Totals',
value: totalsObj
}})

Logger.info('Overriding server totals. ', 'cart', totalsObj)()
let itemsAfterTotal = {}
let platformTotalSegments = totalsObj.total_segments
for (let item of totalsObj.items) {
Expand Down Expand Up @@ -535,7 +531,7 @@ const actions: ActionTree<CartState, RootState> = {
})

if (!serverItem) {
Logger.warn('No server item with sku ' + clientItem.sku + ' on stock.', { tag: '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) {
rootStore.dispatch('cart/serverUpdateItem', {
Expand Down Expand Up @@ -563,7 +559,7 @@ const actions: ActionTree<CartState, RootState> = {
serverCartUpdateRequired = true
}
} else {
Logger.info('Server and client item with SKU ' + clientItem.sku + ' synced. Updating cart.', { tag: 'cart' })
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 })
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 })
Expand Down Expand Up @@ -615,7 +611,7 @@ const actions: ActionTree<CartState, RootState> = {
}
}
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 ', { tag: 'cart', context: { label: 'Differences: ', value: diffLog } })
Logger.info('Client/Server cart synchronised ', 'cart', diffLog)()
} else {
console.error(event.result) // override with guest cart
if (rootStore.state.cart.bypassCount < MAX_BYPASS_COUNT) {
Expand Down Expand Up @@ -643,7 +639,7 @@ const actions: ActionTree<CartState, RootState> = {
}
})
} else {
Logger.warn('Removing product from cart', { tag: 'cart', context: { label: 'Original cart item', value: originalCartItem }})
Logger.warn('Removing product from cart', 'cart', originalCartItem)()
rootStore.commit('cart/' + types.CART_DEL_NON_CONFIRMED_ITEM, { product: originalCartItem }, {root: true})
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion core/modules/catalog/store/product/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ const actions: ActionTree<ProductState, RootState> = {
} else {
context.state.productLoadPromise = new Promise((resolve, reject) => {
context.state.productLoadStart = Date.now()
Logger.info('Fetching product data asynchronously' , { tag: 'product', context: { label: 'Parent and child SKUs', value: {parentSku, childSku} }})
Logger.info('Fetching product data asynchronously' , 'product', {parentSku, childSku})()
Vue.prototype.$bus.$emit('product-before-load', { store: rootStore, route: route })
context.dispatch('reset').then(() => {
rootStore.dispatch('attribute/list', { // load attributes to be shown on the product details
Expand Down
2 changes: 1 addition & 1 deletion core/modules/compare/store/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const actions: ActionTree<CompareState, RootState> = {
cacheStorage.getItem('current-compare', (err, storedItems) => {
if (err) throw new Error(err)
commit(types.COMPARE_LOAD_COMPARE, storedItems)
Logger.info('Compare state loaded from browser cache: ', { tag: 'cache', context: { label: 'Loaded data', value: storedItems } })
Logger.info('Compare state loaded from browser cache: ', 'cache', storedItems)()
})
},
addItem ({commit}, product) {
Expand Down
4 changes: 2 additions & 2 deletions core/modules/user/store/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ const actions: ActionTree<UserState, RootState> = {
me (context, { refresh = true, useCache = true }) {
return new Promise((resolve, reject) => {
if (!context.state.token) {
Logger.info('No User token, user unauthorized', { tag: 'user'})
Logger.warn('No User token, user unauthorized', 'user')()
return resolve(null)
}
const cache = Vue.prototype.$db.usersCollection
Expand Down Expand Up @@ -389,7 +389,7 @@ const actions: ActionTree<UserState, RootState> = {
}
},
sessionAfterAuthorized (context, event) {
Logger.info('User session authorised ', { tag: 'user' })
Logger.info('User session authorised ', 'user')()
rootStore.dispatch('user/me', { refresh: navigator.onLine }, { root: true }).then((us) => {}) // this will load user cart
rootStore.dispatch('user/getOrdersHistory', { refresh: navigator.onLine }, { root: true }).then((us) => {})
}
Expand Down
2 changes: 1 addition & 1 deletion core/modules/wishlist/store/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const actions: ActionTree<WishlistState, RootState> = {
cacheStorage.getItem('current-wishlist', (err, storedItems) => {
if (err) throw new Error(err)
commit(types.WISH_LOAD_WISH, storedItems)
Logger.info('Wishlist state loaded from browser cache: ', { tag: 'cache', context: { label: 'Loaded data', value: storedItems } })
Logger.info('Wishlist state loaded from browser cache. ', 'cache', storedItems)()
})
},
addItem ({ commit }, product) {
Expand Down
2 changes: 1 addition & 1 deletion core/pages/Category.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default {
},
asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data
return new Promise((resolve, reject) => {
Logger.info('Entering asyncData in Category Page (core)')
Logger.info('Entering asyncData in Category Page (core)')()
if (context) context.output.cacheTags.add(`category`)
const defaultFilters = store.state.config.products.defaultFilters
store.dispatch('category/list', { includeFields: store.state.config.entities.optimize && Vue.prototype.$isServer ? store.state.config.entities.category.includeFields : null }).then((categories) => {
Expand Down
2 changes: 1 addition & 1 deletion core/pages/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default {
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.info('Calling asyncData in Home Page (core)')
Logger.info('Calling asyncData in Home Page (core)')()
EventBus.$emitFilter('home-after-load', { store: store, route: route }).then((results) => {
return resolve()
}).catch((err) => {
Expand Down
Loading

0 comments on commit 6b12be0

Please sign in to comment.