@laioutr/logger
v0.5.1
Published
Laioutr nuxt logger module
Downloads
538
Readme
@laioutr/logger
This module makes a pino-logger available everywhere in the application via a composable.
Requirements
Make sure to enable the nitro-config experimental.asyncContext in order to use the logger in nitro. This is done by the nuxt-module without any additional configuration.
Configuration
You can set the following runtime-configurations:
config.public.logLevelClient = 'debug';
config.public.logLevelServer = 'debug';The following values are available and will determine which level is the lowest that will be output:
'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';Furthermore the following config can be set to enable verbose logging for nitro-requests and responses:
config.logNitroRequestsVerbose = true;
config.logNitroResponsesVerbose = true;This is currently disabled by default.
Usage
Get access to the logger using the useLogger() composable. It's available in the browser, the ssr-server and the regular nitro-server.
Best practice is to create a named logger for each part of your application. Here are a few examples:
// In a vue-component
const logger = useLogger('CmsBlockHeroSlider');
// In a composable
const logger = useLogger('useModal');
// In a page
const logger = useLogger('page:pdp');You can then use the logger to log with different levels:
logger.debug('Very unimportant message');
logger.warn('Something is not right here');
logger.error('Error occured!');You can also pass an object to the logger as an argument to include it in the log:
logger.info('Something happened here', { important: 'value for debugging' });
try {
// ...
} catch (error: any) {
// ...
logger.error('Operation failed', error);
}Note, that the order of arguments is swapped compared to the default pino-order. But you can still pass an object as the first argument if you want.
This was done to make logging more natural.
Notes on browser logging
Each message in the browser will be passed to the corresponding console-method. E.g. console.info() et al. If you pass a name when calling the useLogger() composable, the message will be prefixed with that name.
All vue-errors are printed via this logger.
Notes on server logging
In local development the log will be pretty-printed using pino-pretty. In a production-environment the log-messages will be json.
Each request will be logged by pino-http if enabled. This package also adds a reqId to every h3-request which can be used for tracing events across a request. When you use a logger anywhere inside a nitro-request, it will also include that reqId. The reqId will be exposed in the http response-headers as x-req-id.
All logging-messages put out by consolas (used by nuxt for printing logs) will be redirected to pino.
All console.* methods are hooked to also print with pino. This is done by nuxt by default.
All errors in nitro will be printed via this logger.
