diff --git a/docs/3.api/5.kit/13.logging.md b/docs/3.api/5.kit/13.logging.md index 721d6fcd44..fffc107b9f 100644 --- a/docs/3.api/5.kit/13.logging.md +++ b/docs/3.api/5.kit/13.logging.md @@ -17,7 +17,7 @@ Returns a logger instance. It uses [consola](https://github.com/unjs/consola) un ### Type ```ts -function useLogger (tag?: string): ConsolaInstance +function useLogger (tag?: string, options?: Partial): ConsolaInstance ``` ### Parameters @@ -30,6 +30,14 @@ function useLogger (tag?: string): ConsolaInstance A tag to prefix all log messages with. +#### `options` + +**Type**: `Partial` + +***Optional**: `true` + +Consola configuration options + ### Examples ```ts @@ -43,3 +51,15 @@ export default defineNuxtModule({ } }) ``` + +```ts +import { defineNuxtModule, useLogger } from '@nuxt/kit' + +export default defineNuxtModule({ + setup(options, nuxt) { + const logger = useLogger('my-module', { level: options.quiet ? 0 : 3 }) + + logger.info('Hello from my module!') + } +}) +``` diff --git a/packages/kit/src/logger.test.ts b/packages/kit/src/logger.test.ts new file mode 100644 index 0000000000..a3cc49541d --- /dev/null +++ b/packages/kit/src/logger.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest' + +import { consola } from 'consola' +import { logger, useLogger } from './logger' + +vi.mock("consola", () => { + const logger = {} as any; + + logger.create = vi.fn(() => ({...logger})); + logger.withTag = vi.fn(() => ({...logger})); + + return { consola: logger }; +}) + +describe('logger', () => { + it('should expose consola', () => { + expect(logger).toBe(consola) + }) +}) + +describe('useLogger', () => { + it('should expose consola when not passing a tag', () => { + expect(useLogger()).toBe(consola); + }); + + it('should create a new instance when passing a tag', () => { + const logger = vi.mocked(consola); + + const instance = useLogger("tag"); + + expect(instance).toEqual(logger); + expect(instance).not.toBe(logger); + expect(logger.create).toBeCalledWith({}); + expect(logger.withTag).toBeCalledWith("tag"); + }); + + it('should create a new instance when passing a tag and options', () => { + const logger = vi.mocked(consola); + + const instance = useLogger("tag", { level: 0 }); + + expect(instance).toEqual(logger); + expect(instance).not.toBe(logger); + expect(logger.create).toBeCalledWith({ level: 0 }); + expect(logger.withTag).toBeCalledWith("tag"); + }); + +}) diff --git a/packages/kit/src/logger.ts b/packages/kit/src/logger.ts index 39be4ec2c6..be95003480 100644 --- a/packages/kit/src/logger.ts +++ b/packages/kit/src/logger.ts @@ -1,7 +1,8 @@ import { consola } from 'consola' +import type { ConsolaOptions } from 'consola'; export const logger = consola -export function useLogger (tag?: string) { - return tag ? logger.withTag(tag) : logger +export function useLogger (tag?: string, options: Partial = {}) { + return tag ? logger.create(options).withTag(tag) : logger }