Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Flexible logging functionality for Vue.js with support for custom hook operations.

License

NotificationsYou must be signed in to change notification settings

dev-tavern/vue-logger-plugin

Repository files navigation

NPM VersionLicensecodecovcircleciminifiedminzipped

Flexible logging functionality for Vue.js with support for custom hook operations.

Contents

NPM Package Install

npm i vue-logger-plugin@1.x-latest

Vue Plugin Install

The logging implementation can be installed a couple different ways, either by providing options or a constructed VueLogger instance toVue.use.

Here is the simplest usage:

main.js

importVueLoggerfrom'vue-logger-plugin'Vue.use(VueLogger,{<optionshere>})// or simply Vue.use(VueLogger) to just use the default options

For advanced usage (i.e. using conditional options and hooks), it is recommended to export the constructed logger implementation in a separate file and then import into your main file.

logger/index.js

importVueLoggerfrom'vue-logger-plugin'// define optionsconstoptions={enabled:true,level:'debug',beforeHooks:[ ...],afterHooks:[ ...]}// export logger with applied optionsexportdefaultnewVueLogger(options)

main.js

importloggerfrom'./logger'Vue.use(logger)// note that you may also provide the options argument here as well// if provided, they would be merged with / override the options already applied

More information about hooks can be found in theHooks section.

Options

NameTypeDefaultDescription
enabledbooleantrueenable/disable logger
consoleEnabledbooleantrueenable/disable console output
levelstring'debug'the logging level (one of: debug, info, warn, error, log)
callerInfobooleanfalsewhether information about the caller function should be included
prefixFormatstring(seebelow)provide a custom formatted string for the log message prefix (preceeds the log arguments)
beforeHooksLoggerHook[][]hooks invoked before a statement is logged, can be used to alter log arguments (use carefully)
afterHooksLoggerHook[][]hooks invoked after a statement is logged

Levels

log <-- error <-- warn <-- info <-- debug

(from left to right: least inclusive to most inclusive)

Specify an appropriate level to limit the amount of information logged. For example, using the 'warn' level will log the 'log', 'error', and 'warn' events but not the 'info' or 'debug' events.

Note: Depending on your browser, the debug level may be labeled as "Verbose" instead of "Debug". Ensure this level is enabled if looking for debug logs in the browser console. Chrome uses verbose for these logs, see docshere.

enabled vs consoleEnabled

Settingenabled to false will disable all logger functionality (console output + hook invocations).

SettingconsoleEnabled to false will disable just the console output but will still invoke the hooks.

So, for example, if you want to prevent writing logs to the browser console but still invoke a hook (i.e. to send logs to a server) then you would setenabled: true andconsoleEnabled: false.

callerInfo

SettingcallerInfo to true will result in caller function information (fileName, functionName, lineNumber) being determined and included in the log, as well as being included in events provided to hooks, for each log function invocation.

prefixFormat

Use theprefixFormat option to customize the message prefix (portion of log statement that appears before the arguments provided to the log function).This can as well be used to inject additional information into the message prefix, such as timestamps or user identifiers for example.

The value of this option must be a function which accepts a partial LogEvent object and returns a string. The provided LogEvent object contains only loglevel andcaller information.

The default for this option is:

prefixFormat:({ level, caller})=>(caller      ?`[${level.toUpperCase()}] [${caller?.fileName}:${caller?.functionName}:${caller?.lineNumber}]`      :`[${level.toUpperCase()}]`)

Hooks

Hooks allow for advanced customization of the logger implementation, providing operations to be run before and after logging is performed. These are defined on options asbeforeHooks andafterHooks.

beforeHooks

Invoked before a statement is logged, can alter the log arguments which can impact the log output.

afterHooks

Invoked after a statement is logged, cannot impact the log output.

Built-in Hooks

The following hooks are available in this package and can be used by simply importing and adding them to the beforeHooks and/or afterHooks arrays of your options.

StringifyObjectsHookApplies JSON.stringify on all objects provided as arguments to a logging method.

import{StringifyObjectsHook}from'vue-logger-plugin'constoptions={// ... (other options)beforeHooks:[StringifyObjectsHook]}

StringifyAndParseObjectsHookApplies JSON.stringify and JSON.parse on all objects provided as arguments to a logging method.

import{StringifyAndParseObjectsHook}from'vue-logger-plugin'constoptions={// ... (other options)beforeHooks:[StringifyAndParseObjectsHook]}

The above are best used as 'before hooks' as they may purposefully alter the log output. This way you are sure you are seeing the value of an object at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change.

Write Your Own Hooks

You can easily write your own hooks to apply custom logic. A hook must implement arun function to handle a log event (an object containing the log level and the array of arguments which were passed to the logging method), and may optionally implement aninstall function which is invoked during plugin installation (or at the time of logger options application - seeUsage section).

For reference, here are the interfaces:

exportinterfaceLoggerHook{run(event:LogEvent):voidinstall?(options:LoggerOptions):voidprops?:{[key:string]:any}}exportinterfaceLogEvent{level:LogLevel// 'debug' | 'info' | 'warn' | 'error' | 'log'argumentArray:any[]caller?:CallerInfo}exportinterfaceCallerInfo{fileName?:stringfunctionName?:stringlineNumber?:string}

Sample Custom Hook - Leveraging Axios to Send Logs to Server

This is a basic example demonstrating how you could have the logger send log data to a server using an Axios client.

logger/index.ts

importVueLogger,{LoggerOptions,LoggerHook,LogEvent}from'vue-logger-plugin'importaxiosfrom'axios'constServerLogHook:LoggerHook={run(event:LogEvent){axios.post('/log',{severity:event.level,data:event.argumentArray})}}constoptions:LoggerOptions={// ... (other options)afterHooks:[ServerLogHook]}exportdefaultnewVueLogger(options)

Usage

Once installed, the logger is available within the Vue instance via both$log and$logger (both access the same logger instance and provide the same functionality).

newVue({created:function(){consttestObject={name:'test',value:'this is a test object'}// using $logthis.$log.debug('Test Message',testObject)this.$log.info('Test Message',testObject)this.$log.warn('Test Message',testObject)this.$log.error('Test Message',testObject)this.$log.log('Test Message',testObject)// using $loggerthis.$logger.debug('Test Message',testObject)this.$logger.info('Test Message',testObject)this.$logger.warn('Test Message',testObject)this.$logger.error('Test Message',testObject)this.$logger.log('Test Message',testObject)}})

As described in the Vue Plugin Install section above, options can be provided to the VueLogger constructor and/or to the Vue.use method for customizing the logging implementation. As well, options can be applied at any time to the logger on the Vue instance via theapply method. This allows for on-demand enabling/disabling of the logger and adjusting log levels as needed from within your components.

this.$log.apply({level:'info'})// applies log level
this.$log.apply({enabled:false})// disables logging

License

This project is licensed under the MIT License - see theLICENSE file for details.

About

Flexible logging functionality for Vue.js with support for custom hook operations.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp