feat(#27): Set up consola logger, make use of log levels in backend and frontend

This commit is contained in:
2025-12-24 10:26:22 +01:00
parent 805c66bc4f
commit 7f7852a66a
36 changed files with 312 additions and 141 deletions

View File

@@ -91,9 +91,10 @@ const emit = defineEmits<{
const commentStore = useCommentStore()
const { load: loadComments } = commentStore
const { comments } = storeToRefs(commentStore)
const logger = useLogger().withTag('FormEngine')
if (props.applicationFormId) {
console.log('Loading comments for application form:', props.applicationFormId)
logger.debug('Loading comments for application form:', props.applicationFormId)
await loadComments(props.applicationFormId)
}

View File

@@ -1,14 +1,16 @@
import type { ApplicationFormDto, PagedApplicationFormDto, FormElementDto } from '~~/.api-client'
import { useApplicationFormApi } from './useApplicationFormApi'
import { useLogger } from '../useLogger'
export function useApplicationForm() {
const applicationFormApi = useApplicationFormApi()
const logger = useLogger().withTag('applicationForm')
async function createApplicationForm(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
try {
return await applicationFormApi.createApplicationForm(applicationFormDto)
} catch (e: unknown) {
console.error('Failed creating application form:', e)
logger.error('Failed creating application form:', e)
return Promise.reject(e)
}
}
@@ -17,7 +19,7 @@ export function useApplicationForm() {
try {
return await applicationFormApi.getAllApplicationForms(organizationId)
} catch (e: unknown) {
console.error('Failed retrieving application forms:', e, JSON.stringify(e))
logger.error('Failed retrieving application forms:', e)
return Promise.reject(e)
}
}
@@ -26,7 +28,7 @@ export function useApplicationForm() {
try {
return await applicationFormApi.getApplicationFormById(id)
} catch (e: unknown) {
console.error(`Failed retrieving application form with ID ${id}:`, e)
logger.error(`Failed retrieving application form with ID ${id}:`, e)
return Promise.reject(e)
}
}
@@ -39,11 +41,11 @@ export function useApplicationForm() {
return Promise.reject(new Error('ID or application form DTO missing'))
}
console.log('Updating application form with ID:', id, applicationFormDto)
logger.debug('Updating application form with ID:', id, applicationFormDto)
try {
return await applicationFormApi.updateApplicationForm(id, applicationFormDto)
} catch (e: unknown) {
console.error(`Failed updating application form with ID ${id}:`, e)
logger.error(`Failed updating application form with ID ${id}:`, e)
return Promise.reject(e)
}
}
@@ -52,7 +54,7 @@ export function useApplicationForm() {
try {
return await applicationFormApi.deleteApplicationFormById(id)
} catch (e: unknown) {
console.error(`Failed deleting application form with ID ${id}:`, e)
logger.error(`Failed deleting application form with ID ${id}:`, e)
return Promise.reject(e)
}
}
@@ -65,7 +67,7 @@ export function useApplicationForm() {
try {
return await applicationFormApi.submitApplicationForm(id)
} catch (e: unknown) {
console.error(`Failed submitting application form with ID ${id}:`, e)
logger.error(`Failed submitting application form with ID ${id}:`, e)
return Promise.reject(e)
}
}
@@ -88,7 +90,7 @@ export function useApplicationForm() {
position
)
} catch (e: unknown) {
console.error(`Failed adding form element to subsection ${subsectionId}:`, e)
logger.error(`Failed adding form element to subsection ${subsectionId}:`, e)
return Promise.reject(e)
}
}

View File

