Skip to content

Commit

Permalink
Implemented: logger using vue logger plugin (#365)
Browse files Browse the repository at this point in the history
  • Loading branch information
amansinghbais committed Jan 8, 2024
1 parent c3350b1 commit 025604b
Show file tree
Hide file tree
Showing 20 changed files with 149 additions and 51 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"mitt": "^2.1.0",
"register-service-worker": "^1.7.1",
"vue": "^3.2.26",
"vue-logger-plugin": "^2.2.3",
"vue-router": "^4.0.12",
"vuex": "^4.0.1",
"vuex-persistedstate": "^4.0.0-beta.3"
Expand Down
3 changes: 2 additions & 1 deletion src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { mapGetters, useStore } from 'vuex';
import { initialise, resetConfig } from '@/adapter'
import { useRouter } from 'vue-router';
import { translate, useProductIdentificationStore } from "@hotwax/dxp-components";
import logger from '@/logger'
export default defineComponent({
name: 'App',
Expand Down Expand Up @@ -95,7 +96,7 @@ export default defineComponent({
if(this.userToken) {
// Get product identification from api using dxp-component
await useProductIdentificationStore().getIdentificationPref(this.currentEComStore?.productStoreId)
.catch((error) => console.error(error));
.catch((error) => logger.error(error));
}
},
unmounted() {
Expand Down
5 changes: 3 additions & 2 deletions src/components/EditPickerModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import { hasError } from '@/adapter'
import { translate } from '@hotwax/dxp-components'
import { UtilService } from "@/services/UtilService";
import { PicklistService } from "@/services/PicklistService";
import logger from "@/logger";
export default defineComponent({
name: "EditPickersModal",
Expand Down Expand Up @@ -151,7 +152,7 @@ export default defineComponent({
throw resp.data
}
} catch (err) {
console.error('Failed to fetch the pickers information or there are no pickers available', err)
logger.error('Failed to fetch the pickers information or there are no pickers available', err)
}
},
async confirmSave() {
Expand Down Expand Up @@ -191,7 +192,7 @@ export default defineComponent({
}
} catch (err) {
showToast(translate('Something went wrong, could not edit picker.'))
console.error('Something went wrong, could not edit picker')
logger.error('Something went wrong, could not edit picker')
}
},
closeModal() {
Expand Down
5 changes: 3 additions & 2 deletions src/components/Image.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

<script lang="ts">
import { defineComponent } from "vue";
import logger from "@/logger";
export default defineComponent({
name: "Image",
Expand Down Expand Up @@ -51,15 +52,15 @@ export default defineComponent({
this.checkIfImageExists(this.src).then(() => {
this.imageUrl = this.src;
}).catch(() => {
console.error("Image doesn't exist");
logger.error("Image doesn't exist");
})
} else {
// Image is from resource server, hence append to base resource url, check for existence and assign
const imageUrl = this.resourceUrl.concat(this.src)
this.checkIfImageExists(imageUrl).then(() => {
this.imageUrl = imageUrl;
}).catch(() => {
console.error("Image doesn't exist");
logger.error("Image doesn't exist");
})
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/components/NotificationPreferenceModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { showToast } from "@/utils";
import emitter from "@/event-bus"
import { generateTopicName } from "@/utils/firebase";
import { subscribeTopic, unsubscribeTopic } from '@/adapter'
import logger from "@/logger";
export default defineComponent({
name: "NotificationPreferenceModal",
Expand Down Expand Up @@ -134,7 +135,7 @@ export default defineComponent({
try {
await this.handleTopicSubscription()
} catch (error) {
console.error(error)
logger.error(error)
} finally {
emitter.emit("dismissLoader")
}
Expand Down
71 changes: 71 additions & 0 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { createLogger, StringifyObjectsHook } from 'vue-logger-plugin'

// TODO Implement logic to send logs to server
// https://github.com/dev-tavern/vue-logger-plugin#sample-custom-hook---leveraging-axios-to-send-logs-to-server

// https://github.com/dev-tavern/vue-logger-plugin#levels
// Log levels (one of: debug, info, warn, error, log)
// log <-- error <-- warn <-- info <-- debug
// (from left to right: least inclusive to most inclusive)
// const level = (process.env.VUE_APP_DEFAULT_LOG_LEVEL ? process.env.VUE_APP_DEFAULT_LOG_LEVEL : "error") as any;

// Using StringifyObjectsHook as the objects are references and values may change during the code execution
// https://github.com/dev-tavern/vue-logger-plugin#built-in-hooks
// StringifyObjectsHook Applies JSON.stringify on all objects provided as arguments to a logging method.
// StringifyAndParseObjectsHook Applies JSON.stringify and JSON.parse on all objects provided as arguments to a logging method.

// enabled vs consoleEnabled
// Setting enabled to false will disable all logger functionality (console output + hook invocations).
// Setting consoleEnabled to false will disable just the console output but will still invoke the hooks.

const logger = createLogger({
enabled: true,
beforeHooks: [ StringifyObjectsHook ]
});

function getStack(error: any) {
// Handling incompatibilities
// Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user.
// There may also be large incompatibilities between implementations and the behavior may change in the future.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
try {
return error.stack;
} catch (err) {
logger.warn("Error stack is not supported");
}
return error;
}

export default {
install(app: any, options: any) {

// We could pass error: any, instance: any, info: any
// TODO Use other variables to extract more information about the error
app.config.errorHandler = (error: any) => {
// TODO Improve code to add more information related to code failed
logger.error("Global handler:" + getStack(error));
}
const level = options.level ? options.level : "error"

logger.apply({
level
})

logger.install(app);
},
debug(...args: any): void {
logger.debug(...args)
},
info(...args: any): void {
logger.info(...args)
},
warn(...args: any): void {
logger.warn(...args)
},
error(...args: any): void {
logger.error(...args)
},
log(...args: any): void {
logger.log(...args)
}
}
4 changes: 4 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ import localeMessages from './locales';
import { login, logout, loader } from '@/utils/user';
import { addNotification, storeClientRegistrationToken } from '@/utils/firebase';
import { getConfig, getProductIdentificationPref, initialise, setProductIdentificationPref, setUserLocale } from '@/adapter';
import logger from './logger';

const app = createApp(App)
.use(IonicVue, {
mode: 'md'
})
.use(logger, {
level: process.env.VUE_APP_DEFAULT_LOG_LEVEL
})
.use(router)
.use(store)
.use(permissionPlugin, {
Expand Down
7 changes: 4 additions & 3 deletions src/services/OrderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import emitter from '@/event-bus';
import { translate } from '@hotwax/dxp-components';
import store from '@/store';
import { formatPhoneNumber, showToast } from '@/utils';
import logger from '@/logger';

const getOpenOrders = async (payload: any): Promise <any> => {
return api({
Expand Down Expand Up @@ -86,7 +87,7 @@ const rejectItem = async (payload: any): Promise<any> => {
showToast(translate('Something went wrong'));
}
} catch (error) {
console.error(error);
logger.error(error);
}
emitter.emit("dismissLoader");
return resp;
Expand Down Expand Up @@ -207,7 +208,7 @@ const printShippingLabelAndPackingSlip = async (shipmentIds: Array<string>): Pro

} catch (err) {
showToast(translate('Failed to print shipping label and packing slip'))
console.error("Failed to load shipping label and packing slip", err)
logger.error("Failed to load shipping label and packing slip", err)
}
}

Expand Down Expand Up @@ -253,7 +254,7 @@ const getShippingPhoneNumber = async (orderId: string): Promise<any> => {
throw resp.data
}
} catch (err) {
console.error('Failed to fetch customer phone number', err)
logger.error('Failed to fetch customer phone number', err)
}
return phoneNumber
}
Expand Down
25 changes: 13 additions & 12 deletions src/store/modules/order/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { translate } from "@hotwax/dxp-components";
import emitter from '@/event-bus'
import store from "@/store";
import { prepareOrderQuery } from "@/utils/solrHelper";
import logger from "@/logger";

const actions: ActionTree<OrderState , RootState> ={
async getOpenOrders({ commit, state }, payload) {
Expand Down Expand Up @@ -90,7 +91,7 @@ const actions: ActionTree<OrderState , RootState> ={
}
emitter.emit("dismissLoader");
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
}

Expand Down Expand Up @@ -199,7 +200,7 @@ const actions: ActionTree<OrderState , RootState> ={
throw resp.data;
}
} catch (err) {
console.error(err)
logger.error(err)
}

await dispatch('updateCurrent', { order: currentOrder })
Expand Down Expand Up @@ -287,7 +288,7 @@ const actions: ActionTree<OrderState , RootState> ={
}
emitter.emit("dismissLoader");
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
}

Expand Down Expand Up @@ -356,7 +357,7 @@ const actions: ActionTree<OrderState , RootState> ={
}
emitter.emit("dismissLoader");
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
}

Expand Down Expand Up @@ -400,7 +401,7 @@ const actions: ActionTree<OrderState , RootState> ={
}
emitter.emit("dismissLoader")
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
}

Expand Down Expand Up @@ -501,7 +502,7 @@ const actions: ActionTree<OrderState , RootState> ={
}
emitter.emit("dismissLoader")
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
}

Expand Down Expand Up @@ -627,7 +628,7 @@ const actions: ActionTree<OrderState , RootState> ={
showToast(translate("Orders Not Found"))
}
} catch (err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
} finally {
emitter.emit("dismissLoader")
Expand Down Expand Up @@ -712,7 +713,7 @@ const actions: ActionTree<OrderState , RootState> ={
showToast(translate("Orders Not Found"))
}
} catch (err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
} finally {
emitter.emit("dismissLoader")
Expand Down Expand Up @@ -799,7 +800,7 @@ const actions: ActionTree<OrderState , RootState> ={
showToast(translate("Orders Not Found"))
}
} catch(err) {
console.error(err)
logger.error(err)
showToast(translate("Something went wrong"))
} finally {
emitter.emit("dismissLoader")
Expand Down Expand Up @@ -837,7 +838,7 @@ const actions: ActionTree<OrderState , RootState> ={
throw resp.data
}
} catch (err) {
console.error('Failed to fetch order item rejection history', err)
logger.error('Failed to fetch order item rejection history', err)
}

commit(types.ORDER_ITEM_REJECTION_HISTORY_UPDATED, rejectionHistory)
Expand Down Expand Up @@ -893,7 +894,7 @@ const actions: ActionTree<OrderState , RootState> ={
throw resp.data
}
} catch (err) {
console.error("Error in fetching payment detail.", err);
logger.error("Error in fetching payment detail.", err);
}
},

Expand All @@ -907,7 +908,7 @@ const actions: ActionTree<OrderState , RootState> ={
contactNumber
}
} catch (err) {
console.error("Error in fetching customer phone number for current order", err);
logger.error("Error in fetching customer phone number for current order", err);
}
commit(types.ORDER_CURRENT_UPDATED, { order });
},
Expand Down
7 changes: 4 additions & 3 deletions src/store/modules/product/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { showToast } from '@/utils'
import { hasError } from '@/adapter'
import { translate } from '@hotwax/dxp-components'
import emitter from '@/event-bus'
import logger from "@/logger";


const actions: ActionTree<ProductState, RootState> = {
Expand Down Expand Up @@ -37,7 +38,7 @@ const actions: ActionTree<ProductState, RootState> = {
// Handled empty response in case of failed query
if (resp.data) commit(types.PRODUCT_ADD_TO_CACHED_MULTIPLE, { products });
} else {
console.error('Something went wrong')
logger.error('Something went wrong')
}
// TODO Handle specific error
return resp;
Expand Down Expand Up @@ -69,7 +70,7 @@ const actions: ActionTree<ProductState, RootState> = {
showToast(translate("Products not found"));
}
} catch(error){
console.error(error)
logger.error(error)
commit(types.PRODUCT_LIST_UPDATED, { products: [], total: 0, queryString: '' })
showToast(translate("Something went wrong"));
}
Expand Down Expand Up @@ -118,7 +119,7 @@ const actions: ActionTree<ProductState, RootState> = {
showToast(translate("Product not found"));
}
} catch(error){
console.error(error)
logger.error(error)
showToast(translate("Something went wrong"));
}
emitter.emit("dismissLoader");
Expand Down
Loading

0 comments on commit 025604b

Please sign in to comment.