feat(kit): allow customising logger options (#24243)

This commit is contained in:
Daniel Acuña 2023-11-23 18:57:48 -03:00 committed by GitHub
parent 72efc41f50
commit c214869e51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 72 additions and 3 deletions

View File

@ -17,7 +17,7 @@ Returns a logger instance. It uses [consola](https://github.com/unjs/consola) un
### Type ### Type
```ts ```ts
function useLogger (tag?: string): ConsolaInstance function useLogger (tag?: string, options?: Partial<ConsolaOptions>): ConsolaInstance
``` ```
### Parameters ### Parameters
@ -30,6 +30,14 @@ function useLogger (tag?: string): ConsolaInstance
A tag to prefix all log messages with. A tag to prefix all log messages with.
#### `options`
**Type**: `Partial<ConsolaOptions>`
***Optional**: `true`
Consola configuration options
### Examples ### Examples
```ts ```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!')
}
})
```

View File

@ -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");
});
})

View File

@ -1,7 +1,8 @@
import { consola } from 'consola' import { consola } from 'consola'
import type { ConsolaOptions } from 'consola';
export const logger = consola export const logger = consola
export function useLogger (tag?: string) { export function useLogger (tag?: string, options: Partial<ConsolaOptions> = {}) {
return tag ? logger.withTag(tag) : logger return tag ? logger.create(options).withTag(tag) : logger
} }