@@ -1,10 +1,12 @@
import { type ApplicationFormDto, type PagedApplicationFormDto, ResponseError } from '~~/.api-client'
import { useApplicationFormTemplateApi } from './useApplicationFormTemplateApi'
import { useLogger } from '../useLogger'
const currentApplicationForm: Ref<ApplicationFormDto | undefined> = ref()
export async function useApplicationFormTemplate() {
const applicationFormApi = await useApplicationFormTemplateApi()
const logger = useLogger().withTag('applicationFormTemplate')
async function createApplicationFormTemplate(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
try {
@@ -12,9 +14,9 @@ export async function useApplicationFormTemplate() {
return currentApplicationForm.value
} catch (e: unknown) {
if (e instanceof ResponseError) {
console.error('Failed creating application form:', e.response)
logger.error('Failed creating application form:', e.response)
} else {
console.error('Failed creating application form:', e)
logger.error('Failed creating application form:', e)
}
return Promise.reject(e)
}
@@ -25,9 +27,9 @@ export async function useApplicationFormTemplate() {
return await applicationFormApi.getAllApplicationFormTemplates()
} catch (e: unknown) {
if (e instanceof ResponseError) {
console.error('Failed retrieving application forms:', e.response)
logger.error('Failed retrieving application forms:', e.response)
} else {
console.error('Failed retrieving application forms:', e)
logger.error('Failed retrieving application forms:', e)
}
return Promise.reject(e)
}
@@ -38,9 +40,9 @@ export async function useApplicationFormTemplate() {
return await applicationFormApi.getApplicationFormTemplateById(id)
} catch (e: unknown) {
if (e instanceof ResponseError) {
console.error(`Failed retrieving application form with ID ${id}:`, e.response)
logger.error(`Failed retrieving application form with ID ${id}:`, e.response)
} else {
console.error(`Failed retrieving application form with ID ${id}:`, e)
logger.error(`Failed retrieving application form with ID ${id}:`, e)
}
return Promise.reject(e)
}
@@ -59,9 +61,9 @@ export async function useApplicationFormTemplate() {
return currentApplicationForm.value
} catch (e: unknown) {
if (e instanceof ResponseError) {
console.error(`Failed updating application form with ID ${id}:`, e.response)
logger.error(`Failed updating application form with ID ${id}:`, e.response)
} else {
console.error(`Failed updating application form with ID ${id}:`, e)
logger.error(`Failed updating application form with ID ${id}:`, e)
}
return Promise.reject(e)
}
@@ -72,9 +74,9 @@ export async function useApplicationFormTemplate() {
return await applicationFormApi.deleteApplicationFormTemplateById(id)
} catch (e: unknown) {
if (e instanceof ResponseError) {
console.error(`Failed deleting application form with ID ${id}:`, e.response)
logger.error(`Failed deleting application form with ID ${id}:`, e.response)
} else {
console.error(`Failed deleting application form with ID ${id}:`, e)
logger.error(`Failed deleting application form with ID ${id}:`, e)
}
return Promise.reject(e)
}

View File

@@ -1,14 +1,16 @@
import type { ApplicationFormVersionDto, ApplicationFormVersionListItemDto, ApplicationFormDto } from '~~/.api-client'
import { useApplicationFormVersionApi } from '~/composables'
import { useLogger } from '../useLogger'
export function useApplicationFormVersion() {
const versionApi = useApplicationFormVersionApi()
const logger = useLogger().withTag('applicationFormVersion')
async function getVersions(applicationFormId: string): Promise<ApplicationFormVersionListItemDto[]> {
try {
return await versionApi.getVersions(applicationFormId)
} catch (e: unknown) {
console.error(`Failed retrieving versions for application form ${applicationFormId}:`, e)
logger.error(`Failed retrieving versions for application form ${applicationFormId}:`, e)
return Promise.reject(e)
}
}
@@ -17,7 +19,7 @@ export function useApplicationFormVersion() {
try {
return await versionApi.getVersion(applicationFormId, versionNumber)
} catch (e: unknown) {
console.error(`Failed retrieving version ${versionNumber} for application form ${applicationFormId}:`, e)
logger.error(`Failed retrieving version ${versionNumber} for application form ${applicationFormId}:`, e)
return Promise.reject(e)
}
}
@@ -30,7 +32,7 @@ export function useApplicationFormVersion() {
try {
return await versionApi.restoreVersion(applicationFormId, versionNumber)
} catch (e: unknown) {
console.error(`Failed restoring version ${versionNumber} for application form ${applicationFormId}:`, e)
logger.error(`Failed restoring version ${versionNumber} for application form ${applicationFormId}:`, e)
return Promise.reject(e)
}
}

View File

@@ -1,6 +1,7 @@
import type { CreateCommentDto, CommentDto } from '~~/.api-client'
import { useCommentStore } from '~~/stores/useCommentStore'
import { useUserStore } from '~~/stores/useUserStore'
import { useLogger } from '../useLogger'
export function useCommentTextarea(applicationFormId: string) {
const commentStore = useCommentStore()
@@ -11,6 +12,8 @@ export function useCommentTextarea(applicationFormId: string) {
const currentEditedComment = ref<CommentDto | null>(null)
const commentTextAreaValue = ref('')
const toast = useToast()
const { t: $t } = useI18n()
const logger = useLogger().withTag('commentTextarea')
async function submitComment(formElementId: string) {
const newCommentDto: CreateCommentDto = {
@@ -19,10 +22,10 @@ export function useCommentTextarea(applicationFormId: string) {
try {
await createComment(applicationFormId, formElementId, newCommentDto)
commentTextAreaValue.value = ''
toast.add({ title: 'Comment created successfully', color: 'success' })
toast.add({ title: $t('comments.created'), color: 'success' })
} catch (e) {
toast.add({ title: 'Error creating comment', color: 'error' })
console.error('Error creating comment:', e)
toast.add({ title: $t('comments.createError'), color: 'error' })
logger.error('Error creating comment:', e)
}
}
@@ -34,10 +37,10 @@ export function useCommentTextarea(applicationFormId: string) {
commentTextAreaValue.value = ''
currentEditedComment.value = null
isEditingComment.value = false
toast.add({ title: 'Comment updated successfully', color: 'success' })
toast.add({ title: $t('comments.updated'), color: 'success' })
} catch (e) {
toast.add({ title: 'Error updating comment', color: 'error' })
console.error('Error updating comment:', e)
toast.add({ title: $t('comments.updateError'), color: 'error' })
logger.error('Error updating comment:', e)
}
}

View File

@@ -2,6 +2,8 @@ import type { NotificationDto } from '~~/.api-client'
import { useUserStore } from '~~/stores/useUserStore'
export const useNotification = () => {
const logger = useLogger().withTag('notification')
const {
getNotifications,
getUnreadNotifications,
@@ -22,7 +24,7 @@ export const useNotification = () => {
const fetchNotifications = async (page: number = 0, size: number = 20) => {
if (!organizationId.value) {
console.warn('No organization selected')
logger.warn('No organization selected')
return
}
isLoading.value = true
@@ -31,7 +33,7 @@ export const useNotification = () => {
notifications.value = response.content || []
return response
} catch (error) {
console.error('Failed to fetch notifications:', error)
logger.error('Failed to fetch notifications:', error)
throw error
} finally {
isLoading.value = false
@@ -40,7 +42,7 @@ export const useNotification = () => {
const fetchUnreadNotifications = async () => {
if (!organizationId.value) {
console.warn('No organization selected')
logger.warn('No organization selected')
return
}
try {
@@ -48,14 +50,14 @@ export const useNotification = () => {
unreadNotifications.value = response || []
return response
} catch (error) {
console.error('Failed to fetch unread notifications:', error)
logger.error('Failed to fetch unread notifications:', error)
throw error
}
}
const fetchUnreadCount = async () => {
if (!userId.value || !organizationId.value) {
console.warn('No user or organization selected')
logger.warn('No user or organization selected')
return
}
try {
@@ -63,14 +65,14 @@ export const useNotification = () => {
unreadCount.value = count || 0
return count
} catch (error) {
console.error('Failed to fetch unread count:', error)
logger.error('Failed to fetch unread count:', error)
throw error
}
}
const markAllAsRead = async () => {
if (!organizationId.value) {
console.warn('No organization selected')
logger.warn('No organization selected')
return
}
try {
@@ -79,14 +81,14 @@ export const useNotification = () => {
unreadNotifications.value = []
notifications.value = notifications.value.map((n) => ({ ...n, isRead: true }))
} catch (error) {
console.error('Failed to mark all as read:', error)
logger.error('Failed to mark all as read:', error)
throw error
}
}
const markAsRead = async (notificationId: string) => {
if (!organizationId.value) {
console.warn('No organization selected')
logger.warn('No organization selected')
return
}
try {
@@ -102,7 +104,7 @@ export const useNotification = () => {
unreadCount.value--
}
} catch (error) {
console.error('Failed to mark notification as read:', error)
logger.error('Failed to mark notification as read:', error)
throw error
}
}

View File

@@ -1,10 +1,13 @@
import { ComplianceStatus, type FormElementDto } from '~~/.api-client'
import { complianceCheckableElementTypes, complianceMap } from './complianceMap'
import type { FormElementId } from '~~/types/formElement'
import { useLogger } from './useLogger'
const formElementComplianceMap = ref(new Map<FormElementId, ComplianceStatus>())
export function useApplicationFormValidator() {
const logger = useLogger().withTag('validator')
function getHighestComplianceStatus(): ComplianceStatus {
const complianceStatusValues = Array.from(formElementComplianceMap.value.values())
const highestComplianceNumber = Math.max(
@@ -37,7 +40,7 @@ export function useApplicationFormValidator() {
formElement.options.forEach((option) => {
if (!option.value) {
console.log(`Value missing for ${formElement.type}`)
logger.debug(`Value missing for ${formElement.type}`)
return
}

View File

@@ -0,0 +1,5 @@
import type { ConsolaInstance } from 'consola'
export function useLogger(): ConsolaInstance {
return useNuxtApp().$logger
}

View File

@@ -1,8 +1,11 @@
import { useLogger } from './useLogger'
export const isServerAvailable = ref(true)
export const isChecking = ref(false)
export const lastCheckTime = ref<Date | null>(null)
export function useServerHealth() {
const logger = useLogger().withTag('serverHealth')
const checkInterval = ref<ReturnType<typeof setInterval> | null>(null)
const healthCheckUrl = '/api/actuator/health'
@@ -30,11 +33,11 @@ export function useServerHealth() {
isServerAvailable.value = response.ok
if (!wasAvailable && isServerAvailable.value) {
console.info('Server is back online')
logger.info('Server is back online')
}
if (wasAvailable && !isServerAvailable.value) {
console.warn('Server is no longer available')
logger.warn('Server is no longer available')
}
return isServerAvailable.value
@@ -43,7 +46,7 @@ export function useServerHealth() {
isServerAvailable.value = false
if (wasAvailable) {
console.warn('Server health check failed:', error)
logger.warn('Server health check failed:', error)
}
return false

View File

@@ -57,6 +57,7 @@ const links = [
]
]
const open = ref(false)
const logger = useLogger().withTag('layout')
const isNotificationsSlideoverOpen = ref(false)
const { unreadCount, fetchUnreadCount, startPeriodicRefresh } = useNotification()
@@ -73,13 +74,13 @@ provide('notificationState', {
async function copyAccessTokenToClipboard() {
const { session } = useUserSession()
console.log('Access Token :', session.value?.jwt?.accessToken)
logger.debug('Access Token :', session.value?.jwt?.accessToken)
const accessToken = session.value?.jwt?.accessToken
if (accessToken) {
navigator.clipboard.writeText(accessToken)
console.log('Access token copied to clipboard')
logger.info('Access token copied to clipboard')
} else {
console.warn('No access token found in session')
logger.warn('No access token found in session')
}
}
</script>

View File

@@ -3,14 +3,16 @@
import { appendResponseHeader } from 'h3'
import { parse, parseSetCookie, serialize } from 'cookie-es'
import { jwtDecode, type JwtPayload } from 'jwt-decode'
import { useLogger } from '../composables/useLogger'
export default defineNuxtRouteMiddleware(async (to, from) => {
const nuxtApp = useNuxtApp()
// Don't run on client hydration when server rendered
if (import.meta.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) return
console.log('🔍 Middleware: refreshToken.global.ts')
console.log(` from: ${from.fullPath} to: ${to.fullPath}`)
const logger = useLogger().withTag('refreshToken')
logger.debug('🔍 Middleware: refreshToken.global.ts')
logger.debug(`from: ${from.fullPath} to: ${to.fullPath}`)
const { session, clear: clearSession, fetch: fetchSession } = useUserSession()
// Ignore if no tokens
@@ -25,11 +27,11 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
// Both tokens expired, clearing session
if (isExpired(accessPayload) && isExpired(refreshPayload)) {
console.info('both tokens expired, clearing session')
logger.info('both tokens expired, clearing session')
await clearSession()
return navigateTo('/login')
} else if (isExpired(accessPayload)) {
console.info('access token expired, refreshing')
logger.info('access token expired, refreshing')
await useRequestFetch()('/api/jwt/refresh', {
method: 'POST',
onResponse({ response: { headers } }: { response: { headers: Headers } }) {
@@ -41,7 +43,7 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
const { name, value } = parseSetCookie(setCookie)
if (name === runtimeConfig.session.name) {
console.log('updating headers.cookie to', value)
logger.debug('updating headers.cookie to', value)
const cookies = parse(serverEvent.headers.get('cookie') || '')
// set or overwrite existing cookie
@@ -64,10 +66,10 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
}
},
onError() {
console.error('🔍 Middleware: Token refresh failed')
logger.error('🔍 Middleware: Token refresh failed')
const { loggedIn } = useUserSession()
if (!loggedIn.value) {
console.log('🔍 Middleware: User not logged in, redirecting to /login')
logger.debug('🔍 Middleware: User not logged in, redirecting to /login')
return navigateTo('/login')
}
}

View File

@@ -94,6 +94,7 @@ const { hasRole } = usePermissions()
const { getAllApplicationFormTemplates, updateApplicationFormTemplate, createApplicationFormTemplate } =
await useApplicationFormTemplate()
const { t: $t } = useI18n()
const logger = useLogger().withTag('administration')
if (!hasRole('CHIEF_EXECUTIVE_OFFICER') && !hasRole('IT_DEPARTMENT')) {
await navigateTo('/')
@@ -239,7 +240,7 @@ async function saveTemplate() {
description: $t('templates.saveError'),
color: 'error'
})
console.error('Error saving template:', error)
logger.error('Error saving template:', error)
} finally {
isSaving.value = false
}

View File

@@ -4,10 +4,11 @@
<script setup lang="ts">
onMounted(async () => {
const logger = useLogger().withTag('auth callback')
try {
await navigateTo('/')
} catch (e) {
console.error('Error during login', e)
logger.error('Error during login', e)
}
})
</script>

View File

@@ -60,6 +60,7 @@ const userStore = useUserStore()
const { selectedOrganization } = storeToRefs(userStore)
const toast = useToast()
const { t: $t } = useI18n()
const logger = useLogger().withTag('create')
const { data, error } = await useAsyncData<PagedApplicationFormDto>(
'create-application-form',
@@ -132,11 +133,11 @@ function handleFormElementSectionsUpdate(sections: FormElementSectionDto[]) {
async function prepareAndCreateApplicationForm() {
if (!applicationFormTemplate.value) {
console.error('Application form data is undefined')
logger.error('Application form data is undefined')
return null
}
console.log('selectedOrganization', selectedOrganization.value)
logger.debug('selectedOrganization', selectedOrganization.value)
applicationFormTemplate.value.organizationId = selectedOrganization.value?.id ?? ''
return await createApplicationForm(applicationFormTemplate.value)

View File

@@ -119,6 +119,7 @@ const appConfig = useAppConfig()
const toast = useToast()
const userStore = useUserStore()
const { getUserById, updateEmailPreferences } = useUser()
const logger = useLogger().withTag('settings')
const colors = [
'red',
@@ -152,7 +153,7 @@ onMounted(async () => {
emailOnFormCreated.value = userData.emailOnFormCreated ?? true
emailOnFormSubmitted.value = userData.emailOnFormSubmitted ?? true
} catch (error) {
console.error('Failed to load user email preferences:', error)
logger.error('Failed to load user email preferences:', error)
}
}
})

View File

@@ -1,9 +1,18 @@
import { createLogger } from '~~/shared/utils/logger'
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const logger = createLogger({
level: config.public.logLevel,
tag: 'app error-handler',
fancy: import.meta.env.MODE !== 'production'
})
nuxtApp.hook('vue:error', (error, instance, info) => {
console.error('Vue error:', error, 'Instance:', instance, 'Info:', info)
logger.error('Vue error:', error, 'Instance:', instance, 'Info:', info)
})
nuxtApp.hook('app:error', (error) => {
console.error('App error:', error)
logger.error('App error:', error)
})
})

View File

@@ -0,0 +1,16 @@
import { createLogger } from '~~/shared/utils/logger'
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const logger = createLogger({
level: config.public.logLevel,
tag: 'legalconsenthub',
fancy: import.meta.env.MODE !== 'production'
})
return {
provide: {
logger
}
}
})

View File

@@ -1,4 +1,5 @@
import type { HTTPMethod } from 'h3'
import { useLogger } from '../composables/useLogger'
// Custom OpenAPI fetch client that wraps useRequestFetch. This ensures that authentication headers
// are forwarded correctly during SSR. Unlike fetch, useRequestFetch returns data directly,
@@ -28,7 +29,8 @@ export const wrappedFetchWrap = (requestFetch: ReturnType<typeof useRequestFetch
}
})
} catch (error: unknown) {
console.error('Fetch error:', error)
const logger = useLogger().withTag('wrappedFetch')
logger.error('Fetch error:', error)
// Check if it's a FetchError from ofetch
if (error && typeof error === 'object' && 'status' in error) {