From 68fcec404dbbb84ce1ea95bb098bad08957fa91b Mon Sep 17 00:00:00 2001 From: Zachary Haber Date: Mon, 20 Jun 2022 10:33:44 -0500 Subject: [PATCH] style: run prettier:fix --- CHANGELOG.md | 6 +- README.md | 7 +- SECURITY.md | 6 +- docs/_layouts/default.html | 106 ++- docs/api.md | 39 +- docs/appenders.md | 82 +-- docs/assets/css/style.scss | 2 +- docs/categories.md | 59 +- docs/categoryFilter.md | 40 +- docs/clustering.md | 10 +- docs/connect-logger.md | 113 ++-- docs/console.md | 9 +- docs/contrib-guidelines.md | 8 +- docs/contributors.md | 2 +- docs/dateFile.md | 52 +- docs/faq.md | 45 +- docs/file.md | 56 +- docs/fileSync.md | 40 +- docs/layouts.md | 200 +++--- docs/logLevelFilter.md | 9 +- docs/migration-guide.md | 40 +- docs/multiFile.md | 50 +- docs/multiprocess.md | 38 +- docs/noLogFilter.md | 61 +- docs/recording.md | 18 +- docs/stderr.md | 8 +- docs/stdout.md | 9 +- docs/tcp-server.md | 16 +- docs/tcp.md | 18 +- docs/terms.md | 2 +- docs/v3-changes.md | 25 +- docs/webpack.md | 3 +- docs/writing-appenders.md | 16 +- examples/cluster.js | 4 +- examples/custom-layout.js | 16 +- examples/date-file-rolling.js | 11 +- examples/example-connect-logger.js | 6 +- examples/example-socket.js | 14 +- examples/example.js | 11 +- examples/flush-on-exit.js | 30 +- examples/fromreadme.js | 2 +- examples/hipchat-appender.js | 23 +- examples/layouts.js | 6 +- examples/log-rolling-bug.js | 16 +- examples/log-rolling.js | 10 +- examples/log-to-files.js | 52 +- examples/logFaces-appender.js | 11 +- examples/loggly-appender.js | 10 +- examples/logstashHTTP.js | 12 +- examples/logstashUDP.js | 17 +- examples/memory-test.js | 46 +- examples/patternLayout-tokens.js | 14 +- examples/pm2.js | 6 +- examples/pm2.json | 18 +- examples/rabbitmq-appender.js | 14 +- examples/redis-appender.js | 14 +- examples/slack-appender.js | 8 +- examples/smtp-appender.js | 14 +- examples/stacktrace.js | 32 +- lib/LoggingEvent.js | 27 +- lib/appenders/adapters.js | 7 +- lib/appenders/dateFile.js | 28 +- lib/appenders/file.js | 44 +- lib/appenders/fileSync.js | 73 ++- lib/appenders/index.js | 69 +- lib/appenders/logLevelFilter.js | 5 +- lib/appenders/multiFile.js | 10 +- lib/appenders/multiprocess.js | 35 +- lib/appenders/noLogFilter.js | 10 +- lib/appenders/recording.js | 8 +- lib/appenders/stderr.js | 2 - lib/appenders/stdout.js | 2 - lib/appenders/tcp-server.js | 10 +- lib/appenders/tcp.js | 13 +- lib/categories.js | 47 +- lib/clustering.js | 57 +- lib/configuration.js | 22 +- lib/connect-logger.js | 86 +-- lib/layouts.js | 88 ++- lib/levels.js | 21 +- lib/log4js.js | 50 +- lib/logger.js | 29 +- test/.eslintrc | 6 +- test/multiprocess-worker.js | 2 +- test/sandbox-coverage.js | 14 +- test/tap/LoggingEvent-test.js | 93 +-- test/tap/appender-dependencies-test.js | 113 ++-- test/tap/categoryFilter-test.js | 98 +-- test/tap/cluster-test.js | 78 +-- test/tap/configuration-inheritance-test.js | 333 +++++----- test/tap/configuration-test.js | 70 +- test/tap/configuration-validation-test.js | 316 ++++----- test/tap/connect-context-test.js | 44 +- test/tap/connect-logger-test.js | 264 ++++---- test/tap/connect-nolog-test.js | 248 +++---- test/tap/consoleAppender-test.js | 46 +- test/tap/dateFileAppender-test.js | 194 +++--- test/tap/default-settings-test.js | 192 +++--- test/tap/disable-cluster-test.js | 46 +- test/tap/dummy-appender.js | 3 +- test/tap/file-descriptor-leak-test.js | 118 ++-- test/tap/file-sighup-test.js | 110 ++-- test/tap/fileAppender-test.js | 391 ++++++------ test/tap/fileSyncAppender-test.js | 601 ++++++++--------- test/tap/layouts-test.js | 710 +++++++++++---------- test/tap/levels-before-configure-test.js | 8 +- test/tap/levels-test.js | 170 ++--- test/tap/log4js.json | 18 +- test/tap/logLevelFilter-test.js | 142 ++--- test/tap/logger-test.js | 376 ++++++----- test/tap/logging-test.js | 277 ++++---- test/tap/multi-file-appender-test.js | 398 ++++++------ test/tap/multiprocess-shutdown-test.js | 76 +-- test/tap/multiprocess-test.js | 321 +++++----- test/tap/newLevel-test.js | 240 +++---- test/tap/no-cluster-test.js | 18 +- test/tap/noLogFilter-test.js | 168 ++--- test/tap/passenger-test.js | 28 +- test/tap/pause-test.js | 171 ++--- test/tap/pm2-support-test.js | 68 +- test/tap/recordingAppender-test.js | 20 +- test/tap/server-test.js | 269 ++++---- test/tap/setLevel-asymmetry-test.js | 22 +- test/tap/stacktraces-test.js | 20 +- test/tap/stderrAppender-test.js | 50 +- test/tap/stdoutAppender-test.js | 26 +- test/tap/subcategories-test.js | 115 ++-- test/tap/tcp-appender-test.js | 238 +++---- test/tap/test-config.json | 4 +- v2-changes.md | 3 +- 130 files changed, 5189 insertions(+), 4502 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ac0db9b..020f90ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,7 +76,7 @@ ## 6.4.4 -- [fix: set logger.level on runtime will no longer wrongly reset useCallStack](https://github.com/log4js-node/log4js-node/pull/1217) - thanks [@peteriman](https://github.com/peteriman) +- [fix: set logger.level on runtime will no longer wrongly reset useCallStack](https://github.com/log4js-node/log4js-node/pull/1217) - thanks [@peteriman](https://github.com/peteriman) - [docs: updated docs for broken links and inaccessible pages](https://github.com/log4js-node/log4js-node/pull/1219) - thanks [@peteriman](https://github.com/peteriman) - [docs: broken link to gelf appender](https://github.com/log4js-node/log4js-node/pull/1218) - thanks [@mattalexx](https://github.com/mattalexx) - [docs: updated docs for appenders module loading](https://github.com/log4js-node/log4js-node/pull/985) - thanks [@leonimurilo](https://github.com/leonimurilo) @@ -89,7 +89,6 @@ ## 6.4.3 - - [fix: added filename validation](https://github.com/log4js-node/log4js-node/pull/1201) - thanks [@peteriman](https://github.com/peteriman) - [refactor: do not initialise default appenders as it will be done again by configure()](https://github.com/log4js-node/log4js-node/pull/1210) - thanks [@peteriman](https://github.com/peteriman) - [refactor: defensive coding for cluster=null if require('cluster') fails in try-catch ](https://github.com/log4js-node/log4js-node/pull/1199) - thanks [@peteriman](https://github.com/peteriman) @@ -153,6 +152,7 @@ - [chore(deps-dev): bump typescript from 4.5.4 to 4.5.5](https://github.com/log4js-node/log4js-node/pull/1166) - thanks [@peteriman](https://github.com/peteriman) ## 6.4.0 - BREAKING CHANGE 💥 + New default file permissions may cause external applications unable to read logs. A [manual code/configuration change](https://github.com/log4js-node/log4js-node/pull/1141#issuecomment-1076224470) is required. @@ -199,7 +199,7 @@ A [manual code/configuration change](https://github.com/log4js-node/log4js-node/ - chore(deps-dev): bump eslint-plugin-prettier from 3.4.1 to 4.0.0 - chore(deps-dev): bump husky from 3.1.0 to 7.0.4 - chore(deps-dev): bump prettier from 1.19.0 to 2.5.1 - - chore(deps-dev): bump typescript from 3.9.10 to 4.5.4 + - chore(deps-dev): bump typescript from 3.9.10 to 4.5.4 - [chore(deps-dev): bump eslint-config-prettier from 6.15.0 to 8.3.0](https://github.com/log4js-node/log4js-node/pull/1129) - thanks [@peteriman](https://github.com/peteriman) - [chore(deps): updated dependencies](https://github.com/log4js-node/log4js-node/pull/1121) - thanks [@peteriman](https://github.com/peteriman) - chore(deps-dev): bump codecov from 3.6.1 to 3.8.3 diff --git a/README.md b/README.md index 68dc4211..948f5770 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -log4js-node [![CodeQL](https://github.com/log4js-node/log4js-node/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/log4js-node/log4js-node/actions/workflows/codeql-analysis.yml) [![Node.js CI](https://github.com/log4js-node/log4js-node/actions/workflows/node.js.yml/badge.svg)](https://github.com/log4js-node/log4js-node/actions/workflows/node.js.yml) -=========== +# log4js-node [![CodeQL](https://github.com/log4js-node/log4js-node/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/log4js-node/log4js-node/actions/workflows/codeql-analysis.yml) [![Node.js CI](https://github.com/log4js-node/log4js-node/actions/workflows/node.js.yml/badge.svg)](https://github.com/log4js-node/log4js-node/actions/workflows/node.js.yml) [![NPM](https://nodei.co/npm/log4js.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/log4js/) @@ -67,7 +66,7 @@ See example.js for a full example, but here's a snippet (also in `examples/fromr const log4js = require("log4js"); log4js.configure({ appenders: { cheese: { type: "file", filename: "cheese.log" } }, - categories: { default: { appenders: ["cheese"], level: "error" } } + categories: { default: { appenders: ["cheese"], level: "error" } }, }); const logger = log4js.getLogger("cheese"); @@ -102,7 +101,7 @@ There's also [an example application](https://github.com/log4js-node/log4js-exam import log4js from "log4js"; log4js.configure({ appenders: { cheese: { type: "file", filename: "cheese.log" } }, - categories: { default: { appenders: ["cheese"], level: "error" } } + categories: { default: { appenders: ["cheese"], level: "error" } }, }); const logger = log4js.getLogger(); diff --git a/SECURITY.md b/SECURITY.md index f872565b..83060309 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported Versions -We're aiming to only support the latest major version of log4js. Older than that is usually *very* old. +We're aiming to only support the latest major version of log4js. Older than that is usually _very_ old. | Version | Supported | | ------- | ------------------ | @@ -13,7 +13,7 @@ We're aiming to only support the latest major version of log4js. Older than that Report vulnerabilities via email to: -* Gareth Jones -* Lam Wei Li +- Gareth Jones +- Lam Wei Li Please put "[log4js:security]" in the subject line. We will aim to respond within a day or two. diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html index 956b15be..ba8235bb 100644 --- a/docs/_layouts/default.html +++ b/docs/_layouts/default.html @@ -1,14 +1,20 @@ - + - - - {{ site.title | default: site.github.repository_name }} by {{ site.github.owner_name }} + + + + {{ site.title | default: site.github.repository_name }} by {{ + site.github.owner_name }} + - - + + @@ -18,7 +24,11 @@

{{ site.title | default: site.github.repository_name }}

{{ site.description | default: site.github.project_tagline }}

{% if site.github.is_project_page %} -

View the Project on GitHub {{ github_name }}

+

+ View the Project on GitHub {{ github_name }} +

{% endif %}
    @@ -34,42 +44,72 @@

    {{ site.title | default: site.github.repository_name }}

{% if site.github.is_user_page %} -

View My GitHub Profile

- {% endif %} - - {% if site.show_downloads %} - +

+ View My GitHub Profile +

+ {% endif %} {% if site.show_downloads %} + {% endif %} -
- - {{ content }} - -
+
{{ content }}
- - {% if site.google_analytics %} + {% if site.google_analytics %} - {% endif %} + {% endif %} diff --git a/docs/api.md b/docs/api.md index 98eeabae..3e64d658 100644 --- a/docs/api.md +++ b/docs/api.md @@ -13,34 +13,39 @@ Configuration objects must define at least one appender, and a default category. `configure` method call returns the configured log4js object. ### Configuration Object + Properties: -* `levels` (optional, object) - used for defining custom log levels, or redefining existing ones; this is a map with the level name as the key (string, case insensitive), and an object as the value. The object should have two properties: the level value (integer) as the value, and the colour. Log levels are used to assign importance to log messages, with the integer value being used to sort them. If you do not specify anything in your configuration, the default values are used (ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF - note that OFF is intended to be used to turn off logging, not as a level for actual logging, i.e. you would never call `logger.off('some log message')`). Levels defined here are used in addition to the default levels, with the integer value being used to determine their relation to the default levels. If you define a level with the same name as a default level, then the integer value in the config takes precedence. Level names must begin with a letter, and can only contain letters, numbers and underscores. -* `appenders` (object) - a map of named appenders (string) to appender definitions (object); appender definitions must have a property `type` (string) - other properties depend on the appender type. -* `categories` (object) - a map of named categories (string) to category definitions (object). You must define the `default` category which is used for all log events that do not match a specific category. Category definitions have two properties: - * `appenders` (array of strings) - the list of appender names to be used for this category. A category must have at least one appender. - * `level` (string, case insensitive) - the minimum log level that this category will send to the appenders. For example, if set to 'error' then the appenders will only receive log events of level 'error', 'fatal', 'mark' - log events of 'info', 'warn', 'debug', or 'trace' will be ignored. - * `enableCallStack` (boolean, optional, defaults to `false`) - setting this to `true` will make log events for this category use the call stack to generate line numbers and file names in the event. See [pattern layout](layouts.md) for how to output these values in your appenders. -* `pm2` (boolean) (optional) - set this to true if you're running your app using [pm2](http://pm2.keymetrics.io), otherwise logs will not work (you'll also need to install pm2-intercom as pm2 module: `pm2 install pm2-intercom`) -* `pm2InstanceVar` (string) (optional, defaults to 'NODE_APP_INSTANCE') - set this if you're using pm2 and have changed the default name of the NODE_APP_INSTANCE variable. -* `disableClustering` (boolean) (optional) - set this to true if you liked the way log4js used to just ignore clustered environments, or you're having trouble with PM2 logging. Each worker process will do its own logging. Be careful with this if you're logging to files, weirdness can occur. + +- `levels` (optional, object) - used for defining custom log levels, or redefining existing ones; this is a map with the level name as the key (string, case insensitive), and an object as the value. The object should have two properties: the level value (integer) as the value, and the colour. Log levels are used to assign importance to log messages, with the integer value being used to sort them. If you do not specify anything in your configuration, the default values are used (ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF - note that OFF is intended to be used to turn off logging, not as a level for actual logging, i.e. you would never call `logger.off('some log message')`). Levels defined here are used in addition to the default levels, with the integer value being used to determine their relation to the default levels. If you define a level with the same name as a default level, then the integer value in the config takes precedence. Level names must begin with a letter, and can only contain letters, numbers and underscores. +- `appenders` (object) - a map of named appenders (string) to appender definitions (object); appender definitions must have a property `type` (string) - other properties depend on the appender type. +- `categories` (object) - a map of named categories (string) to category definitions (object). You must define the `default` category which is used for all log events that do not match a specific category. Category definitions have two properties: + - `appenders` (array of strings) - the list of appender names to be used for this category. A category must have at least one appender. + - `level` (string, case insensitive) - the minimum log level that this category will send to the appenders. For example, if set to 'error' then the appenders will only receive log events of level 'error', 'fatal', 'mark' - log events of 'info', 'warn', 'debug', or 'trace' will be ignored. + - `enableCallStack` (boolean, optional, defaults to `false`) - setting this to `true` will make log events for this category use the call stack to generate line numbers and file names in the event. See [pattern layout](layouts.md) for how to output these values in your appenders. +- `pm2` (boolean) (optional) - set this to true if you're running your app using [pm2](http://pm2.keymetrics.io), otherwise logs will not work (you'll also need to install pm2-intercom as pm2 module: `pm2 install pm2-intercom`) +- `pm2InstanceVar` (string) (optional, defaults to 'NODE_APP_INSTANCE') - set this if you're using pm2 and have changed the default name of the NODE_APP_INSTANCE variable. +- `disableClustering` (boolean) (optional) - set this to true if you liked the way log4js used to just ignore clustered environments, or you're having trouble with PM2 logging. Each worker process will do its own logging. Be careful with this if you're logging to files, weirdness can occur. ## Loggers - `log4js.getLogger([category])` This function takes a single optional string argument to denote the category to be used for log events on this logger. If no category is specified, the events will be routed to the appender for the `default` category. The function returns a `Logger` object which has its level set to the level specified for that category in the config and implements the following functions: -* `(args...)` - where `` can be any of the lower case names of the levels (including any custom levels defined). For example: `logger.info('some info')` will dispatch a log event with a level of info. If you're using the basic, coloured or message pass-through [layouts](layouts.md), the logged string will have its formatting (placeholders like `%s`, `%d`, etc) delegated to [util.format](https://nodejs.org/api/util.html#util_util_format_format_args). -* `isEnabled()` - returns true if a log event of level (camel case) would be dispatched to the appender defined for the logger's category. For example: `logger.isInfoEnabled()` will return true if the level for the logger is INFO or lower. -* `addContext(,)` - where `` is a string, `` can be anything. This stores a key-value pair that is added to all log events generated by the logger. Uses would be to add ids for tracking a user through your application. Currently only the `logFaces` appenders make use of the context values. -* `removeContext()` - removes a previously defined key-value pair from the context. -* `clearContext()` - removes all context pairs from the logger. -* `setParseCallStackFunction(function)` - Allow to override the default way to parse the callstack data for the layout pattern, a generic javascript Error object is passed to the function. Must return an object with properties : `functionName` / `fileName` / `lineNumber` / `columnNumber` / `callStack`. Can for example be used if all of your log call are made from one "debug" class and you would to "erase" this class from the callstack to only show the function which called your "debug" class. + +- `(args...)` - where `` can be any of the lower case names of the levels (including any custom levels defined). For example: `logger.info('some info')` will dispatch a log event with a level of info. If you're using the basic, coloured or message pass-through [layouts](layouts.md), the logged string will have its formatting (placeholders like `%s`, `%d`, etc) delegated to [util.format](https://nodejs.org/api/util.html#util_util_format_format_args). +- `isEnabled()` - returns true if a log event of level (camel case) would be dispatched to the appender defined for the logger's category. For example: `logger.isInfoEnabled()` will return true if the level for the logger is INFO or lower. +- `addContext(,)` - where `` is a string, `` can be anything. This stores a key-value pair that is added to all log events generated by the logger. Uses would be to add ids for tracking a user through your application. Currently only the `logFaces` appenders make use of the context values. +- `removeContext()` - removes a previously defined key-value pair from the context. +- `clearContext()` - removes all context pairs from the logger. +- `setParseCallStackFunction(function)` - Allow to override the default way to parse the callstack data for the layout pattern, a generic javascript Error object is passed to the function. Must return an object with properties : `functionName` / `fileName` / `lineNumber` / `columnNumber` / `callStack`. Can for example be used if all of your log call are made from one "debug" class and you would to "erase" this class from the callstack to only show the function which called your "debug" class. The `Logger` object has the following properties: -* `level` - where `level` is a log4js level or a string that matches a level (e.g. 'info', 'INFO', etc). This allows overriding the configured level for this logger. Changing this value applies to all loggers of the same category. -* `useCallStack` - where `useCallStack` is a boolean to indicate if log events for this category use the call stack to generate line numbers and file names in the event. This allows overriding the configured useCallStack for this logger. Changing this value applies to all loggers of the same category. + +- `level` - where `level` is a log4js level or a string that matches a level (e.g. 'info', 'INFO', etc). This allows overriding the configured level for this logger. Changing this value applies to all loggers of the same category. +- `useCallStack` - where `useCallStack` is a boolean to indicate if log events for this category use the call stack to generate line numbers and file names in the event. This allows overriding the configured useCallStack for this logger. Changing this value applies to all loggers of the same category. ## Shutdown - `log4js.shutdown(cb)` `shutdown` accepts a callback that will be called when log4js has closed all appenders and finished writing log events. Use this when your programme exits to make sure all your logs are written to files, sockets are closed, etc. ## Custom Layouts - `log4js.addLayout(type, fn)` + This function is used to add user-defined layout functions. See [layouts](layouts.md) for more details and an example. diff --git a/docs/appenders.md b/docs/appenders.md index a34c6b72..1619952a 100644 --- a/docs/appenders.md +++ b/docs/appenders.md @@ -1,73 +1,79 @@ # Log4js - Appenders Appenders serialise log events to some form of output. They can write to files, send emails, send data over the network. All appenders have a `type` which determines which appender gets used. For example: + ```javascript -const log4js = require('log4js'); +const log4js = require("log4js"); log4js.configure({ appenders: { - out: { type: 'stdout' }, - app: { type: 'file', filename: 'application.log' } + out: { type: "stdout" }, + app: { type: "file", filename: "application.log" }, }, categories: { - default: { appenders: [ 'out', 'app' ], level: 'debug' } - } + default: { appenders: ["out", "app"], level: "debug" }, + }, }); ``` + This defines two appenders named 'out' and 'app'. 'out' uses the [stdout](stdout.md) appender which writes to standard out. 'app' uses the [file](file.md) appender, configured to write to 'application.log'. ## Core Appenders The following appenders are included with log4js. Some require extra dependencies that are not included as part of log4js (the [smtp](https://github.com/log4js-node/smtp) appender needs [nodemailer](https://www.npmjs.com/package/nodemailer) for example), and these will be noted in the docs for that appender. If you don't use those appenders, then you don't need the extra dependencies. -* [categoryFilter](categoryFilter.md) -* [console](console.md) -* [dateFile](dateFile.md) -* [file](file.md) -* [fileSync](fileSync.md) -* [logLevelFilter](logLevelFilter.md) -* [multiFile](multiFile.md) -* [multiprocess](multiprocess.md) -* [noLogFilter](noLogFilter.md) -* [recording](recording.md) -* [stderr](stderr.md) -* [stdout](stdout.md) -* [tcp](tcp.md) -* [tcp-server](tcp-server.md) +- [categoryFilter](categoryFilter.md) +- [console](console.md) +- [dateFile](dateFile.md) +- [file](file.md) +- [fileSync](fileSync.md) +- [logLevelFilter](logLevelFilter.md) +- [multiFile](multiFile.md) +- [multiprocess](multiprocess.md) +- [noLogFilter](noLogFilter.md) +- [recording](recording.md) +- [stderr](stderr.md) +- [stdout](stdout.md) +- [tcp](tcp.md) +- [tcp-server](tcp-server.md) ## Optional Appenders The following appenders are supported by log4js, but are no longer distributed with log4js core from version 3 onwards. -* [gelf](https://github.com/log4js-node/gelf) -* [hipchat](https://github.com/log4js-node/hipchat) -* [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) -* [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) -* [loggly](https://github.com/log4js-node/loggly) -* [logstashHTTP](https://github.com/log4js-node/logstashHTTP) -* [logstashUDP](https://github.com/log4js-node/logstashUDP) -* [mailgun](https://github.com/log4js-node/mailgun) -* [rabbitmq](https://github.com/log4js-node/rabbitmq) -* [redis](https://github.com/log4js-node/redis) -* [slack](https://github.com/log4js-node/slack) -* [smtp](https://github.com/log4js-node/smtp) +- [gelf](https://github.com/log4js-node/gelf) +- [hipchat](https://github.com/log4js-node/hipchat) +- [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) +- [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) +- [loggly](https://github.com/log4js-node/loggly) +- [logstashHTTP](https://github.com/log4js-node/logstashHTTP) +- [logstashUDP](https://github.com/log4js-node/logstashUDP) +- [mailgun](https://github.com/log4js-node/mailgun) +- [rabbitmq](https://github.com/log4js-node/rabbitmq) +- [redis](https://github.com/log4js-node/redis) +- [slack](https://github.com/log4js-node/slack) +- [smtp](https://github.com/log4js-node/smtp) For example, if you were previously using the gelf appender (`type: 'gelf'`) then you should add `@log4js-node/gelf` to your dependencies and change the type to `type: '@log4js-node/gelf'`. ## Other Appenders These appenders are maintained by its own authors and may be useful for you: -* [udp](https://github.com/iassasin/log4js-udp-appender) + +- [udp](https://github.com/iassasin/log4js-udp-appender) ## Custom Appenders Log4js can load appenders from outside the core appenders. The `type` config value is used as a require path if no matching appender can be found. For example, the following configuration will attempt to load an appender from the module 'cheese/appender', passing the rest of the config for the appender to that module: + ```javascript log4js.configure({ - appenders: { gouda: { type: 'cheese/appender', flavour: 'tasty' } }, - categories: { default: { appenders: ['gouda'], level: 'debug' }} + appenders: { gouda: { type: "cheese/appender", flavour: "tasty" } }, + categories: { default: { appenders: ["gouda"], level: "debug" } }, }); ``` + Log4js checks the following places (in this order) for appenders based on the type value: + 1. The core appenders: `require('./appenders/' + type)` 2. node_modules: `require(type)` 3. relative to the main file of your application: `require(path.dirname(require.main.filename) + '/' + type)` @@ -76,14 +82,18 @@ Log4js checks the following places (in this order) for appenders based on the ty If you want to write your own appender, read the [documentation](writing-appenders.md) first. ## Advanced configuration + If you've got a custom appender of your own, or are using webpack (or some other bundler), you may find it easier to pass in the appender module in the config instead of loading from the node.js require path. Here's an example: + ```javascript const myAppenderModule = { - configure: (config, layouts, findAppender, levels) => { /* ...your appender config... */ } + configure: (config, layouts, findAppender, levels) => { + /* ...your appender config... */ + }, }; log4js.configure({ appenders: { custom: { type: myAppenderModule } }, - categories: { default: { appenders: ['custom'], level: 'debug' } } + categories: { default: { appenders: ["custom"], level: "debug" } }, }); ``` diff --git a/docs/assets/css/style.scss b/docs/assets/css/style.scss index 94dc5fd9..6cf088a4 100644 --- a/docs/assets/css/style.scss +++ b/docs/assets/css/style.scss @@ -8,7 +8,7 @@ header ul { height: auto; padding: 0; list-style: disc; - clear:both; + clear: both; margin-left: 20px; } diff --git a/docs/categories.md b/docs/categories.md index 8372a4ff..ed16e0de 100644 --- a/docs/categories.md +++ b/docs/categories.md @@ -1,55 +1,64 @@ # Categories + Categories are groups of log events. The category for log events is defined when you get a _Logger_ from log4js (`log4js.getLogger('somecategory')`). Log events with the same _category_ will go to the same _appenders_. ## Default configuration + When defining your appenders through a configuration, at least one category must be defined. ```javascript -const log4js = require('log4js'); +const log4js = require("log4js"); log4js.configure({ appenders: { - out: { type: 'stdout' }, - app: { type: 'file', filename: 'application.log' } + out: { type: "stdout" }, + app: { type: "file", filename: "application.log" }, }, categories: { - default: { appenders: [ 'out' ], level: 'trace' }, - app: { appenders: ['app'], level: 'trace' } - } + default: { appenders: ["out"], level: "trace" }, + app: { appenders: ["app"], level: "trace" }, + }, }); const logger = log4js.getLogger(); -logger.trace('This will use the default category and go to stdout'); -const logToFile = log4js.getLogger('app'); -logToFile.trace('This will go to a file'); +logger.trace("This will use the default category and go to stdout"); +const logToFile = log4js.getLogger("app"); +logToFile.trace("This will go to a file"); ``` ## Categories inheritance -Log4js supports a hierarchy for categories, using dots to separate layers - for example, log events in the category 'myapp.submodule' will use the level for 'myapp' if none is defined for 'myapp.submodule', and also any appenders defined for 'myapp'. -This behaviour can be disabled by setting inherit=false on the sub-category. + +Log4js supports a hierarchy for categories, using dots to separate layers - for example, log events in the category 'myapp.submodule' will use the level for 'myapp' if none is defined for 'myapp.submodule', and also any appenders defined for 'myapp'. +This behaviour can be disabled by setting inherit=false on the sub-category. ```javascript -const log4js = require('log4js'); +const log4js = require("log4js"); log4js.configure({ appenders: { - console: { type: 'console' }, - app: { type: 'file', filename: 'application.log' } + console: { type: "console" }, + app: { type: "file", filename: "application.log" }, }, categories: { - default: { appenders: [ 'console' ], level: 'trace' }, - catA: { appenders: ['console'], level: 'error' }, - 'catA.catB': { appenders: ['app'], level: 'trace' }, - } + default: { appenders: ["console"], level: "trace" }, + catA: { appenders: ["console"], level: "error" }, + "catA.catB": { appenders: ["app"], level: "trace" }, + }, }); -const loggerA = log4js.getLogger('catA'); -loggerA.error('This will be written to console with log level ERROR'); -loggerA.trace('This will not be written'); -const loggerAB = log4js.getLogger('catA.catB'); -loggerAB.error('This will be written with log level ERROR to console and to a file'); -loggerAB.trace('This will be written with log level TRACE to console and to a file'); +const loggerA = log4js.getLogger("catA"); +loggerA.error("This will be written to console with log level ERROR"); +loggerA.trace("This will not be written"); +const loggerAB = log4js.getLogger("catA.catB"); +loggerAB.error( + "This will be written with log level ERROR to console and to a file" +); +loggerAB.trace( + "This will be written with log level TRACE to console and to a file" +); ``` + Two categories are defined: + - Log events with category 'catA' will go to appender 'console' only. -- Log events with category 'catA.catB' will go to appenders 'console' and 'app'. +- Log events with category 'catA.catB' will go to appenders 'console' and 'app'. Appenders will see and log an event only if the category level is less than or equal to the event's level. diff --git a/docs/categoryFilter.md b/docs/categoryFilter.md index 20e4cf87..e9c3aaee 100644 --- a/docs/categoryFilter.md +++ b/docs/categoryFilter.md @@ -4,44 +4,50 @@ This is not strictly an appender - it wraps around another appender and stops lo ## Configuration -* `type` - `"categoryFilter"` -* `exclude` - `string | Array` - the category (or categories if you provide an array of values) that will be excluded from the appender. -* `appender` - `string` - the name of the appender to filter. +- `type` - `"categoryFilter"` +- `exclude` - `string | Array` - the category (or categories if you provide an array of values) that will be excluded from the appender. +- `appender` - `string` - the name of the appender to filter. ## Example ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' }, - 'no-noise': { type: 'categoryFilter', exclude: 'noisy.component', appender: 'everything' } + everything: { type: "file", filename: "all-the-logs.log" }, + "no-noise": { + type: "categoryFilter", + exclude: "noisy.component", + appender: "everything", + }, }, categories: { - default: { appenders: [ 'no-noise' ], level: 'debug' } - } + default: { appenders: ["no-noise"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -const noisyLogger = log4js.getLogger('noisy.component'); -logger.debug('I will be logged in all-the-logs.log'); -noisyLogger.debug('I will not be logged.'); +const noisyLogger = log4js.getLogger("noisy.component"); +logger.debug("I will be logged in all-the-logs.log"); +noisyLogger.debug("I will not be logged."); ``` Note that you can achieve the same outcome without using the category filter, like this: + ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' } + everything: { type: "file", filename: "all-the-logs.log" }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug' }, - 'noisy.component': { appenders: ['everything'], level: 'off' } - } + default: { appenders: ["everything"], level: "debug" }, + "noisy.component": { appenders: ["everything"], level: "off" }, + }, }); const logger = log4js.getLogger(); -const noisyLogger = log4js.getLogger('noisy.component'); -logger.debug('I will be logged in all-the-logs.log'); -noisyLogger.debug('I will not be logged.'); +const noisyLogger = log4js.getLogger("noisy.component"); +logger.debug("I will be logged in all-the-logs.log"); +noisyLogger.debug("I will not be logged."); ``` + Category filter becomes useful when you have many categories you want to exclude, passing them as an array. diff --git a/docs/clustering.md b/docs/clustering.md index 31cb9e74..6696bdb6 100644 --- a/docs/clustering.md +++ b/docs/clustering.md @@ -5,17 +5,21 @@ If you're running log4js in an application that uses [node's core cluster](https This can cause problems in some rare circumstances, if you're experiencing weird logging problems, then use the `disableClustering: true` option in your log4js configuration to have every process behave as if it were the master process. Be careful if you're logging to files. ## I'm using PM2, but I'm not getting any logs! + To get log4js working with [PM2](http://pm2.keymetrics.io), you'll need to install the [pm2-intercom](https://www.npmjs.com/package/pm2-intercom) module. + ```bash pm2 install pm2-intercom ``` + Then add the value `pm2: true` to your log4js configuration. If you're also using `node-config`, then you'll probably have renamed your `NODE_APP_INSTANCE` environment variable. If so, you'll also need to add `pm2InstanceVar: ''` where `` should be replaced with the new name you gave the instance environment variable. + ```javascript log4js.configure({ - appenders: { out: { type: 'stdout'}}, - categories: { default: { appenders: ['out'], level: 'info'}}, + appenders: { out: { type: "stdout" } }, + categories: { default: { appenders: ["out"], level: "info" } }, pm2: true, - pm2InstanceVar: 'INSTANCE_ID' + pm2InstanceVar: "INSTANCE_ID", }); ``` diff --git a/docs/connect-logger.md b/docs/connect-logger.md index d7f428da..e63e420a 100644 --- a/docs/connect-logger.md +++ b/docs/connect-logger.md @@ -3,30 +3,31 @@ The connect/express logger was added to log4js by [danbell](https://github.com/danbell). This allows connect/express servers to log using log4js. See `example-connect-logger.js`. ```javascript -var log4js = require('log4js'); -var express = require('express'); +var log4js = require("log4js"); +var express = require("express"); log4js.configure({ - appenders: { - console: { type: 'console' }, - file: { type: 'file', filename: 'cheese.log' } - }, - categories: { - cheese: { appenders: ['file'], level: 'info' }, - default: { appenders: ['console'], level: 'info' } - } + appenders: { + console: { type: "console" }, + file: { type: "file", filename: "cheese.log" }, + }, + categories: { + cheese: { appenders: ["file"], level: "info" }, + default: { appenders: ["console"], level: "info" }, + }, }); -var logger = log4js.getLogger('cheese'); +var logger = log4js.getLogger("cheese"); var app = express(); -app.use(log4js.connectLogger(logger, { level: 'info' })); -app.get('/', function(req,res) { - res.send('hello world'); +app.use(log4js.connectLogger(logger, { level: "info" })); +app.get("/", function (req, res) { + res.send("hello world"); }); app.listen(5000); ``` The log4js.connectLogger supports the passing of an options object that can be used to set the following: + - log level - log format string or function (the same as the connect/express logger) - nolog expressions (represented as a string, regexp, or array) @@ -35,54 +36,77 @@ The log4js.connectLogger supports the passing of an options object that can be u For example: ```javascript -app.use(log4js.connectLogger(logger, { level: log4js.levels.INFO, format: ':method :url' })); +app.use( + log4js.connectLogger(logger, { + level: log4js.levels.INFO, + format: ":method :url", + }) +); ``` or: ```javascript -app.use(log4js.connectLogger(logger, { - level: 'auto', - // include the Express request ID in the logs - format: (req, res, format) => format(`:remote-addr - ${req.id} - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"`) -})); +app.use( + log4js.connectLogger(logger, { + level: "auto", + // include the Express request ID in the logs + format: (req, res, format) => + format( + `:remote-addr - ${req.id} - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"` + ), + }) +); ``` When you request of POST, you want to log the request body parameter like JSON. The log format function is very useful. Please use log format function instead "tokens" property for use express's request or response. - ```javascript -app.use(log4js.connectLogger(logger, { - level: 'info', - format: (req, res, format) => format(`:remote-addr :method :url ${JSON.stringify(req.body)}`) -})); +app.use( + log4js.connectLogger(logger, { + level: "info", + format: (req, res, format) => + format(`:remote-addr :method :url ${JSON.stringify(req.body)}`), + }) +); ``` Added automatic level detection to connect-logger, depends on http status response, compatible with express 3.x and 4.x. -* http responses 3xx, level = WARN -* http responses 4xx & 5xx, level = ERROR -* else, level = INFO +- http responses 3xx, level = WARN +- http responses 4xx & 5xx, level = ERROR +- else, level = INFO ```javascript -app.use(log4js.connectLogger(logger, { level: 'auto' })); +app.use(log4js.connectLogger(logger, { level: "auto" })); ``` The levels of returned status codes can be configured via status code rulesets. ```javascript -app.use(log4js.connectLogger(logger, { level: 'auto', statusRules: [ - { from: 200, to: 299, level: 'debug' }, - { codes: [303, 304], level: 'info' } -]})); +app.use( + log4js.connectLogger(logger, { + level: "auto", + statusRules: [ + { from: 200, to: 299, level: "debug" }, + { codes: [303, 304], level: "info" }, + ], + }) +); ``` The log4js.connectLogger also supports a nolog option where you can specify a string, regexp, or array to omit certain log messages. Example of 1.2 below. ```javascript -app.use(log4js.connectLogger(logger, { level: 'auto', format: ':method :url', nolog: '\\.gif|\\.jpg$' })); +app.use( + log4js.connectLogger(logger, { + level: "auto", + format: ":method :url", + nolog: "\\.gif|\\.jpg$", + }) +); ``` The log4js.connectLogger can add a response of express to context if `context` flag is set to `true`. @@ -97,20 +121,23 @@ app.use(log4js.connectLogger(logger, { context: true })); In layout: ```javascript -log4js.addLayout('customLayout', () => { +log4js.addLayout("customLayout", () => { return (loggingEvent) => { const res = loggingEvent.context.res; - return util.format(...loggingEvent.data, res ? `status: ${res.statusCode}` : ''); + return util.format( + ...loggingEvent.data, + res ? `status: ${res.statusCode}` : "" + ); }; }); ``` ## Example nolog values -| nolog value | Will Not Log | Will Log | -|-------------|--------------|----------| -| `"\\.gif"` | http://example.com/hoge.gif http://example.com/hoge.gif?fuga | http://example.com/hoge.agif | -| `"\\.gif\|\\.jpg$"` | http://example.com/hoge.gif http://example.com/hoge.gif?fuga http://example.com/hoge.jpg?fuga | http://example.com/hoge.agif http://example.com/hoge.ajpg http://example.com/hoge.jpg?hoge | -| `"\\.(gif\|jpe?g\|png)$"` | http://example.com/hoge.gif http://example.com/hoge.jpeg | http://example.com/hoge.gif?uid=2 http://example.com/hoge.jpg?pid=3 | -| `/\.(gif\|jpe?g\|png)$/` | as above | as above | -| `["\\.jpg$", "\\.png", "\\.gif"]` | same as `"\\.jpg\|\\.png\|\\.gif"` | same as `"\\.jpg\|\\.png\|\\.gif"` | +| nolog value | Will Not Log | Will Log | +| --------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | +| `"\\.gif"` | http://example.com/hoge.gif http://example.com/hoge.gif?fuga | http://example.com/hoge.agif | +| `"\\.gif\|\\.jpg$"` | http://example.com/hoge.gif http://example.com/hoge.gif?fuga http://example.com/hoge.jpg?fuga | http://example.com/hoge.agif http://example.com/hoge.ajpg http://example.com/hoge.jpg?hoge | +| `"\\.(gif\|jpe?g\|png)$"` | http://example.com/hoge.gif http://example.com/hoge.jpeg | http://example.com/hoge.gif?uid=2 http://example.com/hoge.jpg?pid=3 | +| `/\.(gif\|jpe?g\|png)$/` | as above | as above | +| `["\\.jpg$", "\\.png", "\\.gif"]` | same as `"\\.jpg\|\\.png\|\\.gif"` | same as `"\\.jpg\|\\.png\|\\.gif"` | diff --git a/docs/console.md b/docs/console.md index 8fb84b33..abce5ac3 100644 --- a/docs/console.md +++ b/docs/console.md @@ -4,15 +4,16 @@ This appender uses node's console object to write log events. It can also be use # Configuration -* `type` - `console` -* `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) +- `type` - `console` +- `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) Note that all log events are output using `console.log` regardless of the event's level (so `ERROR` events will not be logged using `console.error`). # Example + ```javascript log4js.configure({ - appenders: { console: { type: 'console' } }, - categories: { default: { appenders: [ 'console' ], level: 'info' } } + appenders: { console: { type: "console" } }, + categories: { default: { appenders: ["console"], level: "info" } }, }); ``` diff --git a/docs/contrib-guidelines.md b/docs/contrib-guidelines.md index 07f8c9d2..67a55615 100644 --- a/docs/contrib-guidelines.md +++ b/docs/contrib-guidelines.md @@ -2,7 +2,7 @@ I love pull requests, and I need all the help I can get. However, there are a few rules to follow if you want a better chance of having your pull request merged: -* Fork the repo, make a feature branch just for your changes -* On the branch, only commit changes for the feature you're adding. Each pull request should concentrate on a single change - don't mix multiple features. -* Your feature should be covered by tests. Run the tests with npm test. This is very important - without tests, your feature may be broken by subsequent changes and I may never know. Plus it's always nice to know that your changes work :-) -* Don't bump the npm version - yours may not be the only feature that makes it into a version, and you don't know when your pull request may get merged (the version may have changed by then). +- Fork the repo, make a feature branch just for your changes +- On the branch, only commit changes for the feature you're adding. Each pull request should concentrate on a single change - don't mix multiple features. +- Your feature should be covered by tests. Run the tests with npm test. This is very important - without tests, your feature may be broken by subsequent changes and I may never know. Plus it's always nice to know that your changes work :-) +- Don't bump the npm version - yours may not be the only feature that makes it into a version, and you don't know when your pull request may get merged (the version may have changed by then). diff --git a/docs/contributors.md b/docs/contributors.md index ab719ce0..edac88f6 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -1,6 +1,6 @@ # Contributors -Many people have helped make log4js what it is today. Here's a list of everyone who has contributed to the code. There are lots of people who've helped by submitting bug reports or pull requests that I haven't merged, but I have used their ideas to implement a different way. Thanks to you all. This library also owes a huge amount to the [original log4js project](https://github.com/stritti/log4js). If you'd like to help out, take a look at the [contributor guidelines](contrib-guidelines.md). +Many people have helped make log4js what it is today. Here's a list of everyone who has contributed to the code. There are lots of people who've helped by submitting bug reports or pull requests that I haven't merged, but I have used their ideas to implement a different way. Thanks to you all. This library also owes a huge amount to the [original log4js project](https://github.com/stritti/log4js). If you'd like to help out, take a look at the [contributor guidelines](contrib-guidelines.md).
    {% for contributor in site.github.contributors %} diff --git a/docs/dateFile.md b/docs/dateFile.md index 6ec289f4..35eea3c4 100644 --- a/docs/dateFile.md +++ b/docs/dateFile.md @@ -4,67 +4,75 @@ This is a file appender that rolls log files based on a configurable time, rathe ## Configuration -* `type` - `"dateFile"` -* `filename` - `string` - the path of the file where you want your logs written. -* `pattern` - `string` (optional, defaults to `yyyy-MM-dd`) - the pattern to use to determine when to roll the logs. -* `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) +- `type` - `"dateFile"` +- `filename` - `string` - the path of the file where you want your logs written. +- `pattern` - `string` (optional, defaults to `yyyy-MM-dd`) - the pattern to use to determine when to roll the logs. +- `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) Any other configuration parameters will be passed to the underlying [streamroller](https://github.com/nomiddlename/streamroller) implementation (see also node.js core file streams): -* `encoding` - `string` (default "utf-8") -* `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) -* `flags` - `string` (default 'a' - [node.js file flags](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_system_flags)) -* `compress` - `boolean` (default false) - compress the backup files using gzip (backup files will have `.gz` extension) -* `keepFileExt` - `boolean` (default false) - preserve the file extension when rotating log files (`file.log` becomes `file.2017-05-30.log` instead of `file.log.2017-05-30`). -* `fileNameSep` - `string` (default '.') - the filename separator when rolling. e.g.: abc.log`.`2013-08-30 or abc`.`2013-08-30.log (keepFileExt) -* `alwaysIncludePattern` - `boolean` (default false) - include the pattern in the name of the current log file. -* `numBackups` - `integer` (default 1) - the number of old files that matches the pattern to keep (excluding the hot file). + +- `encoding` - `string` (default "utf-8") +- `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) +- `flags` - `string` (default 'a' - [node.js file flags](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_system_flags)) +- `compress` - `boolean` (default false) - compress the backup files using gzip (backup files will have `.gz` extension) +- `keepFileExt` - `boolean` (default false) - preserve the file extension when rotating log files (`file.log` becomes `file.2017-05-30.log` instead of `file.log.2017-05-30`). +- `fileNameSep` - `string` (default '.') - the filename separator when rolling. e.g.: abc.log`.`2013-08-30 or abc`.`2013-08-30.log (keepFileExt) +- `alwaysIncludePattern` - `boolean` (default false) - include the pattern in the name of the current log file. +- `numBackups` - `integer` (default 1) - the number of old files that matches the pattern to keep (excluding the hot file). The `pattern` is used to determine when the current log file should be renamed and a new log file created. For example, with a filename of 'cheese.log', and the default pattern of `.yyyy-MM-dd` - on startup this will result in a file called `cheese.log` being created and written to until the next write after midnight. When this happens, `cheese.log` will be renamed to `cheese.log.2017-04-30` and a new `cheese.log` file created. The appender uses the [date-format](https://github.com/nomiddlename/date-format) library to parse the `pattern`, and any of the valid formats can be used. Also note that there is no timer controlling the log rolling - changes in the pattern are determined on every log write. If no writes occur, then no log rolling will happen. If your application logs infrequently this could result in no log file being written for a particular time period. Note that, from version 4.x of log4js onwards, the file appender can take any of the options for the [file appender](file.md) as well. So you could roll files by both date and size. - ## Example (default daily log rolling) ```javascript log4js.configure({ appenders: { - everything: { type: 'dateFile', filename: 'all-the-logs.log' } + everything: { type: "dateFile", filename: "all-the-logs.log" }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug' } - } + default: { appenders: ["everything"], level: "debug" }, + }, }); ``` This example will result in files being rolled every day. The initial file will be `all-the-logs.log`, with the daily backups being `all-the-logs.log.2017-04-30`, etc. ## Example with hourly log rolling (and compressed backups) + ```javascript log4js.configure({ appenders: { - everything: { type: 'dateFile', filename: 'all-the-logs.log', pattern: 'yyyy-MM-dd-hh', compress: true } + everything: { + type: "dateFile", + filename: "all-the-logs.log", + pattern: "yyyy-MM-dd-hh", + compress: true, + }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug'} - } + default: { appenders: ["everything"], level: "debug" }, + }, }); ``` + This will result in one current log file (`all-the-logs.log`). Every hour this file will be compressed and renamed to `all-the-logs.log.2017-04-30-08.gz` (for example) and a new `all-the-logs.log` created. ## Memory usage If your application logs a large volume of messages, and find memory usage increasing due to buffering log messages before being written to a file, then you can listen for "log4js:pause" events emitted by the file appenders. Your application should stop logging when it receives one of these events with a value of `true` and resume when it receives an event with a value of `false`. + ```javascript log4js.configure({ appenders: { - output: { type: 'dateFile', filename: 'out.log' } + output: { type: "dateFile", filename: "out.log" }, }, - categories: { default: { appenders: ['output'], level: 'debug'}} + categories: { default: { appenders: ["output"], level: "debug" } }, }); let paused = false; -process.on("log4js:pause", (value) => paused = value); +process.on("log4js:pause", (value) => (paused = value)); const logger = log4js.getLogger(); while (!paused) { diff --git a/docs/faq.md b/docs/faq.md index 9730a496..667f8691 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -3,23 +3,27 @@ ## I want errors to go to a special file, but still want everything written to another file - how do I do that? You'll need to use the [logLevelFilter](logLevelFilter.md). Here's an example configuration: + ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' }, - emergencies: { type: 'file', filename: 'oh-no-not-again.log' }, - 'just-errors': { type: 'logLevelFilter', appender: 'emergencies', level: 'error' } + everything: { type: "file", filename: "all-the-logs.log" }, + emergencies: { type: "file", filename: "oh-no-not-again.log" }, + "just-errors": { + type: "logLevelFilter", + appender: "emergencies", + level: "error", + }, }, categories: { - default: { appenders: ['just-errors', 'everything'], level: 'debug' } - } + default: { appenders: ["just-errors", "everything"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('This goes to all-the-logs.log'); -logger.info('As does this.'); -logger.error('This goes to all-the-logs.log and oh-no-not-again.log'); - +logger.debug("This goes to all-the-logs.log"); +logger.info("As does this."); +logger.error("This goes to all-the-logs.log and oh-no-not-again.log"); ``` ## I want to reload the configuration when I change my config file - how do I do that? @@ -29,6 +33,7 @@ Previous versions of log4js used to watch for changes in the configuration file ## What happened to `replaceConsole` - it doesn't work any more? I removed `replaceConsole` - it caused a few weird errors, and I wasn't entirely comfortable with messing around with a core part of node. If you still want to do this, then code like this should do the trick: + ```javascript log4js.configure(...); // set up your categories and appenders const logger = log4js.getLogger('console'); @@ -46,25 +51,29 @@ Nodemailer version 4.0.1 (the not-deprecated version) requires a node version >= ## I want line numbers in my logs! You need to enable call stack for the category, and use pattern layout to output the values. e.g. + ```javascript -const log4js = require('log4js'); +const log4js = require("log4js"); log4js.configure({ appenders: { out: { - type: 'stdout', + type: "stdout", layout: { - type: 'pattern', pattern: '%d %p %c %f:%l %m%n' - } - } + type: "pattern", + pattern: "%d %p %c %f:%l %m%n", + }, + }, }, categories: { - default: { appenders: ['out'], level: 'info', enableCallStack: true } - } + default: { appenders: ["out"], level: "info", enableCallStack: true }, + }, }); -const logger = log4js.getLogger('thing'); -logger.info('this should give me a line number now'); +const logger = log4js.getLogger("thing"); +logger.info("this should give me a line number now"); ``` + Would output something like this: + ```bash 2019-05-22T08:41:07.312 INFO thing index.js:16 this should give me a line number now ``` diff --git a/docs/file.md b/docs/file.md index f576ee41..b3abfda0 100644 --- a/docs/file.md +++ b/docs/file.md @@ -4,20 +4,21 @@ The file appender writes log events to a file. It supports an optional maximum f ## Configuration -* `type` - `"file"` -* `filename` - `string` - the path of the file where you want your logs written. -* `maxLogSize` - `integer` (optional, defaults to undefined) - the maximum size (in bytes) for the log file. If not specified or 0, then no log rolling will happen. - `maxLogSize` can also accept `string` with the size suffixes: ***K***, ***M***, ***G*** such as `1K`, `1M`, `1G`. -* `backups` - `integer` (optional, defaults to 5) - the number of old log files to keep during log rolling (excluding the hot file). -* `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) +- `type` - `"file"` +- `filename` - `string` - the path of the file where you want your logs written. +- `maxLogSize` - `integer` (optional, defaults to undefined) - the maximum size (in bytes) for the log file. If not specified or 0, then no log rolling will happen. + `maxLogSize` can also accept `string` with the size suffixes: **_K_**, **_M_**, **_G_** such as `1K`, `1M`, `1G`. +- `backups` - `integer` (optional, defaults to 5) - the number of old log files to keep during log rolling (excluding the hot file). +- `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) Any other configuration parameters will be passed to the underlying [streamroller](https://github.com/nomiddlename/streamroller) implementation (see also node.js core file streams): -* `encoding` - `string` (default "utf-8") -* `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) -* `flags` - `string` (default 'a' - [node.js file flags](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_system_flags)) -* `compress` - `boolean` (default false) - compress the backup files using gzip (backup files will have `.gz` extension) -* `keepFileExt` - `boolean` (default false) - preserve the file extension when rotating log files (`file.log` becomes `file.1.log` instead of `file.log.1`). -* `fileNameSep` - `string` (default '.') - the filename separator when rolling. e.g.: abc.log`.`1 or abc`.`1.log (keepFileExt) + +- `encoding` - `string` (default "utf-8") +- `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) +- `flags` - `string` (default 'a' - [node.js file flags](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_system_flags)) +- `compress` - `boolean` (default false) - compress the backup files using gzip (backup files will have `.gz` extension) +- `keepFileExt` - `boolean` (default false) - preserve the file extension when rotating log files (`file.log` becomes `file.1.log` instead of `file.log.1`). +- `fileNameSep` - `string` (default '.') - the filename separator when rolling. e.g.: abc.log`.`1 or abc`.`1.log (keepFileExt) Note that, from version 4.x of log4js onwards, the file appender can take any of the options for the [dateFile appender](dateFile.md) as well. So you could roll files by both date and size. @@ -26,45 +27,54 @@ Note that, from version 4.x of log4js onwards, the file appender can take any of ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' } + everything: { type: "file", filename: "all-the-logs.log" }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug' } - } + default: { appenders: ["everything"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('I will be logged in all-the-logs.log'); +logger.debug("I will be logged in all-the-logs.log"); ``` This example will result in a single log file (`all-the-logs.log`) containing the log messages. ## Example with log rolling (and compressed backups) + ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log', maxLogSize: 10485760, backups: 3, compress: true } + everything: { + type: "file", + filename: "all-the-logs.log", + maxLogSize: 10485760, + backups: 3, + compress: true, + }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug'} - } + default: { appenders: ["everything"], level: "debug" }, + }, }); ``` + This will result in one current log file (`all-the-logs.log`). When that reaches 10Mb in size, it will be renamed and compressed to `all-the-logs.log.1.gz` and a new file opened called `all-the-logs.log`. When `all-the-logs.log` reaches 10Mb again, then `all-the-logs.log.1.gz` will be renamed to `all-the-logs.log.2.gz`, and so on. ## Memory usage -If your application logs a large volume of messages, and find memory usage increasing due to buffering log messages before being written to a file, then you can listen for "log4js:pause" events emitted by the file appenders. Your application should stop logging when it receives one of these events with a value of `true` and resume when it receives an event with a value of `false`. +If your application logs a large volume of messages, and find memory usage increasing due to buffering log messages before being written to a file, then you can listen for "log4js:pause" events emitted by the file appenders. Your application should stop logging when it receives one of these events with a value of `true` and resume when it receives an event with a value of `false`. + ```javascript log4js.configure({ appenders: { - output: { type: 'file', filename: 'out.log' } + output: { type: "file", filename: "out.log" }, }, - categories: { default: { appenders: ['output'], level: 'debug'}} + categories: { default: { appenders: ["output"], level: "debug" } }, }); let paused = false; -process.on("log4js:pause", (value) => paused = value); +process.on("log4js:pause", (value) => (paused = value)); const logger = log4js.getLogger(); while (!paused) { diff --git a/docs/fileSync.md b/docs/fileSync.md index a8f75c0b..a3ca50fc 100644 --- a/docs/fileSync.md +++ b/docs/fileSync.md @@ -4,45 +4,53 @@ The sync file appender writes log events to a file, the only difference to the n ## Configuration -* `type` - `"fileSync"` -* `filename` - `string` - the path of the file where you want your logs written. -* `maxLogSize` - `integer` (optional, defaults to undefined) - the maximum size (in bytes) for the log file. If not specified or 0, then no log rolling will happen. - `maxLogSize` can also accept `string` with the size suffixes: ***K***, ***M***, ***G*** such as `1K`, `1M`, `1G`. -* `backups` - `integer` (optional, defaults to 5) - the number of old log files to keep during log rolling (excluding the hot file). -* `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) +- `type` - `"fileSync"` +- `filename` - `string` - the path of the file where you want your logs written. +- `maxLogSize` - `integer` (optional, defaults to undefined) - the maximum size (in bytes) for the log file. If not specified or 0, then no log rolling will happen. + `maxLogSize` can also accept `string` with the size suffixes: **_K_**, **_M_**, **_G_** such as `1K`, `1M`, `1G`. +- `backups` - `integer` (optional, defaults to 5) - the number of old log files to keep during log rolling (excluding the hot file). +- `layout` - (optional, defaults to basic layout) - see [layouts](layouts.md) Any other configuration parameters will be passed to the underlying node.js core stream implementation: -* `encoding` - `string` (default "utf-8") -* `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) -* `flags` - `string` (default 'a') + +- `encoding` - `string` (default "utf-8") +- `mode` - `integer` (default 0o600 - [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)) +- `flags` - `string` (default 'a') ## Example ```javascript log4js.configure({ appenders: { - everything: { type: 'fileSync', filename: 'all-the-logs.log' } + everything: { type: "fileSync", filename: "all-the-logs.log" }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug' } - } + default: { appenders: ["everything"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('I will be logged in all-the-logs.log'); +logger.debug("I will be logged in all-the-logs.log"); ``` This example will result in a single log file (`all-the-logs.log`) containing the log messages. ## Example with log rolling + ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log', maxLogSize: 10458760, backups: 3 } + everything: { + type: "file", + filename: "all-the-logs.log", + maxLogSize: 10458760, + backups: 3, + }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug'} - } + default: { appenders: ["everything"], level: "debug" }, + }, }); ``` + This will result in one current log file (`all-the-logs.log`). When that reaches 10Mb in size, it will be renamed and compressed to `all-the-logs.log.1.gz` and a new file opened called `all-the-logs.log`. When `all-the-logs.log` reaches 10Mb again, then `all-the-logs.log.1.gz` will be renamed to `all-the-logs.log.2.gz`, and so on. diff --git a/docs/layouts.md b/docs/layouts.md index c3ae8d13..5a8964dc 100644 --- a/docs/layouts.md +++ b/docs/layouts.md @@ -9,171 +9,203 @@ For most use cases you will not need to configure layouts - there are some appen Most appender configuration will take a field called `layout`, which is an object - typically with a single field `type` which is the name of a layout defined below. Some layouts require extra configuration options, which should be included in the same object. ## Example + ```javascript log4js.configure({ - appenders: { out: { type: 'stdout', layout: { type: 'basic' } } }, - categories: { default: { appenders: ['out'], level: 'info' } } + appenders: { out: { type: "stdout", layout: { type: "basic" } } }, + categories: { default: { appenders: ["out"], level: "info" } }, }); ``` + This configuration replaces the [stdout](stdout.md) appender's default `coloured` layout with `basic` layout. # Built-in Layouts ## Basic -* `type` - `basic` +- `type` - `basic` Basic layout will output the timestamp, level, category, followed by the formatted log event data. ## Example + ```javascript log4js.configure({ - appenders: { 'out': { type: 'stdout', layout: { type: 'basic' } } }, - categories: { default: { appenders: ['out'], level: 'info' } } + appenders: { out: { type: "stdout", layout: { type: "basic" } } }, + categories: { default: { appenders: ["out"], level: "info" } }, }); -const logger = log4js.getLogger('cheese'); -logger.error('Cheese is too ripe!'); +const logger = log4js.getLogger("cheese"); +logger.error("Cheese is too ripe!"); ``` + This will output: + ``` [2017-03-30 07:57:00.113] [ERROR] cheese - Cheese is too ripe! ``` ## Coloured -* `type` - `coloured` (or `colored`) +- `type` - `coloured` (or `colored`) This layout is the same as `basic`, except that the timestamp, level and category will be coloured according to the log event's level (if your terminal/file supports it - if you see some weird characters in your output and no colour then you should probably switch to `basic`). The colours used are: -* `TRACE` - 'blue' -* `DEBUG` - 'cyan' -* `INFO` - 'green' -* `WARN` - 'yellow' -* `ERROR` - 'red' -* `FATAL` - 'magenta' + +- `TRACE` - 'blue' +- `DEBUG` - 'cyan' +- `INFO` - 'green' +- `WARN` - 'yellow' +- `ERROR` - 'red' +- `FATAL` - 'magenta' ## Message Pass-Through -* `type` - `messagePassThrough` + +- `type` - `messagePassThrough` This layout just formats the log event data, and does not output a timestamp, level or category. It is typically used in appenders that serialise the events using a specific format (e.g. [gelf](https://github.com/log4js-node/gelf)). ## Example + ```javascript log4js.configure({ - appenders: { out: { type: 'stdout', layout: { type: 'messagePassThrough' } } }, - categories: { default: { appenders: [ 'out' ], level: 'info' } } + appenders: { + out: { type: "stdout", layout: { type: "messagePassThrough" } }, + }, + categories: { default: { appenders: ["out"], level: "info" } }, }); -const logger = log4js.getLogger('cheese'); -const cheeseName = 'gouda'; -logger.error('Cheese is too ripe! Cheese was: ', cheeseName); +const logger = log4js.getLogger("cheese"); +const cheeseName = "gouda"; +logger.error("Cheese is too ripe! Cheese was: ", cheeseName); ``` + This will output: + ``` Cheese is too ripe! Cheese was: gouda ``` ## Dummy -* `type` - `dummy` +- `type` - `dummy` This layout only outputs the first value in the log event's data. It was added for the [logstashUDP](https://github.com/log4js-node/logstashUDP) appender, and I'm not sure there's much use for it outside that. ## Example + ```javascript log4js.configure({ - appenders: { out: { type: 'stdout', layout: { type: 'dummy' } } }, - categories: { default: { appenders: [ 'out' ], level: 'info' } } + appenders: { out: { type: "stdout", layout: { type: "dummy" } } }, + categories: { default: { appenders: ["out"], level: "info" } }, }); -const logger = log4js.getLogger('cheese'); -const cheeseName = 'gouda'; -logger.error('Cheese is too ripe! Cheese was: ', cheeseName); +const logger = log4js.getLogger("cheese"); +const cheeseName = "gouda"; +logger.error("Cheese is too ripe! Cheese was: ", cheeseName); ``` + This will output: + ``` Cheese is too ripe! Cheese was: ``` ## Pattern -* `type` - `pattern` -* `pattern` - `string` - specifier for the output format, using placeholders as described below -* `tokens` - `object` (optional) - user-defined tokens to be used in the pattern + +- `type` - `pattern` +- `pattern` - `string` - specifier for the output format, using placeholders as described below +- `tokens` - `object` (optional) - user-defined tokens to be used in the pattern ## Pattern format + The pattern string can contain any characters, but sequences beginning with `%` will be replaced with values taken from the log event, and other environmental values. Format for specifiers is `%[padding].[truncation][field]{[format]}` - padding and truncation are optional, and format only applies to a few tokens (notably, date). Both padding and truncation values can be negative. -* Positive truncation - truncate the string starting from the beginning -* Negative truncation - truncate the string starting from the end of the string -* Positive padding - left pad the string to make it this length, if the string is longer than the padding value then nothing happens -* Negative padding - right pad the string to make it this length, if the string is longer than the padding value then nothing happens -To make fixed-width columns in your log output, set padding and truncation to the same size (they don't have to have the same sign though, you could have right truncated, left padded columns that are always 10 characters wide with a pattern like "%10.-10m"). + +- Positive truncation - truncate the string starting from the beginning +- Negative truncation - truncate the string starting from the end of the string +- Positive padding - left pad the string to make it this length, if the string is longer than the padding value then nothing happens +- Negative padding - right pad the string to make it this length, if the string is longer than the padding value then nothing happens + To make fixed-width columns in your log output, set padding and truncation to the same size (they don't have to have the same sign though, you could have right truncated, left padded columns that are always 10 characters wide with a pattern like "%10.-10m"). e.g. %5.10p - left pad the log level by up to 5 characters, keep the whole string to a max length of 10. So, for a log level of INFO the output would be " INFO", for DEBUG it would be "DEBUG" and for a (custom) log level of CATASTROPHIC it would be "CATASTROPH". - Fields can be any of: -* `%r` time in toLocaleTimeString format -* `%p` log level -* `%c` log category -* `%h` hostname -* `%m` log data -* `%d` date, formatted - default is `ISO8601`, format options are: `ISO8601`, `ISO8601_WITH_TZ_OFFSET`, `ABSOLUTETIME`, `DATETIME`, or any string compatible with the [date-format](https://www.npmjs.com/package/date-format) library. e.g. `%d{DATETIME}`, `%d{yyyy/MM/dd-hh.mm.ss}` -* `%%` % - for when you want a literal `%` in your output -* `%n` newline -* `%z` process id (from `process.pid`) -* `%f` full path of filename (requires `enableCallStack: true` on the category, see [configuration object](api.md)) -* `%f{depth}` path's depth let you chose to have only filename (`%f{1}`) or a chosen number of directories -* `%l` line number (requires `enableCallStack: true` on the category, see [configuration object](api.md)) -* `%o` column postion (requires `enableCallStack: true` on the category, see [configuration object](api.md)) -* `%s` call stack (requires `enableCallStack: true` on the category, see [configuration object](api.md)) -* `%x{}` add dynamic tokens to your log. Tokens are specified in the tokens parameter. -* `%X{}` add values from the Logger context. Tokens are keys into the context values. -* `%[` start a coloured block (colour will be taken from the log level, similar to `colouredLayout`) -* `%]` end a coloured block + +- `%r` time in toLocaleTimeString format +- `%p` log level +- `%c` log category +- `%h` hostname +- `%m` log data +- `%d` date, formatted - default is `ISO8601`, format options are: `ISO8601`, `ISO8601_WITH_TZ_OFFSET`, `ABSOLUTETIME`, `DATETIME`, or any string compatible with the [date-format](https://www.npmjs.com/package/date-format) library. e.g. `%d{DATETIME}`, `%d{yyyy/MM/dd-hh.mm.ss}` +- `%%` % - for when you want a literal `%` in your output +- `%n` newline +- `%z` process id (from `process.pid`) +- `%f` full path of filename (requires `enableCallStack: true` on the category, see [configuration object](api.md)) +- `%f{depth}` path's depth let you chose to have only filename (`%f{1}`) or a chosen number of directories +- `%l` line number (requires `enableCallStack: true` on the category, see [configuration object](api.md)) +- `%o` column postion (requires `enableCallStack: true` on the category, see [configuration object](api.md)) +- `%s` call stack (requires `enableCallStack: true` on the category, see [configuration object](api.md)) +- `%x{}` add dynamic tokens to your log. Tokens are specified in the tokens parameter. +- `%X{}` add values from the Logger context. Tokens are keys into the context values. +- `%[` start a coloured block (colour will be taken from the log level, similar to `colouredLayout`) +- `%]` end a coloured block ## Tokens + User-defined tokens can be either a string or a function. Functions will be passed the log event, and should return a string. For example, you could define a custom token that outputs the log event's context value for 'user' like so: + ```javascript log4js.configure({ appenders: { - out: { type: 'stdout', layout: { - type: 'pattern', - pattern: '%d %p %c %x{user} %m%n', - tokens: { - user: function(logEvent) { - return AuthLibrary.currentUser(); - } - } - }} + out: { + type: "stdout", + layout: { + type: "pattern", + pattern: "%d %p %c %x{user} %m%n", + tokens: { + user: function (logEvent) { + return AuthLibrary.currentUser(); + }, + }, + }, + }, }, - categories: { default: { appenders: ['out'], level: 'info' } } + categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger(); -logger.info('doing something.'); +logger.info("doing something."); ``` + This would output: + ``` 2017-06-01 08:32:56.283 INFO default charlie doing something. ``` You can also use the Logger context to store tokens (sometimes called Nested Diagnostic Context, or Mapped Diagnostic Context) and use them in your layouts. + ```javascript log4js.configure({ appenders: { - out: { type: 'stdout', layout: { - type: 'pattern', - pattern: '%d %p %c %X{user} %m%n' - }} + out: { + type: "stdout", + layout: { + type: "pattern", + pattern: "%d %p %c %X{user} %m%n", + }, + }, }, - categories: { default: { appenders: ['out'], level: 'info' } } + categories: { default: { appenders: ["out"], level: "info" } }, }); const logger = log4js.getLogger(); -logger.addContext('user', 'charlie'); -logger.info('doing something.'); +logger.addContext("user", "charlie"); +logger.info("doing something."); ``` + This would output: + ``` 2017-06-01 08:32:56.283 INFO default charlie doing something. ``` + Note that you can also add functions to the Logger Context, and they will be passed the logEvent as well. # Adding your own layouts @@ -181,30 +213,36 @@ Note that you can also add functions to the Logger Context, and they will be pas You can add your own layouts by calling `log4js.addLayout(type, fn)` before calling `log4js.configure`. `type` is the label you want to use to refer to your layout in appender configuration. `fn` is a function that takes a single object argument, which will contain the configuration for the layout instance, and returns a layout function. A layout function takes a log event argument and returns a string (usually, although you could return anything as long as the appender knows what to do with it). ## Custom Layout Example + This example can also be found in examples/custom-layout.js. + ```javascript -const log4js = require('log4js'); +const log4js = require("log4js"); -log4js.addLayout('json', function(config) { - return function(logEvent) { return JSON.stringify(logEvent) + config.separator; } +log4js.addLayout("json", function (config) { + return function (logEvent) { + return JSON.stringify(logEvent) + config.separator; + }; }); log4js.configure({ appenders: { - out: { type: 'stdout', layout: { type: 'json', separator: ',' } } + out: { type: "stdout", layout: { type: "json", separator: "," } }, }, categories: { - default: { appenders: ['out'], level: 'info' } - } + default: { appenders: ["out"], level: "info" }, + }, }); -const logger = log4js.getLogger('json-test'); -logger.info('this is just a test'); -logger.error('of a custom appender'); -logger.warn('that outputs json'); +const logger = log4js.getLogger("json-test"); +logger.info("this is just a test"); +logger.error("of a custom appender"); +logger.warn("that outputs json"); log4js.shutdown(() => {}); ``` + This example outputs the following: + ```javascript {"startTime":"2017-06-05T22:23:08.479Z","categoryName":"json-test","data":["this is just a test"],"level":{"level":20000,"levelStr":"INFO"},"context":{}}, {"startTime":"2017-06-05T22:23:08.483Z","categoryName":"json-test","data":["of a custom appender"],"level":{"level":40000,"levelStr":"ERROR"},"context":{}}, diff --git a/docs/logLevelFilter.md b/docs/logLevelFilter.md index 22956626..fb3cf381 100644 --- a/docs/logLevelFilter.md +++ b/docs/logLevelFilter.md @@ -4,10 +4,10 @@ The log level filter allows you to restrict the log events that an appender will ## Configuration -* `type` - `logLevelFilter` -* `appender` - `string` - the name of an appender, defined in the same configuration, that you want to filter -* `level` - `string` - the minimum level of event to allow through the filter -* `maxLevel` - `string` (optional, defaults to `FATAL`) - the maximum level of event to allow through the filter +- `type` - `logLevelFilter` +- `appender` - `string` - the name of an appender, defined in the same configuration, that you want to filter +- `level` - `string` - the minimum level of event to allow through the filter +- `maxLevel` - `string` (optional, defaults to `FATAL`) - the maximum level of event to allow through the filter If an event's level is greater than or equal to `level` and less than or equal to `maxLevel` then it will be sent to the appender. @@ -25,4 +25,5 @@ log4js.configure({ } }); ``` + Log events of `debug`, `info`, `error`, and `fatal` will go to `all-the-logs.log`. Events of `error` and `fatal` will also go to `panic-now.log`. diff --git a/docs/migration-guide.md b/docs/migration-guide.md index 8be8e4f8..f329d628 100644 --- a/docs/migration-guide.md +++ b/docs/migration-guide.md @@ -1,20 +1,26 @@ # Migrating from log4js versions older than 2.x ## Configuration + If you try to use your v1 configuration with v2 code, you'll most likely get an error that says something like 'must have property "appenders" of type object'. The format of the configuration object has changed (see the [api](api.md) docs for details). The main changes are a need for you to name your appenders, and you also have to define the default category. For example, if your v1 config looked like this: + ```javascript -{ appenders: [ - { type: 'console' }, - { - type: 'dateFile', - filename: 'logs/task', - pattern:"-dd.log", - alwaysIncludePattern: true, - category: 'task' - } -] } +{ + appenders: [ + { type: "console" }, + { + type: "dateFile", + filename: "logs/task", + pattern: "-dd.log", + alwaysIncludePattern: true, + category: "task", + }, + ]; +} ``` + Then your v2 config should be something like this: + ```javascript { appenders: { @@ -36,7 +42,9 @@ Then your v2 config should be something like this: The functions to define the configuration programmatically have been remove (`addAppender`, `loadAppender`, etc). All configuration should now be done through the single `configure` function, passing in a filename or object. ## Console replacement + V1 used to allow you to replace the node.js console functions with versions that would log to a log4js appender. This used to cause some weird errors, so I decided it was better to remove it from the log4js core functionality. If you still want to do this, you can replicate the behaviour with code similar to this: + ```javascript log4js.configure(...); // set up your categories and appenders const logger = log4js.getLogger('console'); // any category will work @@ -44,9 +52,11 @@ console.log = logger.info.bind(logger); // do the same for others - console.debu ``` ## Config Reloading + Previous versions of log4js used to watch for changes in the configuration file and reload when it changed. It didn't always work well, sometimes leaving file handles or sockets open. This feature was removed in version 2.x. As a replacement, I'd suggest using a library like [watchr](https://www.npmjs.com/package/watchr) to notify you of file changes. Then you can call `log4js.shutdown` followed by `log4js.configure` again. ## Appenders + If you have written your own custom appenders, they will not work without modification in v2. See the guide to [writing appenders](writing-appenders.md) for details on how appenders work in 2.x. Note that if you want to write your appender to work with both 1.x and 2.x, then you can tell what version you're running in by examining the number of arguments passed to the `configure` function of your appender: 2 arguments means v1, 4 arguments means v2. All the core appenders have been upgraded to work with v2, except for the clustered appender which has been removed. The core log4js code handles cluster mode transparently. @@ -54,10 +64,12 @@ All the core appenders have been upgraded to work with v2, except for the cluste The `logFaces` appender was split into two versions to make testing easier and the code simpler; one has HTTP support, the other UDP. ## Exit listeners + Some appenders used to define their own `exit` listeners, and it was never clear whose responsibility it was to clean up resources. Now log4js does not define any `exit` listeners. Instead your application should register an `exit` listener, and call `log4js.shutdown` to be sure that all log messages get written before your application terminates. ## New Features -* MDC contexts - you can now add key-value pairs to a logger (for grouping all log messages from a particular user, for example). Support for these values exists in the [pattern layout](layouts.md), the logFaces ([UDP](https://github.com/log4js-node/logFaces-UDP) and [HTTP](https://github.com/log4js-node/logFaces-HTTP)) appender, and the [multi-file appender](multiFile.md). -* Automatic cluster support - log4js now handles clusters transparently -* Custom levels - you can define your own log levels in the configuration object, including the colours -* Improved performance - several changes have been made to improve performance, especially for the file appenders. + +- MDC contexts - you can now add key-value pairs to a logger (for grouping all log messages from a particular user, for example). Support for these values exists in the [pattern layout](layouts.md), the logFaces ([UDP](https://github.com/log4js-node/logFaces-UDP) and [HTTP](https://github.com/log4js-node/logFaces-HTTP)) appender, and the [multi-file appender](multiFile.md). +- Automatic cluster support - log4js now handles clusters transparently +- Custom levels - you can define your own log levels in the configuration object, including the colours +- Improved performance - several changes have been made to improve performance, especially for the file appenders. diff --git a/docs/multiFile.md b/docs/multiFile.md index 17ef00de..c69a04c6 100644 --- a/docs/multiFile.md +++ b/docs/multiFile.md @@ -4,11 +4,11 @@ The multiFile appender can be used to dynamically write logs to multiple files, ## Configuration -* `type` - `"multiFile"` -* `base` - `string` - the base part of the generated log filename -* `property` - `string` - the value to use to split files (see below). -* `extension` - `string` - the suffix for the generated log filename. -* `timeout` - `integer` - optional activity timeout in ms after which the file will be closed. +- `type` - `"multiFile"` +- `base` - `string` - the base part of the generated log filename +- `property` - `string` - the value to use to split files (see below). +- `extension` - `string` - the suffix for the generated log filename. +- `timeout` - `integer` - optional activity timeout in ms after which the file will be closed. All other properties will be passed to the created [file](file.md) appenders. For the property value, `categoryName` is probably the most useful - although you could use `pid` or `level`. If the property is not found then the appender will look for the value in the context map. If that fails, then the logger will not output the logging event, without an error. This is to allow for dynamic properties which may not exist for all log messages. @@ -17,37 +17,49 @@ All other properties will be passed to the created [file](file.md) appenders. Fo ```javascript log4js.configure({ appenders: { - multi: { type: 'multiFile', base: 'logs/', property: 'categoryName', extension: '.log' } + multi: { + type: "multiFile", + base: "logs/", + property: "categoryName", + extension: ".log", + }, }, categories: { - default: { appenders: [ 'multi' ], level: 'debug' } - } + default: { appenders: ["multi"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('I will be logged in logs/default.log'); -const otherLogger = log4js.getLogger('cheese'); -otherLogger.info('Cheese is cheddar - this will be logged in logs/cheese.log'); +logger.debug("I will be logged in logs/default.log"); +const otherLogger = log4js.getLogger("cheese"); +otherLogger.info("Cheese is cheddar - this will be logged in logs/cheese.log"); ``` This example will result in two log files (`logs/default.log` and `logs/cheese.log`) containing the log messages. ## Example with log rolling (and compressed backups) + ```javascript log4js.configure({ appenders: { everything: { - type: 'multiFile', base: 'logs/', property: 'userID', extension: '.log', - maxLogSize: 10485760, backups: 3, compress: true - } + type: "multiFile", + base: "logs/", + property: "userID", + extension: ".log", + maxLogSize: 10485760, + backups: 3, + compress: true, + }, }, categories: { - default: { appenders: [ 'everything' ], level: 'debug'} - } + default: { appenders: ["everything"], level: "debug" }, + }, }); -const userLogger = log4js.getLogger('user'); -userLogger.addContext('userID', user.getID()); -userLogger.info('this user just logged in'); +const userLogger = log4js.getLogger("user"); +userLogger.addContext("userID", user.getID()); +userLogger.info("this user just logged in"); ``` + This will result in one log file (`logs/u12345.log`), capped at 10Mb in size, with three backups kept when rolling the file. If more users were logged, each user would get their own files, and their own backups. diff --git a/docs/multiprocess.md b/docs/multiprocess.md index a3f31e87..f9a1fd7c 100644 --- a/docs/multiprocess.md +++ b/docs/multiprocess.md @@ -1,43 +1,51 @@ # Multiprocess Appender -*You probably want to use the [tcp server](tcp-server.md) or [tcp appender](tcp.md) instead of this - they are more flexible* +_You probably want to use the [tcp server](tcp-server.md) or [tcp appender](tcp.md) instead of this - they are more flexible_ -*Note that if you're just using node core's `cluster` module then you don't need to use this appender - log4js will handle logging within the cluster transparently.* +_Note that if you're just using node core's `cluster` module then you don't need to use this appender - log4js will handle logging within the cluster transparently._ The multiprocess appender sends log events to a master server over TCP sockets. It can be used as a simple way to centralise logging when you have multiple servers or processes. It uses the node.js core networking modules, and so does not require any extra dependencies. Remember to call `log4js.shutdown` when your application terminates, so that the sockets get closed cleanly. - ## Configuration -* `type` - `multiprocess` -* `mode` - `master|worker` - controls whether the appender listens for log events sent over the network, or is responsible for serialising events and sending them to a server. -* `appender` - `string` (only needed if `mode` == `master`)- the name of the appender to send the log events to -* `loggerPort` - `integer` (optional, defaults to `5000`) - the port to listen on, or send to -* `loggerHost` - `string` (optional, defaults to `localhost`) - the host/IP address to listen on, or send to +- `type` - `multiprocess` +- `mode` - `master|worker` - controls whether the appender listens for log events sent over the network, or is responsible for serialising events and sending them to a server. +- `appender` - `string` (only needed if `mode` == `master`)- the name of the appender to send the log events to +- `loggerPort` - `integer` (optional, defaults to `5000`) - the port to listen on, or send to +- `loggerHost` - `string` (optional, defaults to `localhost`) - the host/IP address to listen on, or send to ## Example (master) + ```javascript log4js.configure({ appenders: { - file: { type: 'file', filename: 'all-the-logs.log' }, - server: { type: 'multiprocess', mode: 'master', appender: 'file', loggerHost: '0.0.0.0' } + file: { type: "file", filename: "all-the-logs.log" }, + server: { + type: "multiprocess", + mode: "master", + appender: "file", + loggerHost: "0.0.0.0", + }, }, categories: { - default: { appenders: ['file'], level: 'info' } - } + default: { appenders: ["file"], level: "info" }, + }, }); ``` + This creates a log server listening on port 5000, on all IP addresses the host has assigned to it. Note that the appender is not included in the appenders listed for the categories. Also note that the multiprocess master appender will send every event it receives to the underlying appender, regardless of level settings. ## Example (worker) + ```javascript log4js.configure({ appenders: { - network: { type: 'multiprocess', mode: 'worker', loggerHost: 'log.server' } + network: { type: "multiprocess", mode: "worker", loggerHost: "log.server" }, }, categories: { - default: { appenders: ['network'], level: 'error' } - } + default: { appenders: ["network"], level: "error" }, + }, }); ``` + This will send all error messages to `log.server:5000`. diff --git a/docs/noLogFilter.md b/docs/noLogFilter.md index 3bae39ba..438f62db 100644 --- a/docs/noLogFilter.md +++ b/docs/noLogFilter.md @@ -1,58 +1,61 @@ # Category Filter -The no log filter allows you to exclude the log events that an appender will record. +The no log filter allows you to exclude the log events that an appender will record. The log events will be excluded depending on the regular expressions provided in the configuration. -This can be useful when you debug your application and you want to exclude some noisily logs that are irrelevant to your investigation. -You can stop to log them through a regular expression. +This can be useful when you debug your application and you want to exclude some noisily logs that are irrelevant to your investigation. +You can stop to log them through a regular expression. ## Configuration -* `type` - `"noLogFilter"` -* `exclude` - `string | Array` - the regular expression (or the regular expressions if you provide an array of values) will be used for evaluating the events to pass to the appender. The events, which will match the regular expression, will be excluded and so not logged. -* `appender` - `string` - the name of an appender, defined in the same configuration, that you want to filter. +- `type` - `"noLogFilter"` +- `exclude` - `string | Array` - the regular expression (or the regular expressions if you provide an array of values) will be used for evaluating the events to pass to the appender. The events, which will match the regular expression, will be excluded and so not logged. +- `appender` - `string` - the name of an appender, defined in the same configuration, that you want to filter. ## Example ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' }, - filtered: { - type: 'noLogFilter', - exclude: 'not', - appender: 'everything' } + everything: { type: "file", filename: "all-the-logs.log" }, + filtered: { + type: "noLogFilter", + exclude: "not", + appender: "everything", + }, }, categories: { - default: { appenders: [ 'filtered' ], level: 'debug' } - } + default: { appenders: ["filtered"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('I will be logged in all-the-logs.log'); -logger.debug('I will be not logged in all-the-logs.log'); +logger.debug("I will be logged in all-the-logs.log"); +logger.debug("I will be not logged in all-the-logs.log"); ``` Note that: -* an array of strings can be specified in the configuration -* a case insensitive match will be done -* empty strings will be not considered and so removed from the array of values + +- an array of strings can be specified in the configuration +- a case insensitive match will be done +- empty strings will be not considered and so removed from the array of values ```javascript log4js.configure({ appenders: { - everything: { type: 'file', filename: 'all-the-logs.log' }, - filtered: { - type: 'noLogFilter', - exclude: ['NOT', '\\d', ''], - appender: 'everything' } + everything: { type: "file", filename: "all-the-logs.log" }, + filtered: { + type: "noLogFilter", + exclude: ["NOT", "\\d", ""], + appender: "everything", + }, }, categories: { - default: { appenders: [ 'filtered' ], level: 'debug' } - } + default: { appenders: ["filtered"], level: "debug" }, + }, }); const logger = log4js.getLogger(); -logger.debug('I will be logged in all-the-logs.log'); -logger.debug('I will be not logged in all-the-logs.log'); -logger.debug('A 2nd message that will be excluded in all-the-logs.log'); -``` \ No newline at end of file +logger.debug("I will be logged in all-the-logs.log"); +logger.debug("I will be not logged in all-the-logs.log"); +logger.debug("A 2nd message that will be excluded in all-the-logs.log"); +``` diff --git a/docs/recording.md b/docs/recording.md index 2d38d3fa..b9e8cc01 100644 --- a/docs/recording.md +++ b/docs/recording.md @@ -4,7 +4,7 @@ This appender stores the log events in memory. It is mainly useful for testing ( ## Configuration -* `type` - `recording` +- `type` - `recording` There is no other configuration for this appender. @@ -12,19 +12,19 @@ There is no other configuration for this appender. The array that stores log events is shared across all recording appender instances, and is accessible from the recording module. `require('/appenders/recording')` returns a module with the following functions exported: -* `replay` - returns `Array` - get all the events recorded. -* `playback` - synonym for `replay` -* `reset` - clears the array of events recorded. -* `erase` - synonyms for `reset` +- `replay` - returns `Array` - get all the events recorded. +- `playback` - synonym for `replay` +- `reset` - clears the array of events recorded. +- `erase` - synonyms for `reset` ## Example ```javascript -const recording = require('log4js/lib/appenders/recording'); -const log4js = require('log4js'); +const recording = require("log4js/lib/appenders/recording"); +const log4js = require("log4js"); log4js.configure({ - appenders: { vcr: { type: 'recording' } }, - categories: { default: { appenders: ['vcr'], level: 'info' } } + appenders: { vcr: { type: "recording" } }, + categories: { default: { appenders: ["vcr"], level: "info" } }, }); const logger = log4js.getLogger(); diff --git a/docs/stderr.md b/docs/stderr.md index ee54c192..396b73d3 100644 --- a/docs/stderr.md +++ b/docs/stderr.md @@ -4,14 +4,14 @@ This appender writes all log events to the standard error stream. # Configuration -* `type` - `stderr` -* `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) +- `type` - `stderr` +- `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) # Example ```javascript log4js.configure({ - appenders: { err: { type: 'stderr' } }, - categories: { default: { appenders: ['err'], level: 'ERROR' } } + appenders: { err: { type: "stderr" } }, + categories: { default: { appenders: ["err"], level: "ERROR" } }, }); ``` diff --git a/docs/stdout.md b/docs/stdout.md index e21233e6..e8cd9275 100644 --- a/docs/stdout.md +++ b/docs/stdout.md @@ -4,13 +4,14 @@ This appender writes all log events to the standard output stream. It is the def # Configuration -* `type` - `stdout` -* `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) +- `type` - `stdout` +- `layout` - `object` (optional, defaults to colouredLayout) - see [layouts](layouts.md) # Example + ```javascript log4js.configure({ - appenders: { 'out': { type: 'stdout' } }, - categories: { default: { appenders: ['out'], level: 'info' } } + appenders: { out: { type: "stdout" } }, + categories: { default: { appenders: ["out"], level: "info" } }, }); ``` diff --git a/docs/tcp-server.md b/docs/tcp-server.md index 62a90d94..28f0f786 100644 --- a/docs/tcp-server.md +++ b/docs/tcp-server.md @@ -4,20 +4,22 @@ Strictly speaking, this is not an appender - but it is configured as one. The TC ## Configuration -* `type` - `tcp-server` -* `port` - `integer` (optional, defaults to `5000`) - the port to listen on -* `host` - `string` (optional, defaults to `localhost`) - the host/IP address to listen on +- `type` - `tcp-server` +- `port` - `integer` (optional, defaults to `5000`) - the port to listen on +- `host` - `string` (optional, defaults to `localhost`) - the host/IP address to listen on ## Example (master) + ```javascript log4js.configure({ appenders: { - file: { type: 'file', filename: 'all-the-logs.log' }, - server: { type: 'tcp-server', host: '0.0.0.0' } + file: { type: "file", filename: "all-the-logs.log" }, + server: { type: "tcp-server", host: "0.0.0.0" }, }, categories: { - default: { appenders: ['file'], level: 'info' } - } + default: { appenders: ["file"], level: "info" }, + }, }); ``` + This creates a log server listening on port 5000, on all IP addresses the host has assigned to it. Note that the appender is not included in the appenders listed for the categories. All events received on the socket will be forwarded to the other appenders, as if they had originated on the same server. diff --git a/docs/tcp.md b/docs/tcp.md index 9d5302bd..1a2e70c6 100644 --- a/docs/tcp.md +++ b/docs/tcp.md @@ -4,21 +4,23 @@ The TCP appender sends log events to a master server over TCP sockets. It can be ## Configuration -* `type` - `tcp` -* `port` - `integer` (optional, defaults to `5000`) - the port to send to -* `host` - `string` (optional, defaults to `localhost`) - the host/IP address to send to -* `endMsg` - `string` (optional, defaults to `__LOG4JS__`) - the delimiter that marks the end of a log message -* `layout` - `object` (optional, defaults to a serialized log event) - see [layouts](layouts.md) +- `type` - `tcp` +- `port` - `integer` (optional, defaults to `5000`) - the port to send to +- `host` - `string` (optional, defaults to `localhost`) - the host/IP address to send to +- `endMsg` - `string` (optional, defaults to `__LOG4JS__`) - the delimiter that marks the end of a log message +- `layout` - `object` (optional, defaults to a serialized log event) - see [layouts](layouts.md) ## Example + ```javascript log4js.configure({ appenders: { - network: { type: 'tcp', host: 'log.server' } + network: { type: "tcp", host: "log.server" }, }, categories: { - default: { appenders: ['network'], level: 'error' } - } + default: { appenders: ["network"], level: "error" }, + }, }); ``` + This will send all error messages to `log.server:5000`. diff --git a/docs/terms.md b/docs/terms.md index 5e539db1..dc7371e1 100644 --- a/docs/terms.md +++ b/docs/terms.md @@ -2,7 +2,7 @@ `Level` - a log level is the severity or priority of a log event (debug, info, etc). Whether an _appender_ will see the event or not is determined by the _category_'s level. If this is less than or equal to the event's level, it will be sent to the category's appender(s). -`Category` - a label for grouping log events. This can be based on module (e.g. 'auth', 'payment', 'http'), or anything you like. Log events with the same _category_ will go to the same _appenders_. Log4js supports a hierarchy for categories, using dots to separate layers - for example, log events in the category 'myapp.submodule' will use the level for 'myapp' if none is defined for 'myapp.submodule', and also any appenders defined for 'myapp'. (This behaviour can be disabled by setting inherit=false on the sub-category.) The category for log events is defined when you get a _Logger_ from log4js (`log4js.getLogger('somecategory')`). +`Category` - a label for grouping log events. This can be based on module (e.g. 'auth', 'payment', 'http'), or anything you like. Log events with the same _category_ will go to the same _appenders_. Log4js supports a hierarchy for categories, using dots to separate layers - for example, log events in the category 'myapp.submodule' will use the level for 'myapp' if none is defined for 'myapp.submodule', and also any appenders defined for 'myapp'. (This behaviour can be disabled by setting inherit=false on the sub-category.) The category for log events is defined when you get a _Logger_ from log4js (`log4js.getLogger('somecategory')`). `Appender` - appenders are responsible for output of log events. They may write events to files, send emails, store them in a database, or anything. Most appenders use _layouts_ to serialise the events to strings for output. diff --git a/docs/v3-changes.md b/docs/v3-changes.md index ef9698a9..9016e960 100644 --- a/docs/v3-changes.md +++ b/docs/v3-changes.md @@ -3,18 +3,19 @@ log4js no longer supports node versions less than 6. The following appenders have been removed from the core, and moved to their own projects: -* [gelf](https://github.com/log4js-node/gelf) -* [hipchat](https://github.com/log4js-node/hipchat) -* [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) -* [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) -* [loggly](https://github.com/log4js-node/loggly) -* [logstashHTTP](https://github.com/log4js-node/logstashHTTP) -* [logstashUDP](https://github.com/log4js-node/logstashUDP) -* [mailgun](https://github.com/log4js-node/mailgun) -* [rabbitmq](https://github.com/log4js-node/rabbitmq) -* [redis](https://github.com/log4js-node/redis) -* [slack](https://github.com/log4js-node/slack) -* [smtp](https://github.com/log4js-node/smtp) + +- [gelf](https://github.com/log4js-node/gelf) +- [hipchat](https://github.com/log4js-node/hipchat) +- [logFaces-HTTP](https://github.com/log4js-node/logFaces-HTTP) +- [logFaces-UDP](https://github.com/log4js-node/logFaces-UDP) +- [loggly](https://github.com/log4js-node/loggly) +- [logstashHTTP](https://github.com/log4js-node/logstashHTTP) +- [logstashUDP](https://github.com/log4js-node/logstashUDP) +- [mailgun](https://github.com/log4js-node/mailgun) +- [rabbitmq](https://github.com/log4js-node/rabbitmq) +- [redis](https://github.com/log4js-node/redis) +- [slack](https://github.com/log4js-node/slack) +- [smtp](https://github.com/log4js-node/smtp) If you were using them, you'll need to `npm i @log4js-node/`. diff --git a/docs/webpack.md b/docs/webpack.md index dd0f68a2..6d1fec7b 100644 --- a/docs/webpack.md +++ b/docs/webpack.md @@ -1,4 +1,4 @@ -# Working with webpack +# Working with webpack Log4js uses dynamic require for loading appenders. Webpack doesn't know at build time which appender will be used at runtime so a small workaround is necessary. @@ -10,4 +10,3 @@ Configuration.prototype.loadAppenderModule = function(type) { return stdout; }; ``` - diff --git a/docs/writing-appenders.md b/docs/writing-appenders.md index 7f81b2ae..b1a0648d 100644 --- a/docs/writing-appenders.md +++ b/docs/writing-appenders.md @@ -7,6 +7,7 @@ Log4js can load appenders from outside its core set. To add a custom appender, t When log4js parses your configuration, it loops through the defined appenders. For each one, it will `require` the appender initially using the `type` value prepended with './appenders' as the module identifier - this is to try loading from the core appenders first. If that fails (the module could not be found in the core appenders), then log4js will try to require the module using variations of the `type` value. Log4js checks the following places (in this order) for appenders based on the type value: + 1. Bundled core appenders (within appenders directory): `require('./' + type)` 2. node_modules: `require(type)` 3. relative to the main file of your application: `require(path.dirname(require.main.filename) + '/' + type)` @@ -17,15 +18,17 @@ If that fails, an error will be raised. ## Appender Modules An appender module should export a single function called `configure`. The function should accept the following arguments: -* `config` - `object` - the appender's configuration object -* `layouts` - `module` - gives access to the [layouts](layouts.md) module, which most appenders will need - * `layout` - `function(type, config)` - this is the main function that appenders will use to find a layout -* `findAppender` - `function(name)` - if your appender is a wrapper around another appender (like the [logLevelFilter](logLevelFilter.md) for example), this function can be used to find another appender by name -* `levels` - `module` - gives access to the [levels](levels.md) module, which most appenders will need + +- `config` - `object` - the appender's configuration object +- `layouts` - `module` - gives access to the [layouts](layouts.md) module, which most appenders will need + - `layout` - `function(type, config)` - this is the main function that appenders will use to find a layout +- `findAppender` - `function(name)` - if your appender is a wrapper around another appender (like the [logLevelFilter](logLevelFilter.md) for example), this function can be used to find another appender by name +- `levels` - `module` - gives access to the [levels](levels.md) module, which most appenders will need `configure` should return a function which accepts a logEvent, which is the appender itself. One of the simplest examples is the [stdout](stdout.md) appender. Let's run through the code. ## Example + ```javascript // This is the function that generates an appender function function stdoutAppender(layout, timezoneOffset) { @@ -57,6 +60,7 @@ exports.configure = configure; It's a good idea to implement a `shutdown` function on your appender instances. This function will get called by `log4js.shutdown` and signals that `log4js` has been asked to stop logging. Usually this is because of a fatal exception, or the application is being stopped. Your shutdown function should make sure that all asynchronous operations finish, and that any resources are cleaned up. The function must be named `shutdown`, take one callback argument, and be a property of the appender instance. Let's add a shutdown function to the `stdout` appender as an example. ## Example (shutdown) + ```javascript // This is the function that generates an appender function function stdoutAppender(layout, timezoneOffset) { @@ -67,7 +71,7 @@ function stdoutAppender(layout, timezoneOffset) { // add a shutdown function. appender.shutdown = (done) => { - process.stdout.write('', done); + process.stdout.write("", done); }; return appender; diff --git a/examples/cluster.js b/examples/cluster.js index c4de8101..12d9a44b 100644 --- a/examples/cluster.js +++ b/examples/cluster.js @@ -5,9 +5,9 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { - out: { type: 'stdout' } + out: { type: 'stdout' }, }, - categories: { default: { appenders: ['out'], level: 'debug' } } + categories: { default: { appenders: ['out'], level: 'debug' } }, }); let logger; diff --git a/examples/custom-layout.js b/examples/custom-layout.js index 8447c5a3..42b78d0e 100644 --- a/examples/custom-layout.js +++ b/examples/custom-layout.js @@ -1,16 +1,20 @@ const log4js = require('../lib/log4js'); -log4js.addLayout('json', config => function (logEvent) { - return JSON.stringify(logEvent) + config.separator; -}); +log4js.addLayout( + 'json', + (config) => + function (logEvent) { + return JSON.stringify(logEvent) + config.separator; + } +); log4js.configure({ appenders: { - out: { type: 'stdout', layout: { type: 'json', separator: ',' } } + out: { type: 'stdout', layout: { type: 'json', separator: ',' } }, }, categories: { - default: { appenders: ['out'], level: 'info' } - } + default: { appenders: ['out'], level: 'info' }, + }, }); const logger = log4js.getLogger('json-test'); diff --git a/examples/date-file-rolling.js b/examples/date-file-rolling.js index 04f90e9b..7cba62b2 100644 --- a/examples/date-file-rolling.js +++ b/examples/date-file-rolling.js @@ -5,12 +5,15 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { file: { - type: 'dateFile', filename: 'thing.log', numBackups: 3, pattern: '.mm' - } + type: 'dateFile', + filename: 'thing.log', + numBackups: 3, + pattern: '.mm', + }, }, categories: { - default: { appenders: ['file'], level: 'debug' } - } + default: { appenders: ['file'], level: 'debug' }, + }, }); const logger = log4js.getLogger('thing'); diff --git a/examples/example-connect-logger.js b/examples/example-connect-logger.js index ca585f13..95bd2d1b 100644 --- a/examples/example-connect-logger.js +++ b/examples/example-connect-logger.js @@ -11,12 +11,12 @@ const app = express(); log4js.configure({ appenders: { console: { type: 'console' }, - file: { type: 'file', filename: 'logs/log4jsconnect.log' } + file: { type: 'file', filename: 'logs/log4jsconnect.log' }, }, categories: { default: { appenders: ['console'], level: 'debug' }, - log4jslog: { appenders: ['file'], level: 'debug' } - } + log4jslog: { appenders: ['file'], level: 'debug' }, + }, }); // define logger diff --git a/examples/example-socket.js b/examples/example-socket.js index 56f24bf9..d88d2986 100644 --- a/examples/example-socket.js +++ b/examples/example-socket.js @@ -11,12 +11,12 @@ if (cluster.isMaster) { master: { type: 'multiprocess', mode: 'master', - appender: 'console' - } + appender: 'console', + }, }, categories: { - default: { appenders: ['console'], level: 'info' } - } + default: { appenders: ['console'], level: 'info' }, + }, }); console.info('Master creating %d workers', numCPUs); @@ -30,11 +30,11 @@ if (cluster.isMaster) { } else { log4js.configure({ appenders: { - worker: { type: 'multiprocess', mode: 'worker' } + worker: { type: 'multiprocess', mode: 'worker' }, }, categories: { - default: { appenders: ['worker'], level: 'info' } - } + default: { appenders: ['worker'], level: 'info' }, + }, }); const logger = log4js.getLogger('example-socket'); diff --git a/examples/example.js b/examples/example.js index 74070c79..440ff1c5 100644 --- a/examples/example.js +++ b/examples/example.js @@ -5,13 +5,13 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { cheeseLogs: { type: 'file', filename: 'cheese.log' }, - console: { type: 'console' } + console: { type: 'console' }, }, categories: { cheese: { appenders: ['cheeseLogs'], level: 'error' }, another: { appenders: ['console'], level: 'trace' }, - default: { appenders: ['console', 'cheeseLogs'], level: 'trace' } - } + default: { appenders: ['console', 'cheeseLogs'], level: 'trace' }, + }, }); // a custom logger outside of the log4js/lib/appenders directory can be accessed like so @@ -25,7 +25,10 @@ const logger = log4js.getLogger('cheese'); const otherLogger = log4js.getLogger(); // this will get coloured output on console, and appear in cheese.log -otherLogger.error('AAArgh! Something went wrong', { some: 'otherObject', useful_for: 'debug purposes' }); +otherLogger.error('AAArgh! Something went wrong', { + some: 'otherObject', + useful_for: 'debug purposes', +}); otherLogger.log('This should appear as info output'); // these will not appear (logging level beneath error) diff --git a/examples/flush-on-exit.js b/examples/flush-on-exit.js index c4c55203..d27ffd9d 100644 --- a/examples/flush-on-exit.js +++ b/examples/flush-on-exit.js @@ -6,23 +6,27 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { - cheese: { type: 'file', filename: 'cheese.log' } + cheese: { type: 'file', filename: 'cheese.log' }, }, categories: { - default: { appenders: ['cheese'], level: 'debug' } - } + default: { appenders: ['cheese'], level: 'debug' }, + }, }); const logger = log4js.getLogger('cheese'); const http = require('http'); -http.createServer((request, response) => { - response.writeHead(200, { 'Content-Type': 'text/plain' }); - const rd = Math.random() * 50; - logger.info(`hello ${rd}`); - response.write('hello '); - if (Math.floor(rd) === 30) { - log4js.shutdown(() => { process.exit(1); }); - } - response.end(); -}).listen(4444); +http + .createServer((request, response) => { + response.writeHead(200, { 'Content-Type': 'text/plain' }); + const rd = Math.random() * 50; + logger.info(`hello ${rd}`); + response.write('hello '); + if (Math.floor(rd) === 30) { + log4js.shutdown(() => { + process.exit(1); + }); + } + response.end(); + }) + .listen(4444); diff --git a/examples/fromreadme.js b/examples/fromreadme.js index 37c97756..f9f0017b 100644 --- a/examples/fromreadme.js +++ b/examples/fromreadme.js @@ -3,7 +3,7 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { cheese: { type: 'file', filename: 'cheese.log' } }, - categories: { default: { appenders: ['cheese'], level: 'error' } } + categories: { default: { appenders: ['cheese'], level: 'error' } }, }); const logger = log4js.getLogger('cheese'); diff --git a/examples/hipchat-appender.js b/examples/hipchat-appender.js index a9e0764e..8e04ba83 100644 --- a/examples/hipchat-appender.js +++ b/examples/hipchat-appender.js @@ -10,13 +10,15 @@ log4js.configure({ appenders: { hipchat: { type: 'hipchat', - hipchat_token: process.env.HIPCHAT_TOKEN || '< User token with Notification Privileges >', - hipchat_room: process.env.HIPCHAT_ROOM || '< Room ID or Name >' - } + hipchat_token: + process.env.HIPCHAT_TOKEN || + '< User token with Notification Privileges >', + hipchat_room: process.env.HIPCHAT_ROOM || '< Room ID or Name >', + }, }, categories: { - default: { appenders: ['hipchat'], level: 'trace' } - } + default: { appenders: ['hipchat'], level: 'trace' }, + }, }); const logger = log4js.getLogger('hipchat'); @@ -27,7 +29,6 @@ logger.trace('Test Trace Message'); logger.fatal('Test Fatal Message'); logger.error('Test Error Message'); - // alternative configuration demonstrating callback + custom layout // ///////////////////////////////////////////////////////////////// @@ -37,7 +38,9 @@ log4js.configure({ appenders: { hipchat: { type: 'hipchat', - hipchat_token: process.env.HIPCHAT_TOKEN || '< User token with Notification Privileges >', + hipchat_token: + process.env.HIPCHAT_TOKEN || + '< User token with Notification Privileges >', hipchat_room: process.env.HIPCHAT_ROOM || '< Room ID or Name >', hipchat_from: 'Mr. Semantics', hipchat_notify: false, @@ -47,10 +50,10 @@ log4js.configure({ } console.log('mr semantics callback success'); }, - layout: { type: 'basic' } - } + layout: { type: 'basic' }, + }, }, - categories: { default: { appenders: ['hipchat'], level: 'trace' } } + categories: { default: { appenders: ['hipchat'], level: 'trace' } }, }); logger.info('Test customLayout from Mr. Semantics'); diff --git a/examples/layouts.js b/examples/layouts.js index 0d47444f..338a505c 100644 --- a/examples/layouts.js +++ b/examples/layouts.js @@ -2,11 +2,11 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { - out: { type: 'stdout', layout: { type: 'messagePassThrough' } } + out: { type: 'stdout', layout: { type: 'messagePassThrough' } }, }, categories: { - default: { appenders: ['out'], level: 'info' } - } + default: { appenders: ['out'], level: 'info' }, + }, }); const logger = log4js.getLogger('thing'); diff --git a/examples/log-rolling-bug.js b/examples/log-rolling-bug.js index 5bdba3a0..a23e62a2 100644 --- a/examples/log-rolling-bug.js +++ b/examples/log-rolling-bug.js @@ -8,24 +8,24 @@ log4js.configure({ maxLogSize: 100000, backups: 5, keepFileExt: true, - compress: true - } + compress: true, + }, }, categories: { default: { appenders: ['handler'], level: 'debug' }, handler: { appenders: ['handler'], level: 'debug' }, - } + }, }); -const logsToTest = [ - 'handler' -]; +const logsToTest = ['handler']; const logStartDate = new Date(); -const loggers = logsToTest.map(log => log4js.getLogger(log)); +const loggers = logsToTest.map((log) => log4js.getLogger(log)); // write out a lot setInterval(() => { - loggers.forEach(logger => logger.info(`TESTING LOGGER!!!!!!${logStartDate}`)); + loggers.forEach((logger) => + logger.info(`TESTING LOGGER!!!!!!${logStartDate}`) + ); }, 10); diff --git a/examples/log-rolling.js b/examples/log-rolling.js index 4481b024..7f1cc880 100644 --- a/examples/log-rolling.js +++ b/examples/log-rolling.js @@ -3,18 +3,18 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { - type: 'console' + type: 'console', }, file: { type: 'file', filename: 'tmp-test.log', maxLogSize: 1024, - backups: 3 - } + backups: 3, + }, }, categories: { - default: { appenders: ['console', 'file'], level: 'info' } - } + default: { appenders: ['console', 'file'], level: 'info' }, + }, }); const log = log4js.getLogger('test'); diff --git a/examples/log-to-files.js b/examples/log-to-files.js index 15d66cbd..fc19d897 100644 --- a/examples/log-to-files.js +++ b/examples/log-to-files.js @@ -1,33 +1,31 @@ const log4js = require('../lib/log4js'); -log4js.configure( - { - appenders: { - file: { - type: 'file', - filename: 'important-things.log', - maxLogSize: 10 * 1024 * 1024, // = 10Mb - backups: 5, // keep five backup files - compress: true, // compress the backups - encoding: 'utf-8', - mode: 0o0640, - flags: 'w+' - }, - dateFile: { - type: 'dateFile', - filename: 'more-important-things.log', - pattern: 'yyyy-MM-dd-hh', - compress: true - }, - out: { - type: 'stdout' - } +log4js.configure({ + appenders: { + file: { + type: 'file', + filename: 'important-things.log', + maxLogSize: 10 * 1024 * 1024, // = 10Mb + backups: 5, // keep five backup files + compress: true, // compress the backups + encoding: 'utf-8', + mode: 0o0640, + flags: 'w+', }, - categories: { - default: { appenders: ['file', 'dateFile', 'out'], level: 'trace' } - } - } -); + dateFile: { + type: 'dateFile', + filename: 'more-important-things.log', + pattern: 'yyyy-MM-dd-hh', + compress: true, + }, + out: { + type: 'stdout', + }, + }, + categories: { + default: { appenders: ['file', 'dateFile', 'out'], level: 'trace' }, + }, +}); const logger = log4js.getLogger('things'); logger.debug('This little thing went to market'); diff --git a/examples/logFaces-appender.js b/examples/logFaces-appender.js index 62f10056..12a8b15c 100644 --- a/examples/logFaces-appender.js +++ b/examples/logFaces-appender.js @@ -12,13 +12,14 @@ log4js.configure({ application: 'MY-NODEJS', // (optional) name of the application (domain) remoteHost: 'localhost', // (optional) logFaces server host or IP address port: 55201, // (optional) logFaces UDP receiver port (must use JSON format) - layout: { // (optional) the layout to use for messages + layout: { + // (optional) the layout to use for messages type: 'pattern', - pattern: '%m' - } - } + pattern: '%m', + }, + }, }, - categories: { default: { appenders: ['logFaces'], level: 'info' } } + categories: { default: { appenders: ['logFaces'], level: 'info' } }, }); const logger = log4js.getLogger('myLogger'); diff --git a/examples/loggly-appender.js b/examples/loggly-appender.js index cb806d65..a03b7aa8 100644 --- a/examples/loggly-appender.js +++ b/examples/loggly-appender.js @@ -6,19 +6,19 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { - type: 'console' + type: 'console', }, loggly: { type: 'loggly', token: '12345678901234567890', subdomain: 'your-subdomain', - tags: ['test'] - } + tags: ['test'], + }, }, categories: { default: { appenders: ['console'], level: 'info' }, - loggly: { appenders: ['loggly'], level: 'info' } - } + loggly: { appenders: ['loggly'], level: 'info' }, + }, }); const logger = log4js.getLogger('loggly'); diff --git a/examples/logstashHTTP.js b/examples/logstashHTTP.js index b15df947..ab48f6d0 100644 --- a/examples/logstashHTTP.js +++ b/examples/logstashHTTP.js @@ -3,7 +3,7 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { - type: 'console' + type: 'console', }, logstash: { url: 'http://172.17.0.5:9200/_bulk', @@ -13,13 +13,13 @@ log4js.configure({ application: 'logstash-log4js', layout: { type: 'pattern', - pattern: '%m' - } - } + pattern: '%m', + }, + }, }, categories: { - default: { appenders: ['console', 'logstash'], level: 'info' } - } + default: { appenders: ['console', 'logstash'], level: 'info' }, + }, }); const logger = log4js.getLogger('myLogger'); diff --git a/examples/logstashUDP.js b/examples/logstashUDP.js index 83c6c907..2322dfa0 100644 --- a/examples/logstashUDP.js +++ b/examples/logstashUDP.js @@ -14,26 +14,27 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { console: { - type: 'console' + type: 'console', }, logstash: { host: '127.0.0.1', port: 10001, type: 'logstashUDP', logType: 'myAppType', // Optional, defaults to 'category' - fields: { // Optional, will be added to the 'fields' object in logstash + fields: { + // Optional, will be added to the 'fields' object in logstash field1: 'value1', - field2: 'value2' + field2: 'value2', }, layout: { type: 'pattern', - pattern: '%m' - } - } + pattern: '%m', + }, + }, }, categories: { - default: { appenders: ['console', 'logstash'], level: 'info' } - } + default: { appenders: ['console', 'logstash'], level: 'info' }, + }, }); const logger = log4js.getLogger('myLogger'); diff --git a/examples/memory-test.js b/examples/memory-test.js index e6b53bd4..256cc812 100644 --- a/examples/memory-test.js +++ b/examples/memory-test.js @@ -1,35 +1,33 @@ const log4js = require('../lib/log4js'); -log4js.configure( - { - appenders: { - logs: { - type: 'file', - filename: 'memory-test.log' - }, - console: { - type: 'stdout', +log4js.configure({ + appenders: { + logs: { + type: 'file', + filename: 'memory-test.log', + }, + console: { + type: 'stdout', + }, + file: { + type: 'file', + filename: 'memory-usage.log', + layout: { + type: 'messagePassThrough', }, - file: { - type: 'file', - filename: 'memory-usage.log', - layout: { - type: 'messagePassThrough' - } - } }, - categories: { - default: { appenders: ['console'], level: 'info' }, - 'memory-test': { appenders: ['logs'], level: 'info' }, - 'memory-usage': { appenders: ['console', 'file'], level: 'info' } - } - } -); + }, + categories: { + default: { appenders: ['console'], level: 'info' }, + 'memory-test': { appenders: ['logs'], level: 'info' }, + 'memory-usage': { appenders: ['console', 'file'], level: 'info' }, + }, +}); const logger = log4js.getLogger('memory-test'); const usage = log4js.getLogger('memory-usage'); for (let i = 0; i < 1000000; i += 1) { - if ((i % 5000) === 0) { + if (i % 5000 === 0) { usage.info('%d %d', i, process.memoryUsage().rss); } logger.info('Doing something.'); diff --git a/examples/patternLayout-tokens.js b/examples/patternLayout-tokens.js index e2aebd8e..764508b1 100644 --- a/examples/patternLayout-tokens.js +++ b/examples/patternLayout-tokens.js @@ -8,14 +8,16 @@ log4js.configure({ type: 'pattern', pattern: '%[%r (%x{pid}) %p %c -%] %m%n', tokens: { - pid: function () { return process.pid; } - } - } - } + pid: function () { + return process.pid; + }, + }, + }, + }, }, categories: { - default: { appenders: ['out'], level: 'info' } - } + default: { appenders: ['out'], level: 'info' }, + }, }); const logger = log4js.getLogger('app'); diff --git a/examples/pm2.js b/examples/pm2.js index ce1fe153..910969e0 100644 --- a/examples/pm2.js +++ b/examples/pm2.js @@ -4,13 +4,13 @@ const log4js = require('../lib/log4js'); // `pm2 install pm2-intercom` log4js.configure({ appenders: { - out: { type: 'file', filename: 'pm2logs.log' } + out: { type: 'file', filename: 'pm2logs.log' }, }, categories: { - default: { appenders: ['out'], level: 'info' } + default: { appenders: ['out'], level: 'info' }, }, pm2: true, - pm2InstanceVar: 'INSTANCE_ID' + pm2InstanceVar: 'INSTANCE_ID', }); const logger = log4js.getLogger('app'); logger.info("I'm forever blowing bubbles ", process.env.INSTANCE_ID); diff --git a/examples/pm2.json b/examples/pm2.json index 45ba25b3..e03a0711 100644 --- a/examples/pm2.json +++ b/examples/pm2.json @@ -1,9 +1,11 @@ -{ "apps": [ - { "name": "testing", - "script": "pm2.js", - "instances": 0, - "instance_var": "INSTANCE_ID", - "exec_mode": "cluster" +{ + "apps": [ + { + "name": "testing", + "script": "pm2.js", + "instances": 0, + "instance_var": "INSTANCE_ID", + "exec_mode": "cluster" } - ] - } + ] +} diff --git a/examples/rabbitmq-appender.js b/examples/rabbitmq-appender.js index f9fde1af..23c60112 100755 --- a/examples/rabbitmq-appender.js +++ b/examples/rabbitmq-appender.js @@ -5,13 +5,13 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { out: { - type: 'console' + type: 'console', }, file: { type: 'dateFile', filename: 'logs/log.txt', pattern: 'yyyyMMdd', - alwaysIncludePattern: false + alwaysIncludePattern: false, }, mq: { type: '@log4js-node/rabbitmq', @@ -25,15 +25,15 @@ log4js.configure({ durable: true, layout: { type: 'pattern', - pattern: '%d{yyyy-MM-dd hh:mm:ss:SSS}#%p#%m' - } - } + pattern: '%d{yyyy-MM-dd hh:mm:ss:SSS}#%p#%m', + }, + }, }, categories: { default: { appenders: ['out'], level: 'info' }, dateFile: { appenders: ['file'], level: 'info' }, - rabbitmq: { appenders: ['mq'], level: 'info' } - } + rabbitmq: { appenders: ['mq'], level: 'info' }, + }, }); const log = log4js.getLogger('console'); diff --git a/examples/redis-appender.js b/examples/redis-appender.js index 5e8e1208..d45d5936 100644 --- a/examples/redis-appender.js +++ b/examples/redis-appender.js @@ -5,13 +5,13 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { out: { - type: 'console' + type: 'console', }, file: { type: 'dateFile', filename: 'logs/log.txt', pattern: 'yyyyMMdd', - alwaysIncludePattern: false + alwaysIncludePattern: false, }, db: { type: '@log4js-node/redis', @@ -21,15 +21,15 @@ log4js.configure({ channel: 'q_log', layout: { type: 'pattern', - pattern: '%d{yyyy-MM-dd hh:mm:ss:SSS}#%p#%m' - } - } + pattern: '%d{yyyy-MM-dd hh:mm:ss:SSS}#%p#%m', + }, + }, }, categories: { default: { appenders: ['out'], level: 'info' }, dateFile: { appenders: ['file'], level: 'info' }, - redis: { appenders: ['db'], level: 'info' } - } + redis: { appenders: ['db'], level: 'info' }, + }, }); const log = log4js.getLogger('console'); diff --git a/examples/slack-appender.js b/examples/slack-appender.js index 5847c49d..0f11967d 100644 --- a/examples/slack-appender.js +++ b/examples/slack-appender.js @@ -9,12 +9,12 @@ log4js.configure({ channel_id: '#CHANNEL', username: 'USERNAME', format: 'text', - icon_url: 'ICON_URL' - } + icon_url: 'ICON_URL', + }, }, categories: { - default: { appenders: ['slack'], level: 'info' } - } + default: { appenders: ['slack'], level: 'info' }, + }, }); const logger = log4js.getLogger('slack'); diff --git a/examples/smtp-appender.js b/examples/smtp-appender.js index 32745165..716b3991 100644 --- a/examples/smtp-appender.js +++ b/examples/smtp-appender.js @@ -6,7 +6,7 @@ const log4js = require('../lib/log4js'); log4js.configure({ appenders: { out: { - type: 'console' + type: 'console', }, mail: { type: '@log4js-node/smtp', @@ -19,16 +19,16 @@ log4js.configure({ port: 465, auth: { user: 'someone@gmail', - pass: '********************' + pass: '********************', }, - debug: true - } - } + debug: true, + }, + }, }, categories: { default: { appenders: ['out'], level: 'info' }, - mailer: { appenders: ['mail'], level: 'info' } - } + mailer: { appenders: ['mail'], level: 'info' }, + }, }); const log = log4js.getLogger('test'); const logmailer = log4js.getLogger('mailer'); diff --git a/examples/stacktrace.js b/examples/stacktrace.js index db3f2f93..ff3abf49 100644 --- a/examples/stacktrace.js +++ b/examples/stacktrace.js @@ -1,22 +1,22 @@ const log4js = require('../lib/log4js'); log4js.configure({ - "appenders": { - "console-appender": { - "type": "console", - "layout": { - "type": "pattern", - "pattern": "%[[%p]%] - %10.-100f{2} | %7.12l:%7.12o - %[%m%]" - } - } + appenders: { + 'console-appender': { + type: 'console', + layout: { + type: 'pattern', + pattern: '%[[%p]%] - %10.-100f{2} | %7.12l:%7.12o - %[%m%]', + }, + }, }, - "categories": { - "default": { - "appenders": ["console-appender"], - "enableCallStack": true, - "level": "info" - } - } -}) + categories: { + default: { + appenders: ['console-appender'], + enableCallStack: true, + level: 'info', + }, + }, +}); log4js.getLogger().info('This should not cause problems'); diff --git a/lib/LoggingEvent.js b/lib/LoggingEvent.js index f30e5ee1..a3dff7ac 100644 --- a/lib/LoggingEvent.js +++ b/lib/LoggingEvent.js @@ -38,11 +38,17 @@ class LoggingEvent { // duck-typing for Error object if (value && value.message && value.stack) { // eslint-disable-next-line prefer-object-spread - value = Object.assign({message: value.message, stack: value.stack}, value); + value = Object.assign( + { message: value.message, stack: value.stack }, + value + ); } // JSON.stringify({a: parseInt('abc'), b: 1/0, c: -1/0}) returns {a: null, b: null, c: null}. // The following allows us to serialize to NaN, Infinity and -Infinity correctly. - else if (typeof value === 'number' && (Number.isNaN(value) || !Number.isFinite(value))) { + else if ( + typeof value === 'number' && + (Number.isNaN(value) || !Number.isFinite(value)) + ) { value = value.toString(); } // JSON.stringify([undefined]) returns [null]. @@ -60,7 +66,9 @@ class LoggingEvent { const rehydratedEvent = flatted.parse(serialised, (key, value) => { if (value && value.message && value.stack) { const fakeError = new Error(value); - Object.keys(value).forEach((k) => { fakeError[k] = value[k]; }); + Object.keys(value).forEach((k) => { + fakeError[k] = value[k]; + }); value = fakeError; } return value; @@ -70,7 +78,7 @@ class LoggingEvent { fileName: rehydratedEvent.fileName, lineNumber: rehydratedEvent.lineNumber, columnNumber: rehydratedEvent.columnNumber, - callStack: rehydratedEvent.callStack + callStack: rehydratedEvent.callStack, }; event = new LoggingEvent( rehydratedEvent.categoryName, @@ -83,11 +91,12 @@ class LoggingEvent { event.pid = rehydratedEvent.pid; event.cluster = rehydratedEvent.cluster; } catch (e) { - event = new LoggingEvent( - 'log4js', - levels.ERROR, - ['Unable to parse log:', serialised, 'because: ', e] - ); + event = new LoggingEvent('log4js', levels.ERROR, [ + 'Unable to parse log:', + serialised, + 'because: ', + e, + ]); } return event; diff --git a/lib/appenders/adapters.js b/lib/appenders/adapters.js index 35dfff26..648c3621 100644 --- a/lib/appenders/adapters.js +++ b/lib/appenders/adapters.js @@ -31,7 +31,7 @@ function adapter(configAdapter, config) { function fileAppenderAdapter(config) { const configAdapter = { - maxLogSize: maxFileSizeUnitTransform + maxLogSize: maxFileSizeUnitTransform, }; return adapter(configAdapter, config); } @@ -39,7 +39,8 @@ function fileAppenderAdapter(config) { const adapters = { dateFile: fileAppenderAdapter, file: fileAppenderAdapter, - fileSync: fileAppenderAdapter + fileSync: fileAppenderAdapter, }; -module.exports.modifyConfig = config => (adapters[config.type] ? adapters[config.type](config) : config); +module.exports.modifyConfig = (config) => + adapters[config.type] ? adapters[config.type](config) : config; diff --git a/lib/appenders/dateFile.js b/lib/appenders/dateFile.js index 76de634c..36811b34 100644 --- a/lib/appenders/dateFile.js +++ b/lib/appenders/dateFile.js @@ -4,17 +4,17 @@ const os = require('os'); const eol = os.EOL; function openTheStream(filename, pattern, options) { - const stream = new streams.DateRollingFileStream( - filename, - pattern, - options - ); + const stream = new streams.DateRollingFileStream(filename, pattern, options); stream.on('error', (err) => { // eslint-disable-next-line no-console - console.error('log4js.dateFileAppender - Writing to file %s, error happened ', filename, err); + console.error( + 'log4js.dateFileAppender - Writing to file %s, error happened ', + filename, + err + ); }); - stream.on("drain", () => { - process.emit("log4js:pause", false); + stream.on('drain', () => { + process.emit('log4js:pause', false); }); return stream; } @@ -28,13 +28,7 @@ function openTheStream(filename, pattern, options) { * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ -function appender( - filename, - pattern, - layout, - options, - timezoneOffset -) { +function appender(filename, pattern, layout, options, timezoneOffset) { // the options for file appender use maxLogSize, but the docs say any file appender // options should work for dateFile as well. options.maxSize = options.maxLogSize; @@ -45,8 +39,8 @@ function appender( if (!writer.writable) { return; } - if (!writer.write(layout(logEvent, timezoneOffset) + eol, "utf8")) { - process.emit("log4js:pause", true); + if (!writer.write(layout(logEvent, timezoneOffset) + eol, 'utf8')) { + process.emit('log4js:pause', true); } }; diff --git a/lib/appenders/file.js b/lib/appenders/file.js index 789a9321..3f4f8663 100644 --- a/lib/appenders/file.js +++ b/lib/appenders/file.js @@ -26,8 +26,15 @@ function mainSighupHandler() { * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ -function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset) { - if (typeof file !== "string" || file.length === 0) { +function fileAppender( + file, + layout, + logSize, + numBackups, + options, + timezoneOffset +) { + if (typeof file !== 'string' || file.length === 0) { throw new Error(`Invalid filename: ${file}`); } else if (file.endsWith(path.sep)) { throw new Error(`Filename is a directory: ${file}`); @@ -37,15 +44,20 @@ function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset file = file.replace(new RegExp(`^~(?=${path.sep}.+)`), os.homedir()); } file = path.normalize(file); - numBackups = (!numBackups && numBackups !== 0) ? 5 : numBackups; + numBackups = !numBackups && numBackups !== 0 ? 5 : numBackups; debug( 'Creating file appender (', - file, ', ', - logSize, ', ', - numBackups, ', ', - options, ', ', - timezoneOffset, ')' + file, + ', ', + logSize, + ', ', + numBackups, + ', ', + options, + ', ', + timezoneOffset, + ')' ); function openTheStream(filePath, fileSize, numFiles, opt) { @@ -57,10 +69,14 @@ function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset ); stream.on('error', (err) => { // eslint-disable-next-line no-console - console.error('log4js.fileAppender - Writing to file %s, error happened ', filePath, err); + console.error( + 'log4js.fileAppender - Writing to file %s, error happened ', + filePath, + err + ); }); stream.on('drain', () => { - process.emit("log4js:pause", false); + process.emit('log4js:pause', false); }); return stream; } @@ -74,18 +90,20 @@ function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset if (options.removeColor === true) { // eslint-disable-next-line no-control-regex const regex = /\x1b[[0-9;]*m/g; - loggingEvent.data = loggingEvent.data.map(d => { + loggingEvent.data = loggingEvent.data.map((d) => { if (typeof d === 'string') return d.replace(regex, ''); return d; }); } - if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, "utf8")) { + if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, 'utf8')) { process.emit('log4js:pause', true); } }; app.reopen = function () { - writer.end(() => { writer = openTheStream(file, logSize, numBackups, options); }); + writer.end(() => { + writer = openTheStream(file, logSize, numBackups, options); + }); }; app.sighupHandler = function () { diff --git a/lib/appenders/fileSync.js b/lib/appenders/fileSync.js index fa8b4089..12436e72 100755 --- a/lib/appenders/fileSync.js +++ b/lib/appenders/fileSync.js @@ -10,9 +10,8 @@ function touchFile(file, options) { const mkdir = (dir) => { try { return fs.mkdirSync(dir, { recursive: true }); - } - // backward-compatible fs.mkdirSync for nodejs pre-10.12.0 (without recursive option) - catch (e) { + } catch (e) { + // backward-compatible fs.mkdirSync for nodejs pre-10.12.0 (without recursive option) // recursive creation of parent first if (e.code === 'ENOENT') { mkdir(path.dirname(dir)); @@ -41,7 +40,7 @@ function touchFile(file, options) { mkdir(path.dirname(file)); // try to throw EISDIR, EROFS, EACCES - fs.appendFileSync(file, "", { mode: options.mode, flag: options.flags }); + fs.appendFileSync(file, '', { mode: options.mode, flag: options.flags }); } class RollingFileSync { @@ -74,7 +73,11 @@ class RollingFileSync { } shouldRoll() { - debug('should roll with current size %d, and max size %d', this.currentSize, this.size); + debug( + 'should roll with current size %d, and max size %d', + this.currentSize, + this.size + ); return this.currentSize >= this.size; } @@ -87,7 +90,9 @@ class RollingFileSync { } function index(filename_) { - return parseInt(filename_.slice((`${path.basename(filename)}.`).length), 10) || 0; + return ( + parseInt(filename_.slice(`${path.basename(filename)}.`.length), 10) || 0 + ); } function byIndex(a, b) { @@ -109,7 +114,10 @@ class RollingFileSync { } debug(`Renaming ${fileToRename} -> ${filename}.${idx + 1}`); - fs.renameSync(path.join(path.dirname(filename), fileToRename), `${filename}.${idx + 1}`); + fs.renameSync( + path.join(path.dirname(filename), fileToRename), + `${filename}.${idx + 1}` + ); } } @@ -118,7 +126,11 @@ class RollingFileSync { debug('Renaming the old files'); const files = fs.readdirSync(path.dirname(filename)); - files.filter(justTheseFiles).sort(byIndex).reverse().forEach(increaseFileIndex); + files + .filter(justTheseFiles) + .sort(byIndex) + .reverse() + .forEach(increaseFileIndex); } debug('Rolling, rolling, rolling'); @@ -129,7 +141,6 @@ class RollingFileSync { write(chunk, encoding) { const that = this; - function writeTheChunk() { debug('writing the chunk to the file'); that.currentSize += chunk.length; @@ -138,7 +149,6 @@ class RollingFileSync { debug('in write'); - if (this.shouldRoll()) { this.currentSize = 0; this.roll(this.filename); @@ -161,8 +171,15 @@ class RollingFileSync { * @param options - options to be passed to the underlying stream * @param timezoneOffset - optional timezone offset in minutes (default system local) */ -function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset) { - if (typeof file !== "string" || file.length === 0) { +function fileAppender( + file, + layout, + logSize, + numBackups, + options, + timezoneOffset +) { + if (typeof file !== 'string' || file.length === 0) { throw new Error(`Invalid filename: ${file}`); } else if (file.endsWith(path.sep)) { throw new Error(`Filename is a directory: ${file}`); @@ -172,38 +189,38 @@ function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset file = file.replace(new RegExp(`^~(?=${path.sep}.+)`), os.homedir()); } file = path.normalize(file); - numBackups = (!numBackups && numBackups !== 0) ? 5 : numBackups; + numBackups = !numBackups && numBackups !== 0 ? 5 : numBackups; debug( 'Creating fileSync appender (', - file, ', ', - logSize, ', ', - numBackups, ', ', - options, ', ', - timezoneOffset, ')' + file, + ', ', + logSize, + ', ', + numBackups, + ', ', + options, + ', ', + timezoneOffset, + ')' ); function openTheStream(filePath, fileSize, numFiles) { let stream; if (fileSize) { - stream = new RollingFileSync( - filePath, - fileSize, - numFiles, - options - ); + stream = new RollingFileSync(filePath, fileSize, numFiles, options); } else { - stream = (((f) => { + stream = ((f) => { // touch the file to apply flags (like w to truncate the file) touchFile(f, options); return { write(data) { fs.appendFileSync(f, data); - } + }, }; - }))(filePath); + })(filePath); } return stream; @@ -225,7 +242,7 @@ function configure(config, layouts) { const options = { flags: config.flags || 'a', encoding: config.encoding || 'utf8', - mode: config.mode || 0o600 + mode: config.mode || 0o600, }; return fileAppender( diff --git a/lib/appenders/index.js b/lib/appenders/index.js index d89a77f2..3e26c127 100644 --- a/lib/appenders/index.js +++ b/lib/appenders/index.js @@ -37,18 +37,22 @@ const tryLoading = (modulePath, config) => { } }; -const loadAppenderModule = (type, config) => coreAppenders.get(type) - || tryLoading(`./${type}`, config) - || tryLoading(type, config) - || (require.main && require.main.filename && tryLoading(path.join(path.dirname(require.main.filename), type), config)) - || tryLoading(path.join(process.cwd(), type), config); +const loadAppenderModule = (type, config) => + coreAppenders.get(type) || + tryLoading(`./${type}`, config) || + tryLoading(type, config) || + (require.main && + require.main.filename && + tryLoading(path.join(path.dirname(require.main.filename), type), config)) || + tryLoading(path.join(process.cwd(), type), config); const appendersLoading = new Set(); const getAppender = (name, config) => { if (appenders.has(name)) return appenders.get(name); if (!config.appenders[name]) return false; - if (appendersLoading.has(name)) throw new Error(`Dependency loop detected for appender ${name}.`); + if (appendersLoading.has(name)) + throw new Error(`Dependency loop detected for appender ${name}.`); appendersLoading.add(name); debug(`Creating appender ${name}`); @@ -62,7 +66,8 @@ const getAppender = (name, config) => { const createAppender = (name, config) => { const appenderConfig = config.appenders[name]; const appenderModule = appenderConfig.type.configure - ? appenderConfig.type : loadAppenderModule(appenderConfig.type, config); + ? appenderConfig.type + : loadAppenderModule(appenderConfig.type, config); configuration.throwExceptionIf( config, configuration.not(appenderModule), @@ -71,18 +76,24 @@ const createAppender = (name, config) => { if (appenderModule.appender) { process.emitWarning( `Appender ${appenderConfig.type} exports an appender function.`, - "DeprecationWarning", "log4js-node-DEP0001" + 'DeprecationWarning', + 'log4js-node-DEP0001' + ); + debug( + '[log4js-node-DEP0001]', + `DEPRECATION: Appender ${appenderConfig.type} exports an appender function.` ); - debug("[log4js-node-DEP0001]", - `DEPRECATION: Appender ${appenderConfig.type} exports an appender function.`); } if (appenderModule.shutdown) { process.emitWarning( `Appender ${appenderConfig.type} exports a shutdown function.`, - "DeprecationWarning", "log4js-node-DEP0002" + 'DeprecationWarning', + 'log4js-node-DEP0002' + ); + debug( + '[log4js-node-DEP0002]', + `DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.` ); - debug("[log4js-node-DEP0002]", - `DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.`); } debug(`${name}: clustering.isMaster ? ${clustering.isMaster()}`); @@ -90,15 +101,20 @@ const createAppender = (name, config) => { // eslint-disable-next-line global-require `${name}: appenderModule is ${require('util').inspect(appenderModule)}` ); - return clustering.onlyOnMaster(() => { - debug(`calling appenderModule.configure for ${name} / ${appenderConfig.type}`); - return appenderModule.configure( - adapters.modifyConfig(appenderConfig), - layouts, - appender => getAppender(appender, config), - levels - ); - }, /* istanbul ignore next: fn never gets called by non-master yet needed to pass config validation */ () => {}); + return clustering.onlyOnMaster( + () => { + debug( + `calling appenderModule.configure for ${name} / ${appenderConfig.type}` + ); + return appenderModule.configure( + adapters.modifyConfig(appenderConfig), + layouts, + (appender) => getAppender(appender, config), + levels + ); + }, + /* istanbul ignore next: fn never gets called by non-master yet needed to pass config validation */ () => {} + ); }; const setup = (config) => { @@ -109,14 +125,17 @@ const setup = (config) => { } const usedAppenders = []; - Object.values(config.categories).forEach(category => { + Object.values(config.categories).forEach((category) => { usedAppenders.push(...category.appenders); }); Object.keys(config.appenders).forEach((name) => { // dodgy hard-coding of special case for tcp-server and multiprocess which may not have // any categories associated with it, but needs to be started up anyway - if (usedAppenders.includes(name) || config.appenders[name].type === 'tcp-server' - || config.appenders[name].type === 'multiprocess') { + if ( + usedAppenders.includes(name) || + config.appenders[name].type === 'tcp-server' || + config.appenders[name].type === 'multiprocess' + ) { getAppender(name, config); } }); diff --git a/lib/appenders/logLevelFilter.js b/lib/appenders/logLevelFilter.js index 253fedd7..2e759cd0 100644 --- a/lib/appenders/logLevelFilter.js +++ b/lib/appenders/logLevelFilter.js @@ -3,7 +3,10 @@ function logLevelFilter(minLevelString, maxLevelString, appender, levels) { const maxLevel = levels.getLevel(maxLevelString, levels.FATAL); return (logEvent) => { const eventLevel = logEvent.level; - if (minLevel.isLessThanOrEqualTo(eventLevel) && maxLevel.isGreaterThanOrEqualTo(eventLevel)) { + if ( + minLevel.isLessThanOrEqualTo(eventLevel) && + maxLevel.isGreaterThanOrEqualTo(eventLevel) + ) { appender(logEvent); } }; diff --git a/lib/appenders/multiFile.js b/lib/appenders/multiFile.js index 8efb4e14..1a0746fc 100644 --- a/lib/appenders/multiFile.js +++ b/lib/appenders/multiFile.js @@ -1,10 +1,9 @@ - - const debug = require('debug')('log4js:multiFile'); const path = require('path'); const fileAppender = require('./file'); -const findFileKey = (property, event) => event[property] || event.context[property]; +const findFileKey = (property, event) => + event[property] || event.context[property]; module.exports.configure = (config, layouts) => { debug('Creating a multi-file appender'); @@ -49,7 +48,10 @@ module.exports.configure = (config, layouts) => { timers.set(fileKey, { timeout: config.timeout, lastUsed: Date.now(), - interval: setInterval(checkForTimeout.bind(null, fileKey), config.timeout) + interval: setInterval( + checkForTimeout.bind(null, fileKey), + config.timeout + ), }); } } else if (config.timeout) { diff --git a/lib/appenders/multiprocess.js b/lib/appenders/multiprocess.js index 95b5a9d3..06d9fb52 100644 --- a/lib/appenders/multiprocess.js +++ b/lib/appenders/multiprocess.js @@ -1,5 +1,3 @@ - - const debug = require('debug')('log4js:multiprocess'); const net = require('net'); const LoggingEvent = require('../LoggingEvent'); @@ -55,7 +53,7 @@ function logServer(config, actualAppender, levels) { level: levels.ERROR, data: ['A worker log process hung up unexpectedly', error], remoteAddress: clientSocket.remoteAddress, - remotePort: clientSocket.remotePort + remotePort: clientSocket.remotePort, }; actualAppender(loggingEvent); } @@ -65,11 +63,15 @@ function logServer(config, actualAppender, levels) { clientSocket.on('error', handleError); }); - server.listen(config.loggerPort || 5000, config.loggerHost || 'localhost', (e) => { - debug('(master) master server listening, error was ', e); - // allow the process to exit, if this is the only socket active - server.unref(); - }); + server.listen( + config.loggerPort || 5000, + config.loggerHost || 'localhost', + (e) => { + debug('(master) master server listening, error was ', e); + // allow the process to exit, if this is the only socket active + server.unref(); + } + ); function app(event) { debug('(master) log event sent directly to actual appender (local event)'); @@ -106,9 +108,14 @@ function workerAppender(config) { function createSocket() { debug( - `(worker) worker appender creating socket to ${config.loggerHost || 'localhost'}:${config.loggerPort || 5000}` + `(worker) worker appender creating socket to ${ + config.loggerHost || 'localhost' + }:${config.loggerPort || 5000}` + ); + socket = net.createConnection( + config.loggerPort || 5000, + config.loggerHost || 'localhost' ); - socket = net.createConnection(config.loggerPort || 5000, config.loggerHost || 'localhost'); socket.on('connect', () => { debug('(worker) worker socket connected'); emptyBuffer(); @@ -129,7 +136,9 @@ function workerAppender(config) { if (canWrite) { write(loggingEvent); } else { - debug('(worker) worker buffering log event because it cannot write at the moment'); + debug( + '(worker) worker buffering log event because it cannot write at the moment' + ); buffer.push(loggingEvent); } } @@ -171,7 +180,9 @@ function configure(config, layouts, findAppender, levels) { appender = findAppender(config.appender); if (!appender) { debug(`actual appender "${config.appender}" not found`); - throw new Error(`multiprocess master appender "${config.appender}" not defined`); + throw new Error( + `multiprocess master appender "${config.appender}" not defined` + ); } } return createAppender(config, appender, levels); diff --git a/lib/appenders/noLogFilter.js b/lib/appenders/noLogFilter.js index aa0327ad..82129ccf 100644 --- a/lib/appenders/noLogFilter.js +++ b/lib/appenders/noLogFilter.js @@ -1,5 +1,3 @@ - - const debug = require('debug')('log4js:noLogFilter'); /** @@ -8,7 +6,7 @@ const debug = require('debug')('log4js:noLogFilter'); * @returns {string[]} a filtered string array with not empty or null regexp */ function removeNullOrEmptyRegexp(regexp) { - const filtered = regexp.filter(el => ((el != null) && (el !== ''))); + const filtered = regexp.filter((el) => el != null && el !== ''); return filtered; } @@ -27,8 +25,10 @@ function noLogFilter(filters, appender) { } filters = removeNullOrEmptyRegexp(filters); const regex = new RegExp(filters.join('|'), 'i'); - if (filters.length === 0 - || logEvent.data.findIndex(value => regex.test(value)) < 0) { + if ( + filters.length === 0 || + logEvent.data.findIndex((value) => regex.test(value)) < 0 + ) { debug('Not excluded, sending to appender'); appender(logEvent); } diff --git a/lib/appenders/recording.js b/lib/appenders/recording.js index 096eabb4..ca90e070 100644 --- a/lib/appenders/recording.js +++ b/lib/appenders/recording.js @@ -1,12 +1,12 @@ - - const debug = require('debug')('log4js:recording'); const recordedEvents = []; function configure() { return function (logEvent) { - debug(`received logEvent, number of events now ${recordedEvents.length + 1}`); + debug( + `received logEvent, number of events now ${recordedEvents.length + 1}` + ); debug('log event was ', logEvent); recordedEvents.push(logEvent); }; @@ -25,5 +25,5 @@ module.exports = { replay, playback: replay, reset, - erase: reset + erase: reset, }; diff --git a/lib/appenders/stderr.js b/lib/appenders/stderr.js index c005d63c..690d1df8 100644 --- a/lib/appenders/stderr.js +++ b/lib/appenders/stderr.js @@ -1,5 +1,3 @@ - - function stderrAppender(layout, timezoneOffset) { return (loggingEvent) => { process.stderr.write(`${layout(loggingEvent, timezoneOffset)}\n`); diff --git a/lib/appenders/stdout.js b/lib/appenders/stdout.js index b73a7ade..9f78b9f4 100644 --- a/lib/appenders/stdout.js +++ b/lib/appenders/stdout.js @@ -1,5 +1,3 @@ - - function stdoutAppender(layout, timezoneOffset) { return (loggingEvent) => { process.stdout.write(`${layout(loggingEvent, timezoneOffset)}\n`); diff --git a/lib/appenders/tcp-server.js b/lib/appenders/tcp-server.js index 222fe5ce..3459c311 100644 --- a/lib/appenders/tcp-server.js +++ b/lib/appenders/tcp-server.js @@ -20,9 +20,11 @@ exports.configure = (config) => { } else { dataSoFar = ''; } - events.filter(e => e.length).forEach((e) => { - clustering.send(LoggingEvent.deserialise(e)); - }); + events + .filter((e) => e.length) + .forEach((e) => { + clustering.send(LoggingEvent.deserialise(e)); + }); } else { dataSoFar = ''; } @@ -42,6 +44,6 @@ exports.configure = (config) => { shutdown: (cb) => { debug('shutdown called.'); server.close(cb); - } + }, }; }; diff --git a/lib/appenders/tcp.js b/lib/appenders/tcp.js index 8098d48f..5a9854a3 100644 --- a/lib/appenders/tcp.js +++ b/lib/appenders/tcp.js @@ -1,5 +1,3 @@ - - const debug = require('debug')('log4js:tcp'); const net = require('net'); @@ -24,9 +22,16 @@ function appender(config, layout) { } function createSocket() { - debug(`appender creating socket to ${config.host || 'localhost'}:${config.port || 5000}`); + debug( + `appender creating socket to ${config.host || 'localhost'}:${ + config.port || 5000 + }` + ); endMsg = `${config.endMsg || '__LOG4JS__'}`; - socket = net.createConnection(config.port || 5000, config.host || 'localhost'); + socket = net.createConnection( + config.port || 5000, + config.host || 'localhost' + ); socket.on('connect', () => { debug('socket connected'); emptyBuffer(); diff --git a/lib/categories.js b/lib/categories.js index 18c3c1df..10ed016a 100644 --- a/lib/categories.js +++ b/lib/categories.js @@ -22,7 +22,6 @@ function inheritFromParent(config, category, categoryName) { const parentCategoryName = categoryName.slice(0, lastDotIndex); let parentCategory = config.categories[parentCategoryName]; - if (!parentCategory) { // parent is missing, so implicitly create it, so that it can inherit from its parents parentCategory = { inherit: true, appenders: [] }; @@ -33,10 +32,12 @@ function inheritFromParent(config, category, categoryName) { // if the parent is not in the config (because we just created it above), // and it inherited a valid configuration, add it to config.categories - if (!config.categories[parentCategoryName] - && parentCategory.appenders - && parentCategory.appenders.length - && parentCategory.level) { + if ( + !config.categories[parentCategoryName] && + parentCategory.appenders && + parentCategory.appenders.length && + parentCategory.level + ) { config.categories[parentCategoryName] = parentCategory; } @@ -52,7 +53,6 @@ function inheritFromParent(config, category, categoryName) { category.parent = parentCategory; } - /** * Walk all categories in the config, and pull down any configuration from parent to child. * This includes inherited appenders, and level, where level is not set. @@ -69,7 +69,9 @@ function addCategoryInheritance(config) { }); } -configuration.addPreProcessingListener(config => addCategoryInheritance(config)); +configuration.addPreProcessingListener((config) => + addCategoryInheritance(config) +); configuration.addListener((config) => { configuration.throwExceptionIf( @@ -91,7 +93,7 @@ configuration.addListener((config) => { config, [ configuration.not(category.appenders), - configuration.not(category.level) + configuration.not(category.level), ], `category "${name}" is not valid (must be an object with properties "appenders" and "level")` ); @@ -127,8 +129,8 @@ configuration.addListener((config) => { configuration.throwExceptionIf( config, configuration.not(levels.getLevel(category.level)), - `category "${name}" is not valid (level "${category.level}" not recognised;` - + ` valid levels are ${levels.levels.join(', ')})` + `category "${name}" is not valid (level "${category.level}" not recognised;` + + ` valid levels are ${levels.levels.join(', ')})` ); }); @@ -152,14 +154,11 @@ const setup = (config) => { category.appenders.forEach((appender) => { categoryAppenders.push(appenders.get(appender)); debug(`Creating category ${name}`); - categories.set( - name, - { - appenders: categoryAppenders, - level: levels.getLevel(category.level), - enableCallStack: category.enableCallStack || false - } - ); + categories.set(name, { + appenders: categoryAppenders, + level: levels.getLevel(category.level), + enableCallStack: category.enableCallStack || false, + }); }); }); }; @@ -181,7 +180,9 @@ const configForCategory = (category) => { let sourceCategoryConfig; if (category.indexOf('.') > 0) { debug(`configForCategory: ${category} has hierarchy, cloning from parents`); - sourceCategoryConfig = { ...configForCategory(category.slice(0, category.lastIndexOf('.'))) }; + sourceCategoryConfig = { + ...configForCategory(category.slice(0, category.lastIndexOf('.'))), + }; } else { if (!categories.has('default')) { setup({ categories: { default: { appenders: ['out'], level: 'OFF' } } }); @@ -193,14 +194,16 @@ const configForCategory = (category) => { return sourceCategoryConfig; }; -const appendersForCategory = category => configForCategory(category).appenders; +const appendersForCategory = (category) => + configForCategory(category).appenders; -const getLevelForCategory = category => configForCategory(category).level; +const getLevelForCategory = (category) => configForCategory(category).level; const setLevelForCategory = (category, level) => { configForCategory(category).level = level; }; -const getEnableCallStackForCategory = category => configForCategory(category).enableCallStack === true; +const getEnableCallStackForCategory = (category) => + configForCategory(category).enableCallStack === true; const setEnableCallStackForCategory = (category, useCallStack) => { configForCategory(category).enableCallStack = useCallStack; }; diff --git a/lib/clustering.js b/lib/clustering.js index fefe9764..ba445e79 100644 --- a/lib/clustering.js +++ b/lib/clustering.js @@ -1,54 +1,55 @@ -const debug = require("debug")("log4js:clustering"); -const LoggingEvent = require("./LoggingEvent"); -const configuration = require("./configuration"); +const debug = require('debug')('log4js:clustering'); +const LoggingEvent = require('./LoggingEvent'); +const configuration = require('./configuration'); let disabled = false; let cluster = null; try { // eslint-disable-next-line global-require - cluster = require("cluster"); + cluster = require('cluster'); } catch (e) { - debug("cluster module not present"); + debug('cluster module not present'); disabled = true; } const listeners = []; let pm2 = false; -let pm2InstanceVar = "NODE_APP_INSTANCE"; +let pm2InstanceVar = 'NODE_APP_INSTANCE'; -const isPM2Master = () => pm2 && process.env[pm2InstanceVar] === "0"; -const isMaster = () => disabled || (cluster && cluster.isMaster) || isPM2Master(); +const isPM2Master = () => pm2 && process.env[pm2InstanceVar] === '0'; +const isMaster = () => + disabled || (cluster && cluster.isMaster) || isPM2Master(); -const sendToListeners = logEvent => { - listeners.forEach(l => l(logEvent)); +const sendToListeners = (logEvent) => { + listeners.forEach((l) => l(logEvent)); }; // in a multi-process node environment, worker loggers will use // process.send const receiver = (worker, message) => { // prior to node v6, the worker parameter was not passed (args were message, handle) - debug("cluster message received from worker ", worker, ": ", message); + debug('cluster message received from worker ', worker, ': ', message); if (worker.topic && worker.data) { message = worker; worker = undefined; } - if (message && message.topic && message.topic === "log4js:message") { - debug("received message: ", message.data); + if (message && message.topic && message.topic === 'log4js:message') { + debug('received message: ', message.data); const logEvent = LoggingEvent.deserialise(message.data); sendToListeners(logEvent); } }; if (!disabled) { - configuration.addListener(config => { + configuration.addListener((config) => { // clear out the listeners, because configure has been called. listeners.length = 0; ({ pm2, disableClustering: disabled, - pm2InstanceVar = "NODE_APP_INSTANCE" + pm2InstanceVar = 'NODE_APP_INSTANCE', } = config); debug(`clustering disabled ? ${disabled}`); @@ -59,25 +60,25 @@ if (!disabled) { // just in case configure is called after shutdown if (pm2) { - process.removeListener("message", receiver); + process.removeListener('message', receiver); } if (cluster && cluster.removeListener) { - cluster.removeListener("message", receiver); + cluster.removeListener('message', receiver); } if (disabled || config.disableClustering) { - debug("Not listening for cluster messages, because clustering disabled."); + debug('Not listening for cluster messages, because clustering disabled.'); } else if (isPM2Master()) { // PM2 cluster support // PM2 runs everything as workers - install pm2-intercom for this to work. // we only want one of the app instances to write logs - debug("listening for PM2 broadcast messages"); - process.on("message", receiver); + debug('listening for PM2 broadcast messages'); + process.on('message', receiver); } else if (cluster && cluster.isMaster) { - debug("listening for cluster messages"); - cluster.on("message", receiver); + debug('listening for cluster messages'); + cluster.on('message', receiver); } else { - debug("not listening for messages, because we are not a master process"); + debug('not listening for messages, because we are not a master process'); } }); } @@ -85,20 +86,20 @@ if (!disabled) { module.exports = { onlyOnMaster: (fn, notMaster) => (isMaster() ? fn() : notMaster), isMaster, - send: msg => { + send: (msg) => { if (isMaster()) { sendToListeners(msg); } else { if (!pm2) { msg.cluster = { workerId: cluster.worker.id, - worker: process.pid + worker: process.pid, }; } - process.send({ topic: "log4js:message", data: msg.serialise() }); + process.send({ topic: 'log4js:message', data: msg.serialise() }); } }, - onMessage: listener => { + onMessage: (listener) => { listeners.push(listener); - } + }, }; diff --git a/lib/configuration.js b/lib/configuration.js index e3170c35..e02a4e55 100644 --- a/lib/configuration.js +++ b/lib/configuration.js @@ -1,18 +1,18 @@ - - const util = require('util'); const debug = require('debug')('log4js:configuration'); const preProcessingListeners = []; const listeners = []; -const not = thing => !thing; +const not = (thing) => !thing; -const anObject = thing => thing && typeof thing === 'object' && !Array.isArray(thing); +const anObject = (thing) => + thing && typeof thing === 'object' && !Array.isArray(thing); -const validIdentifier = thing => /^[A-Za-z][A-Za-z0-9_]*$/g.test(thing); +const validIdentifier = (thing) => /^[A-Za-z][A-Za-z0-9_]*$/g.test(thing); -const anInteger = thing => thing && typeof thing === 'number' && Number.isInteger(thing); +const anInteger = (thing) => + thing && typeof thing === 'number' && Number.isInteger(thing); const addListener = (fn) => { listeners.push(fn); @@ -21,7 +21,9 @@ const addListener = (fn) => { const addPreProcessingListener = (fn) => { preProcessingListeners.push(fn); - debug(`Added pre-processing listener, now ${preProcessingListeners.length} listeners`); + debug( + `Added pre-processing listener, now ${preProcessingListeners.length} listeners` + ); }; const throwExceptionIf = (config, checks, message) => { @@ -42,11 +44,11 @@ const configure = (candidate) => { throwExceptionIf(candidate, not(anObject(candidate)), 'must be an object.'); debug(`Calling pre-processing listeners (${preProcessingListeners.length})`); - preProcessingListeners.forEach(listener => listener(candidate)); + preProcessingListeners.forEach((listener) => listener(candidate)); debug('Configuration pre-processing finished.'); debug(`Calling configuration listeners (${listeners.length})`); - listeners.forEach(listener => listener(candidate)); + listeners.forEach((listener) => listener(candidate)); debug('Configuration finished.'); }; @@ -58,5 +60,5 @@ module.exports = { anObject, anInteger, validIdentifier, - not + not, }; diff --git a/lib/connect-logger.js b/lib/connect-logger.js index d39d371a..f3d3418c 100755 --- a/lib/connect-logger.js +++ b/lib/connect-logger.js @@ -1,9 +1,9 @@ /* eslint no-underscore-dangle: ["error", { "allow": ["__statusCode", "_remoteAddress", "__headers", "_logging"] }] */ -const levels = require("./levels"); +const levels = require('./levels'); const DEFAULT_FORMAT = - ":remote-addr - -" + + ':remote-addr - -' + ' ":method :url HTTP/:http-version"' + ' :status :content-length ":referrer"' + ' ":user-agent"'; @@ -32,7 +32,7 @@ function getUrl(req) { * @return {Array} */ function assembleTokens(req, res, customTokens) { - const arrayUniqueTokens = array => { + const arrayUniqueTokens = (array) => { const a = array.concat(); for (let i = 0; i < a.length; ++i) { for (let j = i + 1; j < a.length; ++j) { @@ -47,53 +47,53 @@ function assembleTokens(req, res, customTokens) { }; const defaultTokens = []; - defaultTokens.push({ token: ":url", replacement: getUrl(req) }); - defaultTokens.push({ token: ":protocol", replacement: req.protocol }); - defaultTokens.push({ token: ":hostname", replacement: req.hostname }); - defaultTokens.push({ token: ":method", replacement: req.method }); + defaultTokens.push({ token: ':url', replacement: getUrl(req) }); + defaultTokens.push({ token: ':protocol', replacement: req.protocol }); + defaultTokens.push({ token: ':hostname', replacement: req.hostname }); + defaultTokens.push({ token: ':method', replacement: req.method }); defaultTokens.push({ - token: ":status", - replacement: res.__statusCode || res.statusCode + token: ':status', + replacement: res.__statusCode || res.statusCode, }); defaultTokens.push({ - token: ":response-time", - replacement: res.responseTime + token: ':response-time', + replacement: res.responseTime, }); - defaultTokens.push({ token: ":date", replacement: new Date().toUTCString() }); + defaultTokens.push({ token: ':date', replacement: new Date().toUTCString() }); defaultTokens.push({ - token: ":referrer", - replacement: req.headers.referer || req.headers.referrer || "" + token: ':referrer', + replacement: req.headers.referer || req.headers.referrer || '', }); defaultTokens.push({ - token: ":http-version", - replacement: `${req.httpVersionMajor}.${req.httpVersionMinor}` + token: ':http-version', + replacement: `${req.httpVersionMajor}.${req.httpVersionMinor}`, }); defaultTokens.push({ - token: ":remote-addr", + token: ':remote-addr', replacement: - req.headers["x-forwarded-for"] || + req.headers['x-forwarded-for'] || req.ip || req._remoteAddress || (req.socket && (req.socket.remoteAddress || - (req.socket.socket && req.socket.socket.remoteAddress))) + (req.socket.socket && req.socket.socket.remoteAddress))), }); defaultTokens.push({ - token: ":user-agent", - replacement: req.headers["user-agent"] + token: ':user-agent', + replacement: req.headers['user-agent'], }); defaultTokens.push({ - token: ":content-length", + token: ':content-length', replacement: - res.getHeader("content-length") || - (res.__headers && res.__headers["Content-Length"]) || - "-" + res.getHeader('content-length') || + (res.__headers && res.__headers['Content-Length']) || + '-', }); defaultTokens.push({ token: /:req\[([^\]]+)]/g, replacement(_, field) { return req.headers[field.toLowerCase()]; - } + }, }); defaultTokens.push({ token: /:res\[([^\]]+)]/g, @@ -102,7 +102,7 @@ function assembleTokens(req, res, customTokens) { res.getHeader(field.toLowerCase()) || (res.__headers && res.__headers[field]) ); - } + }, }); return arrayUniqueTokens(customTokens.concat(defaultTokens)); @@ -157,14 +157,16 @@ function createNoLogCondition(nolog) { regexp = nolog; } - if (typeof nolog === "string") { + if (typeof nolog === 'string') { regexp = new RegExp(nolog); } if (Array.isArray(nolog)) { // convert to strings - const regexpsAsStrings = nolog.map(reg => (reg.source ? reg.source : reg)); - regexp = new RegExp(regexpsAsStrings.join("|")); + const regexpsAsStrings = nolog.map((reg) => + reg.source ? reg.source : reg + ); + regexp = new RegExp(regexpsAsStrings.join('|')); } return regexp; @@ -190,7 +192,7 @@ function matchRules(statusCode, currentLevel, ruleSet) { let level = currentLevel; if (ruleSet) { - const matchedRule = ruleSet.find(rule => { + const matchedRule = ruleSet.find((rule) => { let ruleMatched = false; if (rule.from && rule.to) { ruleMatched = statusCode >= rule.from && statusCode <= rule.to; @@ -237,7 +239,7 @@ function matchRules(statusCode, currentLevel, ruleSet) { * @api public */ module.exports = function getLogger(logger4js, options) { - if (typeof options === "string" || typeof options === "function") { + if (typeof options === 'string' || typeof options === 'function') { options = { format: options }; } else { options = options || {}; @@ -255,7 +257,7 @@ module.exports = function getLogger(logger4js, options) { // nologs if (nolog && nolog.test(req.originalUrl)) return next(); - if (thisLogger.isLevelEnabled(level) || options.level === "auto") { + if (thisLogger.isLevelEnabled(level) || options.level === 'auto') { const start = new Date(); const { writeHead } = res; @@ -280,7 +282,7 @@ module.exports = function getLogger(logger4js, options) { finished = true; res.responseTime = new Date() - start; // status code response level handling - if (res.statusCode && options.level === "auto") { + if (res.statusCode && options.level === 'auto') { level = levels.INFO; if (res.statusCode >= 300) level = levels.WARN; if (res.statusCode >= 400) level = levels.ERROR; @@ -289,19 +291,19 @@ module.exports = function getLogger(logger4js, options) { const combinedTokens = assembleTokens(req, res, options.tokens || []); - if (options.context) thisLogger.addContext("res", res); - if (typeof fmt === "function") { - const line = fmt(req, res, str => format(str, combinedTokens)); + if (options.context) thisLogger.addContext('res', res); + if (typeof fmt === 'function') { + const line = fmt(req, res, (str) => format(str, combinedTokens)); if (line) thisLogger.log(level, line); } else { thisLogger.log(level, format(fmt, combinedTokens)); } - if (options.context) thisLogger.removeContext("res"); + if (options.context) thisLogger.removeContext('res'); }; - res.on("end", handler); - res.on("finish", handler); - res.on("error", handler); - res.on("close", handler); + res.on('end', handler); + res.on('finish', handler); + res.on('error', handler); + res.on('close', handler); } // ensure next gets always called diff --git a/lib/layouts.js b/lib/layouts.js index 74254858..8e5325ba 100644 --- a/lib/layouts.js +++ b/lib/layouts.js @@ -21,7 +21,7 @@ const styles = { green: [32, 39], magenta: [35, 39], red: [91, 39], - yellow: [33, 39] + yellow: [33, 39], }; function colorizeStart(style) { @@ -61,7 +61,9 @@ function timestampLevelAndCategory(loggingEvent, colour) { * @author Stephan Strittmatter */ function basicLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent) + util.format(...loggingEvent.data); + return ( + timestampLevelAndCategory(loggingEvent) + util.format(...loggingEvent.data) + ); } /** @@ -69,7 +71,10 @@ function basicLayout(loggingEvent) { * same as basicLayout, but with colours. */ function colouredLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent, loggingEvent.level.colour) + util.format(...loggingEvent.data); + return ( + timestampLevelAndCategory(loggingEvent, loggingEvent.level.colour) + + util.format(...loggingEvent.data) + ); } function messagePassThroughLayout(loggingEvent) { @@ -125,7 +130,8 @@ function dummyLayout(loggingEvent) { */ function patternLayout(pattern, tokens) { const TTCC_CONVERSION_PATTERN = '%r %p %c - %m%n'; - const regex = /%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/; + const regex = + /%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/; pattern = pattern || TTCC_CONVERSION_PATTERN; @@ -135,7 +141,9 @@ function patternLayout(pattern, tokens) { const precision = parseInt(specifier, 10); const loggerNameBits = loggerName.split('.'); if (precision < loggerNameBits.length) { - loggerName = loggerNameBits.slice(loggerNameBits.length - precision).join('.'); + loggerName = loggerNameBits + .slice(loggerNameBits.length - precision) + .join('.'); } } return loggerName; @@ -157,26 +165,32 @@ function patternLayout(pattern, tokens) { break; case 'ABSOLUTE': process.emitWarning( - "Pattern %d{ABSOLUTE} is deprecated in favor of %d{ABSOLUTETIME}. " + - "Please use %d{ABSOLUTETIME} instead.", - "DeprecationWarning", "log4js-node-DEP0003" + 'Pattern %d{ABSOLUTE} is deprecated in favor of %d{ABSOLUTETIME}. ' + + 'Please use %d{ABSOLUTETIME} instead.', + 'DeprecationWarning', + 'log4js-node-DEP0003' + ); + debug( + '[log4js-node-DEP0003]', + 'DEPRECATION: Pattern %d{ABSOLUTE} is deprecated and replaced by %d{ABSOLUTETIME}.' ); - debug("[log4js-node-DEP0003]", - "DEPRECATION: Pattern %d{ABSOLUTE} is deprecated and replaced by %d{ABSOLUTETIME}."); - // falls through + // falls through case 'ABSOLUTETIME': case 'ABSOLUTETIME_FORMAT': format = dateFormat.ABSOLUTETIME_FORMAT; break; case 'DATE': process.emitWarning( - "Pattern %d{DATE} is deprecated due to the confusion it causes when used. " + - "Please use %d{DATETIME} instead.", - "DeprecationWarning", "log4js-node-DEP0004" + 'Pattern %d{DATE} is deprecated due to the confusion it causes when used. ' + + 'Please use %d{DATETIME} instead.', + 'DeprecationWarning', + 'log4js-node-DEP0004' ); - debug("[log4js-node-DEP0004]", - "DEPRECATION: Pattern %d{DATE} is deprecated and replaced by %d{DATETIME}."); - // falls through + debug( + '[log4js-node-DEP0004]', + 'DEPRECATION: Pattern %d{DATE} is deprecated and replaced by %d{DATETIME}.' + ); + // falls through case 'DATETIME': case 'DATETIME_FORMAT': format = dateFormat.DATETIME_FORMAT; @@ -221,7 +235,9 @@ function patternLayout(pattern, tokens) { } function pid(loggingEvent) { - return loggingEvent && loggingEvent.pid ? loggingEvent.pid.toString() : process.pid.toString(); + return loggingEvent && loggingEvent.pid + ? loggingEvent.pid.toString() + : process.pid.toString(); } function clusterInfo() { @@ -233,7 +249,9 @@ function patternLayout(pattern, tokens) { function userDefined(loggingEvent, specifier) { if (typeof tokens[specifier] !== 'undefined') { - return typeof tokens[specifier] === 'function' ? tokens[specifier](loggingEvent) : tokens[specifier]; + return typeof tokens[specifier] === 'function' + ? tokens[specifier](loggingEvent) + : tokens[specifier]; } return null; @@ -266,7 +284,9 @@ function patternLayout(pattern, tokens) { // posix: file:///hello/world/foo.txt -> /hello/world/foo.txt -> /hello/world/foo.txt // win32: file:///C:/path/foo.txt -> /C:/path/foo.txt -> \C:\path\foo.txt -> C:\path\foo.txt // win32: file://nas/foo.txt -> //nas/foo.txt -> nas\foo.txt -> \\nas\foo.txt - filepath = path.normalize(filepath.replace(new RegExp(`^${urlPrefix}`), '')); + filepath = path.normalize( + filepath.replace(new RegExp(`^${urlPrefix}`), '') + ); if (process.platform === 'win32') { if (filepath.startsWith('\\')) { filepath = filepath.slice(1); @@ -321,7 +341,7 @@ function patternLayout(pattern, tokens) { f: fileName, l: lineNumber, o: columnNumber, - s: callStack + s: callStack, }; function replaceToken(conversionCharacter, loggingEvent, specifier) { @@ -385,7 +405,11 @@ function patternLayout(pattern, tokens) { } else { // Create a raw replacement string based on the conversion // character and specifier - const replacement = replaceToken(conversionCharacter, loggingEvent, specifier); + const replacement = replaceToken( + conversionCharacter, + loggingEvent, + specifier + ); formattedString += truncateAndPad(replacement, truncation, padding); } searchString = searchString.slice(result.index + result[0].length); @@ -395,24 +419,24 @@ function patternLayout(pattern, tokens) { } const layoutMakers = { - messagePassThrough () { + messagePassThrough() { return messagePassThroughLayout; }, - basic () { + basic() { return basicLayout; }, - colored () { + colored() { return colouredLayout; }, - coloured () { + coloured() { return colouredLayout; }, - pattern (config) { + pattern(config) { return patternLayout(config && config.pattern, config && config.tokens); }, - dummy () { + dummy() { return dummyLayout; - } + }, }; module.exports = { @@ -422,10 +446,10 @@ module.exports = { colouredLayout, coloredLayout: colouredLayout, dummyLayout, - addLayout (name, serializerGenerator) { + addLayout(name, serializerGenerator) { layoutMakers[name] = serializerGenerator; }, - layout (name, config) { + layout(name, config) { return layoutMakers[name] && layoutMakers[name](config); - } + }, }; diff --git a/lib/levels.js b/lib/levels.js index 80c346e8..4d319c8c 100644 --- a/lib/levels.js +++ b/lib/levels.js @@ -1,11 +1,15 @@ - - const configuration = require('./configuration'); const validColours = [ - 'white', 'grey', 'black', - 'blue', 'cyan', 'green', - 'magenta', 'red', 'yellow' + 'white', + 'grey', + 'black', + 'blue', + 'cyan', + 'green', + 'magenta', + 'red', + 'yellow', ]; class Level { @@ -52,7 +56,9 @@ class Level { levelStr, customLevels[l].colour ); - const existingLevelIndex = Level.levels.findIndex(lvl => lvl.levelStr === levelStr); + const existingLevelIndex = Level.levels.findIndex( + (lvl) => lvl.levelStr === levelStr + ); if (existingLevelIndex > -1) { Level.levels[existingLevelIndex] = Level[levelStr]; } else { @@ -63,7 +69,6 @@ class Level { } } - isLessThanOrEqualTo(otherLevel) { if (typeof otherLevel === 'string') { otherLevel = Level.getLevel(otherLevel); @@ -96,7 +101,7 @@ Level.addLevels({ ERROR: { value: 40000, colour: 'red' }, FATAL: { value: 50000, colour: 'magenta' }, MARK: { value: 9007199254740992, colour: 'grey' }, // 2^53 - OFF: { value: Number.MAX_VALUE, colour: 'grey' } + OFF: { value: Number.MAX_VALUE, colour: 'grey' }, }); configuration.addListener((config) => { diff --git a/lib/log4js.js b/lib/log4js.js index aef83c52..323ce11a 100644 --- a/lib/log4js.js +++ b/lib/log4js.js @@ -18,28 +18,28 @@ * @since 2005-05-20 * Website: http://log4js.berlios.de */ -const debug = require("debug")("log4js:main"); -const fs = require("fs"); -const deepClone = require("rfdc")({ proto: true }); -const configuration = require("./configuration"); -const layouts = require("./layouts"); -const levels = require("./levels"); -const appenders = require("./appenders"); -const categories = require("./categories"); -const Logger = require("./logger"); -const clustering = require("./clustering"); -const connectLogger = require("./connect-logger"); -const recordingModule = require("./appenders/recording"); +const debug = require('debug')('log4js:main'); +const fs = require('fs'); +const deepClone = require('rfdc')({ proto: true }); +const configuration = require('./configuration'); +const layouts = require('./layouts'); +const levels = require('./levels'); +const appenders = require('./appenders'); +const categories = require('./categories'); +const Logger = require('./logger'); +const clustering = require('./clustering'); +const connectLogger = require('./connect-logger'); +const recordingModule = require('./appenders/recording'); let enabled = false; function sendLogEventToAppender(logEvent) { if (!enabled) return; - debug("Received log event ", logEvent); + debug('Received log event ', logEvent); const categoryAppenders = categories.appendersForCategory( logEvent.categoryName ); - categoryAppenders.forEach(appender => { + categoryAppenders.forEach((appender) => { appender(logEvent); }); } @@ -47,7 +47,7 @@ function sendLogEventToAppender(logEvent) { function loadConfigurationFile(filename) { debug(`Loading configuration from ${filename}`); try { - return JSON.parse(fs.readFileSync(filename, "utf8")); + return JSON.parse(fs.readFileSync(filename, 'utf8')); } catch (e) { throw new Error( `Problem reading config from file "${filename}". Error was ${e.message}`, @@ -64,7 +64,7 @@ function configure(configurationFileOrObject) { let configObject = configurationFileOrObject; - if (typeof configObject === "string") { + if (typeof configObject === 'string') { configObject = loadConfigurationFile(configurationFileOrObject); } debug(`Configuration is ${configObject}`); @@ -80,7 +80,7 @@ function configure(configurationFileOrObject) { } function recording() { - return recordingModule + return recordingModule; } /** @@ -92,7 +92,7 @@ function recording() { * as the first argument. */ function shutdown(cb) { - debug("Shutdown called. Disabling all log writing."); + debug('Shutdown called. Disabling all log writing.'); // First, disable all writing to appenders. This prevents appenders from // not being able to be drained because of run-away log writes. enabled = false; @@ -110,7 +110,7 @@ function shutdown(cb) { 0 ); if (shutdownFunctions === 0) { - debug("No appenders with shutdown functions found."); + debug('No appenders with shutdown functions found.'); return cb !== undefined && cb(); } @@ -122,13 +122,15 @@ function shutdown(cb) { completed += 1; debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`); if (completed >= shutdownFunctions) { - debug("All shutdown functions completed."); + debug('All shutdown functions completed.'); if (cb) { cb(error); } } } - appendersToCheck.filter(a => a.shutdown).forEach(a => a.shutdown(complete)); + appendersToCheck + .filter((a) => a.shutdown) + .forEach((a) => a.shutdown(complete)); return null; } @@ -143,12 +145,12 @@ function getLogger(category) { if (!enabled) { configure( process.env.LOG4JS_CONFIG || { - appenders: { out: { type: "stdout" } }, - categories: { default: { appenders: ["out"], level: "OFF" } } + appenders: { out: { type: 'stdout' } }, + categories: { default: { appenders: ['out'], level: 'OFF' } }, } ); } - return new Logger(category || "default"); + return new Logger(category || 'default'); } /** diff --git a/lib/logger.js b/lib/logger.js index 0116d3b1..14385d6d 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -1,17 +1,17 @@ /* eslint no-underscore-dangle: ["error", { "allow": ["_log"] }] */ -const debug = require("debug")("log4js:logger"); -const LoggingEvent = require("./LoggingEvent"); -const levels = require("./levels"); -const clustering = require("./clustering"); -const categories = require("./categories"); -const configuration = require("./configuration"); +const debug = require('debug')('log4js:logger'); +const LoggingEvent = require('./LoggingEvent'); +const levels = require('./levels'); +const clustering = require('./clustering'); +const categories = require('./categories'); +const configuration = require('./configuration'); const stackReg = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/; function defaultParseCallStack(data, skipIdx = 4) { try { - const stacklines = data.stack.split("\n").slice(skipIdx); + const stacklines = data.stack.split('\n').slice(skipIdx); const lineMatch = stackReg.exec(stacklines[0]); /* istanbul ignore else: failsafe */ if (lineMatch && lineMatch.length === 6) { @@ -20,15 +20,14 @@ function defaultParseCallStack(data, skipIdx = 4) { fileName: lineMatch[2], lineNumber: parseInt(lineMatch[3], 10), columnNumber: parseInt(lineMatch[4], 10), - callStack: stacklines.join("\n") + callStack: stacklines.join('\n'), }; // eslint-disable-next-line no-else-return } else { // will never get here unless nodejs has changes to Error console.error('log4js.logger - defaultParseCallStack error'); // eslint-disable-line no-console } - } - catch (err) { + } catch (err) { // will never get error unless nodejs has breaking changes to Error console.error('log4js.logger - defaultParseCallStack error', err); // eslint-disable-line no-console } @@ -50,7 +49,7 @@ function defaultParseCallStack(data, skipIdx = 4) { class Logger { constructor(name) { if (!name) { - throw new Error("No category provided."); + throw new Error('No category provided.'); } this.category = name; this.context = {}; @@ -85,7 +84,11 @@ class Logger { if (!logLevel) { if (configuration.validIdentifier(level) && args.length > 0) { // logLevel not found but of valid signature, WARN before fallback to INFO - this.log(levels.WARN, 'log4js:logger.log: valid log-level not found as first parameter given:', level); + this.log( + levels.WARN, + 'log4js:logger.log: valid log-level not found as first parameter given:', + level + ); this.log(levels.INFO, `[${level}]`, ...args); } else { // apart from fallback, allow .log(...args) to be synonym with .log("INFO", ...args) @@ -133,7 +136,7 @@ function addLevelMethods(target) { const level = levels.getLevel(target); const levelStrLower = level.toString().toLowerCase(); - const levelMethod = levelStrLower.replace(/_([a-z])/g, g => + const levelMethod = levelStrLower.replace(/_([a-z])/g, (g) => g[1].toUpperCase() ); const isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1); diff --git a/test/.eslintrc b/test/.eslintrc index 985a565e..72248364 100644 --- a/test/.eslintrc +++ b/test/.eslintrc @@ -1,11 +1,11 @@ { "extends": "../.eslintrc", - "rules": { - "no-plusplus": 0, + "rules": { + "no-plusplus": 0, "global-require": 0, "no-mixed-operators": 0, "no-underscore-dangle": 0, "guard-for-in": 0, "no-restricted-syntax": ["error", "WithStatement"] - } + } } diff --git a/test/multiprocess-worker.js b/test/multiprocess-worker.js index 2a018753..f2e2dbf6 100644 --- a/test/multiprocess-worker.js +++ b/test/multiprocess-worker.js @@ -5,7 +5,7 @@ if (process.argv.indexOf('start-multiprocess-worker') >= 0) { appenders: { multi: { type: 'multiprocess', mode: 'worker', loggerPort: port }, }, - categories: { default: { appenders: ['multi'], level: 'debug' } } + categories: { default: { appenders: ['multi'], level: 'debug' } }, }); log4js.getLogger('worker').info('Logging from worker'); log4js.shutdown(() => { diff --git a/test/sandbox-coverage.js b/test/sandbox-coverage.js index 2d86361f..1632f427 100644 --- a/test/sandbox-coverage.js +++ b/test/sandbox-coverage.js @@ -1,13 +1,15 @@ -const sandbox = require("@log4js-node/sandboxed-module"); +const sandbox = require('@log4js-node/sandboxed-module'); sandbox.configure({ sourceTransformers: { nyc(source) { - if (this.filename.indexOf("node_modules") > -1) { + if (this.filename.indexOf('node_modules') > -1) { return source; } - const nyc = new (require("nyc"))({}); - return nyc.instrumenter().instrumentSync(source, this.filename, { registerMap: () => {} }); - } - } + const nyc = new (require('nyc'))({}); + return nyc + .instrumenter() + .instrumentSync(source, this.filename, { registerMap: () => {} }); + }, + }, }); diff --git a/test/tap/LoggingEvent-test.js b/test/tap/LoggingEvent-test.js index f8c8ec35..f3cd49ec 100644 --- a/test/tap/LoggingEvent-test.js +++ b/test/tap/LoggingEvent-test.js @@ -1,80 +1,85 @@ -const flatted = require("flatted"); -const { test } = require("tap"); -const LoggingEvent = require("../../lib/LoggingEvent"); -const levels = require("../../lib/levels"); +const flatted = require('flatted'); +const { test } = require('tap'); +const LoggingEvent = require('../../lib/LoggingEvent'); +const levels = require('../../lib/levels'); -test("LoggingEvent", batch => { - batch.test("should serialise to flatted", t => { - const event = new LoggingEvent("cheese", levels.DEBUG, ["log message", parseInt("abc", 10), 1/0, -1/0, undefined], { - user: "bob" - }); +test('LoggingEvent', (batch) => { + batch.test('should serialise to flatted', (t) => { + const event = new LoggingEvent( + 'cheese', + levels.DEBUG, + ['log message', parseInt('abc', 10), 1 / 0, -1 / 0, undefined], + { + user: 'bob', + } + ); // set the event date to a known value event.startTime = new Date(Date.UTC(2018, 1, 4, 18, 30, 23, 10)); const rehydratedEvent = flatted.parse(event.serialise()); - t.equal(rehydratedEvent.startTime, "2018-02-04T18:30:23.010Z"); - t.equal(rehydratedEvent.categoryName, "cheese"); - t.equal(rehydratedEvent.level.levelStr, "DEBUG"); + t.equal(rehydratedEvent.startTime, '2018-02-04T18:30:23.010Z'); + t.equal(rehydratedEvent.categoryName, 'cheese'); + t.equal(rehydratedEvent.level.levelStr, 'DEBUG'); t.equal(rehydratedEvent.data.length, 5); - t.equal(rehydratedEvent.data[0], "log message"); - t.equal(rehydratedEvent.data[1], "NaN"); - t.equal(rehydratedEvent.data[2], "Infinity"); - t.equal(rehydratedEvent.data[3], "-Infinity"); - t.equal(rehydratedEvent.data[4], "undefined"); - t.equal(rehydratedEvent.context.user, "bob"); + t.equal(rehydratedEvent.data[0], 'log message'); + t.equal(rehydratedEvent.data[1], 'NaN'); + t.equal(rehydratedEvent.data[2], 'Infinity'); + t.equal(rehydratedEvent.data[3], '-Infinity'); + t.equal(rehydratedEvent.data[4], 'undefined'); + t.equal(rehydratedEvent.context.user, 'bob'); t.end(); }); - batch.test("should deserialise from flatted", t => { + batch.test('should deserialise from flatted', (t) => { const dehydratedEvent = flatted.stringify({ - startTime: "2018-02-04T10:25:23.010Z", - categoryName: "biscuits", + startTime: '2018-02-04T10:25:23.010Z', + categoryName: 'biscuits', level: { - levelStr: "INFO" + levelStr: 'INFO', }, - data: ["some log message", { x: 1 }], - context: { thing: "otherThing" }, - pid: "1234", - functionName: "bound", - fileName: "domain.js", + data: ['some log message', { x: 1 }], + context: { thing: 'otherThing' }, + pid: '1234', + functionName: 'bound', + fileName: 'domain.js', lineNumber: 421, columnNumber: 15, - callStack: "at bound (domain.js:421:15)\n" + callStack: 'at bound (domain.js:421:15)\n', }); const event = LoggingEvent.deserialise(dehydratedEvent); t.type(event, LoggingEvent); t.same(event.startTime, new Date(Date.UTC(2018, 1, 4, 10, 25, 23, 10))); - t.equal(event.categoryName, "biscuits"); + t.equal(event.categoryName, 'biscuits'); t.same(event.level, levels.INFO); - t.equal(event.data[0], "some log message"); + t.equal(event.data[0], 'some log message'); t.equal(event.data[1].x, 1); - t.equal(event.context.thing, "otherThing"); - t.equal(event.pid, "1234"); - t.equal(event.functionName, "bound"); - t.equal(event.fileName, "domain.js"); + t.equal(event.context.thing, 'otherThing'); + t.equal(event.pid, '1234'); + t.equal(event.functionName, 'bound'); + t.equal(event.fileName, 'domain.js'); t.equal(event.lineNumber, 421); t.equal(event.columnNumber, 15); - t.equal(event.callStack, "at bound (domain.js:421:15)\n"); + t.equal(event.callStack, 'at bound (domain.js:421:15)\n'); t.end(); }); - batch.test("Should correct construct with/without location info", t => { + batch.test('Should correct construct with/without location info', (t) => { // console.log([Error('123').stack.split('\n').slice(1).join('\n')]) const callStack = - " at repl:1:14\n at ContextifyScript.Script.runInThisContext (vm.js:50:33)\n at REPLServer.defaultEval (repl.js:240:29)\n at bound (domain.js:301:14)\n at REPLServer.runBound [as eval] (domain.js:314:12)\n at REPLServer.onLine (repl.js:468:10)\n at emitOne (events.js:121:20)\n at REPLServer.emit (events.js:211:7)\n at REPLServer.Interface._onLine (readline.js:280:10)\n at REPLServer.Interface._line (readline.js:629:8)"; // eslint-disable-line max-len - const fileName = "/log4js-node/test/tap/layouts-test.js"; + ' at repl:1:14\n at ContextifyScript.Script.runInThisContext (vm.js:50:33)\n at REPLServer.defaultEval (repl.js:240:29)\n at bound (domain.js:301:14)\n at REPLServer.runBound [as eval] (domain.js:314:12)\n at REPLServer.onLine (repl.js:468:10)\n at emitOne (events.js:121:20)\n at REPLServer.emit (events.js:211:7)\n at REPLServer.Interface._onLine (readline.js:280:10)\n at REPLServer.Interface._line (readline.js:629:8)'; // eslint-disable-line max-len + const fileName = '/log4js-node/test/tap/layouts-test.js'; const lineNumber = 1; const columnNumber = 14; const location = { fileName, lineNumber, columnNumber, - callStack + callStack, }; const event = new LoggingEvent( - "cheese", + 'cheese', levels.DEBUG, - ["log message"], - { user: "bob" }, + ['log message'], + { user: 'bob' }, location ); t.equal(event.fileName, fileName); @@ -82,8 +87,8 @@ test("LoggingEvent", batch => { t.equal(event.columnNumber, columnNumber); t.equal(event.callStack, callStack); - const event2 = new LoggingEvent("cheese", levels.DEBUG, ["log message"], { - user: "bob" + const event2 = new LoggingEvent('cheese', levels.DEBUG, ['log message'], { + user: 'bob', }); t.equal(event2.fileName, undefined); t.equal(event2.lineNumber, undefined); diff --git a/test/tap/appender-dependencies-test.js b/test/tap/appender-dependencies-test.js index 75265a90..045c8c12 100644 --- a/test/tap/appender-dependencies-test.js +++ b/test/tap/appender-dependencies-test.js @@ -1,111 +1,108 @@ -const { test } = require("tap"); +const { test } = require('tap'); const categories = { - default: { appenders: ["filtered"], level: "debug" } -} + default: { appenders: ['filtered'], level: 'debug' }, +}; let log4js; let recording; -test("log4js appender dependencies", batch => { +test('log4js appender dependencies', (batch) => { batch.beforeEach(() => { - log4js = require("../../lib/log4js"); - recording = require("../../lib/appenders/recording"); + log4js = require('../../lib/log4js'); + recording = require('../../lib/appenders/recording'); }); batch.afterEach(() => { recording.erase(); }); - batch.test("in order", t => { + batch.test('in order', (t) => { const config = { categories, appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "logLevelFilter", - appender: "recorder", - level: "ERROR" - } - } + type: 'logLevelFilter', + appender: 'recorder', + level: 'ERROR', + }, + }, }; - t.test('should resolve if defined in dependency order', assert => { + t.test('should resolve if defined in dependency order', (assert) => { assert.doesNotThrow(() => { log4js.configure(config); }, 'this should not trigger an error'); assert.end(); }); - const logger = log4js.getLogger("logLevelTest"); - logger.debug("this should not trigger an event"); - logger.error("this should, though"); + const logger = log4js.getLogger('logLevelTest'); + logger.debug('this should not trigger an event'); + logger.error('this should, though'); const logEvents = recording.replay(); - t.test( - "should process log events normally", - assert => { - assert.equal(logEvents.length, 1); - assert.equal(logEvents[0].data[0], "this should, though"); - assert.end(); - } - ); + t.test('should process log events normally', (assert) => { + assert.equal(logEvents.length, 1); + assert.equal(logEvents[0].data[0], 'this should, though'); + assert.end(); + }); t.end(); }); - batch.test("not in order", t => { + batch.test('not in order', (t) => { const config = { categories, appenders: { filtered: { - type: "logLevelFilter", - appender: "recorder", - level: "ERROR" + type: 'logLevelFilter', + appender: 'recorder', + level: 'ERROR', }, - recorder: { type: "recording" }, - } + recorder: { type: 'recording' }, + }, }; - t.test('should resolve if defined out of dependency order', assert => { + t.test('should resolve if defined out of dependency order', (assert) => { assert.doesNotThrow(() => { log4js.configure(config); }, 'this should not trigger an error'); assert.end(); }); - const logger = log4js.getLogger("logLevelTest"); - logger.debug("this should not trigger an event"); - logger.error("this should, though"); + const logger = log4js.getLogger('logLevelTest'); + logger.debug('this should not trigger an event'); + logger.error('this should, though'); const logEvents = recording.replay(); - t.test( - "should process log events normally", - assert => { - assert.equal(logEvents.length, 1); - assert.equal(logEvents[0].data[0], "this should, though"); - assert.end(); - } - ); + t.test('should process log events normally', (assert) => { + assert.equal(logEvents.length, 1); + assert.equal(logEvents[0].data[0], 'this should, though'); + assert.end(); + }); t.end(); }); - batch.test("with dependency loop", t => { + batch.test('with dependency loop', (t) => { const config = { categories, appenders: { filtered: { - type: "logLevelFilter", - appender: "filtered2", - level: "ERROR" + type: 'logLevelFilter', + appender: 'filtered2', + level: 'ERROR', }, filtered2: { - type: "logLevelFilter", - appender: "filtered", - level: "ERROR" + type: 'logLevelFilter', + appender: 'filtered', + level: 'ERROR', }, - recorder: { type: "recording" }, - } + recorder: { type: 'recording' }, + }, }; - t.test('should throw an error if if a dependency loop is found', assert => { - assert.throws(() => { - log4js.configure(config); - }, 'Dependency loop detected for appender filtered.'); - assert.end(); - }); + t.test( + 'should throw an error if if a dependency loop is found', + (assert) => { + assert.throws(() => { + log4js.configure(config); + }, 'Dependency loop detected for appender filtered.'); + assert.end(); + } + ); t.end(); }); batch.end(); diff --git a/test/tap/categoryFilter-test.js b/test/tap/categoryFilter-test.js index 4ec52a84..af9bba7b 100644 --- a/test/tap/categoryFilter-test.js +++ b/test/tap/categoryFilter-test.js @@ -1,101 +1,101 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); -const recording = require("../../lib/appenders/recording"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); +const recording = require('../../lib/appenders/recording'); -test("log4js categoryFilter", batch => { +test('log4js categoryFilter', (batch) => { batch.beforeEach(() => { recording.reset(); }); - batch.test("appender should exclude categories", t => { + batch.test('appender should exclude categories', (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "categoryFilter", - exclude: "web", - appender: "recorder" - } + type: 'categoryFilter', + exclude: 'web', + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); - const webLogger = log4js.getLogger("web"); - const appLogger = log4js.getLogger("app"); + const webLogger = log4js.getLogger('web'); + const appLogger = log4js.getLogger('app'); - webLogger.debug("This should not get logged"); - appLogger.debug("This should get logged"); - webLogger.debug("Hello again"); + webLogger.debug('This should not get logged'); + appLogger.debug('This should get logged'); + webLogger.debug('Hello again'); log4js - .getLogger("db") - .debug("This should be included by the appender anyway"); + .getLogger('db') + .debug('This should be included by the appender anyway'); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "This should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); t.equal( logEvents[1].data[0], - "This should be included by the appender anyway" + 'This should be included by the appender anyway' ); t.end(); }); - batch.test("appender should exclude categories", t => { + batch.test('appender should exclude categories', (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "categoryFilter", - exclude: ["app", "web"], - appender: "recorder" - } + type: 'categoryFilter', + exclude: ['app', 'web'], + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); - const webLogger = log4js.getLogger("web"); - const appLogger = log4js.getLogger("app"); + const webLogger = log4js.getLogger('web'); + const appLogger = log4js.getLogger('app'); - webLogger.debug("This should not get logged"); - appLogger.debug("This should get logged"); - webLogger.debug("Hello again"); + webLogger.debug('This should not get logged'); + appLogger.debug('This should get logged'); + webLogger.debug('Hello again'); log4js - .getLogger("db") - .debug("This should be included by the appender anyway"); + .getLogger('db') + .debug('This should be included by the appender anyway'); const logEvents = recording.replay(); t.equal(logEvents.length, 1); t.equal( logEvents[0].data[0], - "This should be included by the appender anyway" + 'This should be included by the appender anyway' ); t.end(); }); - batch.test("should not really need a category filter any more", t => { + batch.test('should not really need a category filter any more', (t) => { log4js.configure({ - appenders: { recorder: { type: "recording" } }, + appenders: { recorder: { type: 'recording' } }, categories: { - default: { appenders: ["recorder"], level: "DEBUG" }, - web: { appenders: ["recorder"], level: "OFF" } - } + default: { appenders: ['recorder'], level: 'DEBUG' }, + web: { appenders: ['recorder'], level: 'OFF' }, + }, }); - const appLogger = log4js.getLogger("app"); - const webLogger = log4js.getLogger("web"); + const appLogger = log4js.getLogger('app'); + const webLogger = log4js.getLogger('web'); - webLogger.debug("This should not get logged"); - appLogger.debug("This should get logged"); - webLogger.debug("Hello again"); + webLogger.debug('This should not get logged'); + appLogger.debug('This should get logged'); + webLogger.debug('Hello again'); log4js - .getLogger("db") - .debug("This should be included by the appender anyway"); + .getLogger('db') + .debug('This should be included by the appender anyway'); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "This should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); t.equal( logEvents[1].data[0], - "This should be included by the appender anyway" + 'This should be included by the appender anyway' ); t.end(); }); diff --git a/test/tap/cluster-test.js b/test/tap/cluster-test.js index f25eb28d..e43cd059 100644 --- a/test/tap/cluster-test.js +++ b/test/tap/cluster-test.js @@ -1,62 +1,62 @@ -const { test } = require("tap"); -const cluster = require("cluster"); -const log4js = require("../../lib/log4js"); -const recorder = require("../../lib/appenders/recording"); +const { test } = require('tap'); +const cluster = require('cluster'); +const log4js = require('../../lib/log4js'); +const recorder = require('../../lib/appenders/recording'); log4js.configure({ appenders: { - vcr: { type: "recording" } + vcr: { type: 'recording' }, }, - categories: { default: { appenders: ["vcr"], level: "debug" } } + categories: { default: { appenders: ['vcr'], level: 'debug' } }, }); if (cluster.isMaster) { cluster.fork(); - const masterLogger = log4js.getLogger("master"); + const masterLogger = log4js.getLogger('master'); const masterPid = process.pid; - masterLogger.info("this is master"); + masterLogger.info('this is master'); let workerLevel; - cluster.on("message", (worker, message) => { + cluster.on('message', (worker, message) => { if (worker.type || worker.topic) { message = worker; } - if (message.type && message.type === "::testing") { + if (message.type && message.type === '::testing') { workerLevel = message.level; } }); - cluster.on("exit", worker => { + cluster.on('exit', (worker) => { const workerPid = worker.process.pid; const logEvents = recorder.replay(); - test("cluster master", batch => { - batch.test("events should be logged", t => { + test('cluster master', (batch) => { + batch.test('events should be logged', (t) => { t.equal(logEvents.length, 3); - t.equal(logEvents[0].categoryName, "master"); + t.equal(logEvents[0].categoryName, 'master'); t.equal(logEvents[0].pid, masterPid); - t.equal(logEvents[1].categoryName, "worker"); + t.equal(logEvents[1].categoryName, 'worker'); t.equal(logEvents[1].pid, workerPid); // serialising errors with stacks intact - t.type(logEvents[1].data[1], "Error"); - t.match(logEvents[1].data[1].stack, "Error: oh dear"); + t.type(logEvents[1].data[1], 'Error'); + t.match(logEvents[1].data[1].stack, 'Error: oh dear'); // serialising circular references in objects - t.type(logEvents[1].data[2], "object"); - t.type(logEvents[1].data[2].me, "object"); + t.type(logEvents[1].data[2], 'object'); + t.type(logEvents[1].data[2].me, 'object'); // serialising errors with custom properties - t.type(logEvents[1].data[3], "Error"); - t.match(logEvents[1].data[3].stack, "Error: wtf"); - t.equal(logEvents[1].data[3].alert, "chartreuse"); + t.type(logEvents[1].data[3], 'Error'); + t.match(logEvents[1].data[3].stack, 'Error: wtf'); + t.equal(logEvents[1].data[3].alert, 'chartreuse'); // serialising things that are not errors, but look a bit like them - t.type(logEvents[1].data[4], "object"); - t.equal(logEvents[1].data[4].stack, "this is not a stack trace"); + t.type(logEvents[1].data[4], 'object'); + t.equal(logEvents[1].data[4].stack, 'this is not a stack trace'); - t.equal(logEvents[2].categoryName, "log4js"); - t.equal(logEvents[2].level.toString(), "ERROR"); - t.equal(logEvents[2].data[0], "Unable to parse log:"); + t.equal(logEvents[2].categoryName, 'log4js'); + t.equal(logEvents[2].level.toString(), 'ERROR'); + t.equal(logEvents[2].data[0], 'Unable to parse log:'); t.end(); }); @@ -64,37 +64,37 @@ if (cluster.isMaster) { batch.end(); }); - test("cluster worker", batch => { - batch.test("logger should get correct config", t => { - t.equal(workerLevel, "DEBUG"); + test('cluster worker', (batch) => { + batch.test('logger should get correct config', (t) => { + t.equal(workerLevel, 'DEBUG'); t.end(); }); batch.end(); }); }); } else { - const workerLogger = log4js.getLogger("worker"); + const workerLogger = log4js.getLogger('worker'); // test for serialising circular references const circle = {}; circle.me = circle; // test for serialising errors with their own properties - const someError = new Error("wtf"); - someError.alert = "chartreuse"; + const someError = new Error('wtf'); + someError.alert = 'chartreuse'; // test for serialising things that look like errors but aren't. - const notAnError = { stack: "this is not a stack trace" }; + const notAnError = { stack: 'this is not a stack trace' }; workerLogger.info( - "this is worker", - new Error("oh dear"), + 'this is worker', + new Error('oh dear'), circle, someError, notAnError ); // can't run the test in the worker, things get weird process.send({ - type: "::testing", - level: workerLogger.level.toString() + type: '::testing', + level: workerLogger.level.toString(), }); // test sending a badly-formed log message - process.send({ topic: "log4js:message", data: { cheese: "gouda" } }); + process.send({ topic: 'log4js:message', data: { cheese: 'gouda' } }); cluster.worker.disconnect(); } diff --git a/test/tap/configuration-inheritance-test.js b/test/tap/configuration-inheritance-test.js index 9c2b9a47..ae49422b 100644 --- a/test/tap/configuration-inheritance-test.js +++ b/test/tap/configuration-inheritance-test.js @@ -1,326 +1,357 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); -const categories = require("../../lib/categories"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); +const categories = require('../../lib/categories'); -test("log4js category inherit all appenders from direct parent", batch => { - batch.test("should inherit appenders from direct parent", t => { +test('log4js category inherit all appenders from direct parent', (batch) => { + batch.test('should inherit appenders from direct parent', (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1", "stdout2"], level: "INFO" }, - "catA.catB": { level: "DEBUG" } - } + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1', 'stdout2'], level: 'INFO' }, + 'catA.catB': { level: 'DEBUG' }, + }, }; log4js.configure(config); - const childCategoryName = "catA.catB"; + const childCategoryName = 'catA.catB'; const childAppenders = categories.appendersForCategory(childCategoryName); const childLevel = categories.getLevelForCategory(childCategoryName); t.ok(childAppenders); - t.equal(childAppenders.length, 2, "inherited 2 appenders"); - t.ok(childAppenders.some(a => a.label === "stdout1"), "inherited stdout1"); - t.ok(childAppenders.some(a => a.label === "stdout2"), "inherited stdout2"); - t.equal(childLevel.levelStr, "DEBUG", "child level overrides parent"); + t.equal(childAppenders.length, 2, 'inherited 2 appenders'); + t.ok( + childAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' + ); + t.ok( + childAppenders.some((a) => a.label === 'stdout2'), + 'inherited stdout2' + ); + t.equal(childLevel.levelStr, 'DEBUG', 'child level overrides parent'); t.end(); }); batch.test( - "multiple children should inherit config from shared parent", - t => { + 'multiple children should inherit config from shared parent', + (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, - "catA.catB.cat1": { level: "DEBUG" }, // should get sdtout1, DEBUG - "catA.catB.cat2": { appenders: ["stdout2"] } // should get sdtout1,sdtout2, INFO - } + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, + 'catA.catB.cat1': { level: 'DEBUG' }, // should get sdtout1, DEBUG + 'catA.catB.cat2': { appenders: ['stdout2'] }, // should get sdtout1,sdtout2, INFO + }, }; log4js.configure(config); - const child1CategoryName = "catA.catB.cat1"; - const child1Appenders = categories.appendersForCategory( - child1CategoryName - ); + const child1CategoryName = 'catA.catB.cat1'; + const child1Appenders = + categories.appendersForCategory(child1CategoryName); const child1Level = categories.getLevelForCategory(child1CategoryName); - t.equal(child1Appenders.length, 1, "inherited 1 appender"); + t.equal(child1Appenders.length, 1, 'inherited 1 appender'); t.ok( - child1Appenders.some(a => a.label === "stdout1"), - "inherited stdout1" + child1Appenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' ); - t.equal(child1Level.levelStr, "DEBUG", "child level overrides parent"); + t.equal(child1Level.levelStr, 'DEBUG', 'child level overrides parent'); - const child2CategoryName = "catA.catB.cat2"; - const child2Appenders = categories.appendersForCategory( - child2CategoryName - ); + const child2CategoryName = 'catA.catB.cat2'; + const child2Appenders = + categories.appendersForCategory(child2CategoryName); const child2Level = categories.getLevelForCategory(child2CategoryName); t.ok(child2Appenders); t.equal( child2Appenders.length, 2, - "inherited 1 appenders, plus its original" + 'inherited 1 appenders, plus its original' ); t.ok( - child2Appenders.some(a => a.label === "stdout1"), - "inherited stdout1" + child2Appenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' ); - t.ok(child2Appenders.some(a => a.label === "stdout2"), "kept stdout2"); - t.equal(child2Level.levelStr, "INFO", "inherited parent level"); + t.ok( + child2Appenders.some((a) => a.label === 'stdout2'), + 'kept stdout2' + ); + t.equal(child2Level.levelStr, 'INFO', 'inherited parent level'); t.end(); } ); - batch.test("should inherit appenders from multiple parents", t => { + batch.test('should inherit appenders from multiple parents', (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, - "catA.catB": { appenders: ["stdout2"], level: "INFO" }, // should get stdout1 and stdout2 - "catA.catB.catC": { level: "DEBUG" } // should get stdout1 and stdout2 - } + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, + 'catA.catB': { appenders: ['stdout2'], level: 'INFO' }, // should get stdout1 and stdout2 + 'catA.catB.catC': { level: 'DEBUG' }, // should get stdout1 and stdout2 + }, }; log4js.configure(config); - const childCategoryName = "catA.catB.catC"; + const childCategoryName = 'catA.catB.catC'; const childAppenders = categories.appendersForCategory(childCategoryName); t.ok(childAppenders); - t.equal(childAppenders.length, 2, "inherited 2 appenders"); - t.ok(childAppenders.some(a => a.label === "stdout1"), "inherited stdout1"); - t.ok(childAppenders.some(a => a.label === "stdout1"), "inherited stdout1"); - - const firstParentName = "catA.catB"; - const firstParentAppenders = categories.appendersForCategory( - firstParentName + t.equal(childAppenders.length, 2, 'inherited 2 appenders'); + t.ok( + childAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' + ); + t.ok( + childAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' ); + const firstParentName = 'catA.catB'; + const firstParentAppenders = + categories.appendersForCategory(firstParentName); + t.ok(firstParentAppenders); - t.equal(firstParentAppenders.length, 2, "ended up with 2 appenders"); + t.equal(firstParentAppenders.length, 2, 'ended up with 2 appenders'); + t.ok( + firstParentAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' + ); t.ok( - firstParentAppenders.some(a => a.label === "stdout1"), - "inherited stdout1" + firstParentAppenders.some((a) => a.label === 'stdout2'), + 'kept stdout2' ); - t.ok(firstParentAppenders.some(a => a.label === "stdout2"), "kept stdout2"); t.end(); }); batch.test( - "should inherit appenders from deep parent with missing direct parent", - t => { + 'should inherit appenders from deep parent with missing direct parent', + (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, // no catA.catB, but should get created, with stdout1 - "catA.catB.catC": { level: "DEBUG" } // should get stdout1 - } + 'catA.catB.catC': { level: 'DEBUG' }, // should get stdout1 + }, }; log4js.configure(config); - const childCategoryName = "catA.catB.catC"; + const childCategoryName = 'catA.catB.catC'; const childAppenders = categories.appendersForCategory(childCategoryName); t.ok(childAppenders); - t.equal(childAppenders.length, 1, "inherited 1 appenders"); + t.equal(childAppenders.length, 1, 'inherited 1 appenders'); t.ok( - childAppenders.some(a => a.label === "stdout1"), - "inherited stdout1" + childAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' ); - const firstParentCategoryName = "catA.catB"; + const firstParentCategoryName = 'catA.catB'; const firstParentAppenders = categories.appendersForCategory( firstParentCategoryName ); - t.ok(firstParentAppenders, "catA.catB got created implicitily"); + t.ok(firstParentAppenders, 'catA.catB got created implicitily'); t.equal( firstParentAppenders.length, 1, - "created with 1 inherited appender" + 'created with 1 inherited appender' ); t.ok( - firstParentAppenders.some(a => a.label === "stdout1"), - "inherited stdout1" + firstParentAppenders.some((a) => a.label === 'stdout1'), + 'inherited stdout1' ); t.end(); } ); - batch.test("should deal gracefully with missing parent", t => { + batch.test('should deal gracefully with missing parent', (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, + default: { appenders: ['stdout1'], level: 'ERROR' }, // no catA nor catA.catB, but should get created, with default values - "catA.catB.catC": { appenders: ["stdout2"], level: "DEBUG" } // should get stdout2, DEBUG - } + 'catA.catB.catC': { appenders: ['stdout2'], level: 'DEBUG' }, // should get stdout2, DEBUG + }, }; log4js.configure(config); - const childCategoryName = "catA.catB.catC"; + const childCategoryName = 'catA.catB.catC'; const childAppenders = categories.appendersForCategory(childCategoryName); t.ok(childAppenders); t.equal(childAppenders.length, 1); - t.ok(childAppenders.some(a => a.label === "stdout2")); + t.ok(childAppenders.some((a) => a.label === 'stdout2')); t.end(); }); batch.test( - "should not get duplicate appenders if parent has the same one", - t => { + 'should not get duplicate appenders if parent has the same one', + (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1", "stdout2"], level: "INFO" }, - "catA.catB": { appenders: ["stdout1"], level: "DEBUG" } - } + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1', 'stdout2'], level: 'INFO' }, + 'catA.catB': { appenders: ['stdout1'], level: 'DEBUG' }, + }, }; log4js.configure(config); - const childCategoryName = "catA.catB"; + const childCategoryName = 'catA.catB'; const childAppenders = categories.appendersForCategory(childCategoryName); t.ok(childAppenders); - t.equal(childAppenders.length, 2, "inherited 1 appender"); + t.equal(childAppenders.length, 2, 'inherited 1 appender'); t.ok( - childAppenders.some(a => a.label === "stdout1"), - "still have stdout1" + childAppenders.some((a) => a.label === 'stdout1'), + 'still have stdout1' ); t.ok( - childAppenders.some(a => a.label === "stdout2"), - "inherited stdout2" + childAppenders.some((a) => a.label === 'stdout2'), + 'inherited stdout2' ); t.end(); } ); - batch.test("inherit:falses should disable inheritance", t => { + batch.test('inherit:falses should disable inheritance', (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, - "catA.catB": { appenders: ["stdout2"], level: "INFO", inherit: false } // should not inherit from catA - } + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, + 'catA.catB': { appenders: ['stdout2'], level: 'INFO', inherit: false }, // should not inherit from catA + }, }; log4js.configure(config); - const childCategoryName = "catA.catB"; + const childCategoryName = 'catA.catB'; const childAppenders = categories.appendersForCategory(childCategoryName); t.ok(childAppenders); - t.equal(childAppenders.length, 1, "inherited no appender"); - t.ok(childAppenders.some(a => a.label === "stdout2"), "kept stdout2"); + t.equal(childAppenders.length, 1, 'inherited no appender'); + t.ok( + childAppenders.some((a) => a.label === 'stdout2'), + 'kept stdout2' + ); t.end(); }); - batch.test("inheritance should stop if direct parent has inherit off", t => { - const config = { - appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } - }, - categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, - "catA.catB": { appenders: ["stdout2"], level: "INFO", inherit: false }, // should not inherit from catA - "catA.catB.catC": { level: "DEBUG" } // should inherit from catB only - } - }; + batch.test( + 'inheritance should stop if direct parent has inherit off', + (t) => { + const config = { + appenders: { + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, + }, + categories: { + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, + 'catA.catB': { + appenders: ['stdout2'], + level: 'INFO', + inherit: false, + }, // should not inherit from catA + 'catA.catB.catC': { level: 'DEBUG' }, // should inherit from catB only + }, + }; - log4js.configure(config); + log4js.configure(config); - const childCategoryName = "catA.catB.catC"; - const childAppenders = categories.appendersForCategory(childCategoryName); + const childCategoryName = 'catA.catB.catC'; + const childAppenders = categories.appendersForCategory(childCategoryName); - t.ok(childAppenders); - t.equal(childAppenders.length, 1, "inherited 1 appender"); - t.ok(childAppenders.some(a => a.label === "stdout2"), "inherited stdout2"); + t.ok(childAppenders); + t.equal(childAppenders.length, 1, 'inherited 1 appender'); + t.ok( + childAppenders.some((a) => a.label === 'stdout2'), + 'inherited stdout2' + ); - const firstParentCategoryName = "catA.catB"; - const firstParentAppenders = categories.appendersForCategory( - firstParentCategoryName - ); + const firstParentCategoryName = 'catA.catB'; + const firstParentAppenders = categories.appendersForCategory( + firstParentCategoryName + ); - t.ok(firstParentAppenders); - t.equal(firstParentAppenders.length, 1, "did not inherit new appenders"); - t.ok(firstParentAppenders.some(a => a.label === "stdout2"), "kept stdout2"); + t.ok(firstParentAppenders); + t.equal(firstParentAppenders.length, 1, 'did not inherit new appenders'); + t.ok( + firstParentAppenders.some((a) => a.label === 'stdout2'), + 'kept stdout2' + ); - t.end(); - }); + t.end(); + } + ); - batch.test("should inherit level when it is missing", t => { + batch.test('should inherit level when it is missing', (t) => { const config = { appenders: { - stdout1: { type: "dummy-appender", label: "stdout1" }, - stdout2: { type: "dummy-appender", label: "stdout2" } + stdout1: { type: 'dummy-appender', label: 'stdout1' }, + stdout2: { type: 'dummy-appender', label: 'stdout2' }, }, categories: { - default: { appenders: ["stdout1"], level: "ERROR" }, - catA: { appenders: ["stdout1"], level: "INFO" }, + default: { appenders: ['stdout1'], level: 'ERROR' }, + catA: { appenders: ['stdout1'], level: 'INFO' }, // no catA.catB, but should get created, with stdout1, level INFO - "catA.catB.catC": {} // should get stdout1, level INFO - } + 'catA.catB.catC': {}, // should get stdout1, level INFO + }, }; log4js.configure(config); - const childCategoryName = "catA.catB.catC"; + const childCategoryName = 'catA.catB.catC'; const childLevel = categories.getLevelForCategory(childCategoryName); - t.equal(childLevel.levelStr, "INFO", "inherited level"); + t.equal(childLevel.levelStr, 'INFO', 'inherited level'); - const firstParentCategoryName = "catA.catB"; + const firstParentCategoryName = 'catA.catB'; const firstParentLevel = categories.getLevelForCategory( firstParentCategoryName ); t.equal( firstParentLevel.levelStr, - "INFO", - "generate parent inherited level from base" + 'INFO', + 'generate parent inherited level from base' ); t.end(); diff --git a/test/tap/configuration-test.js b/test/tap/configuration-test.js index e54fcbc4..1fced152 100644 --- a/test/tap/configuration-test.js +++ b/test/tap/configuration-test.js @@ -1,15 +1,15 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); -const realFS = require("fs"); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); +const realFS = require('fs'); -const modulePath = "some/path/to/mylog4js.json"; +const modulePath = 'some/path/to/mylog4js.json'; const pathsChecked = []; let fakeFS = {}; let dependencies; let fileRead; -test("log4js configure", batch => { +test('log4js configure', (batch) => { batch.beforeEach(() => { fileRead = 0; @@ -22,50 +22,50 @@ test("log4js configure", batch => { config: { appenders: { console: { - type: "console", - layout: { type: "messagePassThrough" } - } + type: 'console', + layout: { type: 'messagePassThrough' }, + }, }, categories: { default: { - appenders: ["console"], - level: "INFO" - } - } + appenders: ['console'], + level: 'INFO', + }, + }, }, - readdirSync: dir => require("fs").readdirSync(dir), + readdirSync: (dir) => require('fs').readdirSync(dir), readFileSync: (file, encoding) => { fileRead += 1; - batch.type(file, "string"); + batch.type(file, 'string'); batch.equal(file, modulePath); - batch.equal(encoding, "utf8"); + batch.equal(encoding, 'utf8'); return JSON.stringify(fakeFS.config); }, - statSync: path => { + statSync: (path) => { pathsChecked.push(path); if (path === modulePath) { return { mtime: new Date() }; } - throw new Error("no such file"); - } + throw new Error('no such file'); + }, }; dependencies = { requires: { - fs: fakeFS - } + fs: fakeFS, + }, }; }); batch.test( - "when configuration file loaded via LOG4JS_CONFIG env variable", - t => { - process.env.LOG4JS_CONFIG = "some/path/to/mylog4js.json"; + 'when configuration file loaded via LOG4JS_CONFIG env variable', + (t) => { + process.env.LOG4JS_CONFIG = 'some/path/to/mylog4js.json'; - const log4js = sandbox.require("../../lib/log4js", dependencies); + const log4js = sandbox.require('../../lib/log4js', dependencies); - log4js.getLogger("test-logger"); - t.equal(fileRead, 1, "should load the specified local config file"); + log4js.getLogger('test-logger'); + t.equal(fileRead, 1, 'should load the specified local config file'); delete process.env.LOG4JS_CONFIG; @@ -74,24 +74,24 @@ test("log4js configure", batch => { ); batch.test( - "when configuration is set via configure() method call, return the log4js object", - t => { + 'when configuration is set via configure() method call, return the log4js object', + (t) => { const log4js = sandbox - .require("../../lib/log4js", dependencies) + .require('../../lib/log4js', dependencies) .configure(fakeFS.config); t.type( log4js, - "object", - "Configure method call should return the log4js object!" + 'object', + 'Configure method call should return the log4js object!' ); - const log = log4js.getLogger("daemon"); + const log = log4js.getLogger('daemon'); t.type( log, - "object", - "log4js object, returned by configure(...) method should be able to create log object." + 'object', + 'log4js object, returned by configure(...) method should be able to create log object.' ); - t.type(log.info, "function"); + t.type(log.info, 'function'); t.end(); } diff --git a/test/tap/configuration-validation-test.js b/test/tap/configuration-validation-test.js index 5f221377..401b5f97 100644 --- a/test/tap/configuration-validation-test.js +++ b/test/tap/configuration-validation-test.js @@ -1,17 +1,16 @@ -const { test } = require("tap"); -const util = require("util"); -const path = require("path"); -const sandbox = require("@log4js-node/sandboxed-module"); -const debug = require("debug")("log4js:test.configuration-validation"); -const deepFreeze = require("deep-freeze"); -const fs = require("fs"); -const log4js = require("../../lib/log4js"); -const configuration = require("../../lib/configuration"); - -const removeFiles = async filenames => { - if (!Array.isArray(filenames)) - filenames = [filenames]; - const promises = filenames.map(filename => fs.promises.unlink(filename)); +const { test } = require('tap'); +const util = require('util'); +const path = require('path'); +const sandbox = require('@log4js-node/sandboxed-module'); +const debug = require('debug')('log4js:test.configuration-validation'); +const deepFreeze = require('deep-freeze'); +const fs = require('fs'); +const log4js = require('../../lib/log4js'); +const configuration = require('../../lib/configuration'); + +const removeFiles = async (filenames) => { + if (!Array.isArray(filenames)) filenames = [filenames]; + const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; @@ -29,12 +28,12 @@ const testAppender = (label, result) => ({ result.layouts = layouts; result.findAppender = findAppender; return {}; - } + }, }); -test("log4js configuration validation", batch => { - batch.test("should give error if config is just plain silly", t => { - [null, undefined, "", " ", []].forEach(config => { +test('log4js configuration validation', (batch) => { + batch.test('should give error if config is just plain silly', (t) => { + [null, undefined, '', ' ', []].forEach((config) => { const expectedError = new Error( `Problem with log4js configuration: (${util.inspect( config @@ -46,7 +45,7 @@ test("log4js configuration validation", batch => { t.end(); }); - batch.test("should give error if config is an empty object", t => { + batch.test('should give error if config is an empty object', (t) => { t.throws( () => log4js.configure({}), '- must have a property "appenders" of type object.' @@ -54,7 +53,7 @@ test("log4js configuration validation", batch => { t.end(); }); - batch.test("should give error if config has no appenders", t => { + batch.test('should give error if config has no appenders', (t) => { t.throws( () => log4js.configure({ categories: {} }), '- must have a property "appenders" of type object.' @@ -62,15 +61,15 @@ test("log4js configuration validation", batch => { t.end(); }); - batch.test("should give error if config has no categories", t => { + batch.test('should give error if config has no categories', (t) => { t.throws( - () => log4js.configure({ appenders: { out: { type: "stdout" } } }), + () => log4js.configure({ appenders: { out: { type: 'stdout' } } }), '- must have a property "categories" of type object.' ); t.end(); }); - batch.test("should give error if appenders is not an object", t => { + batch.test('should give error if appenders is not an object', (t) => { t.throws( () => log4js.configure({ appenders: [], categories: [] }), '- must have a property "appenders" of type object.' @@ -78,77 +77,77 @@ test("log4js configuration validation", batch => { t.end(); }); - batch.test("should give error if appenders are not all valid", t => { + batch.test('should give error if appenders are not all valid', (t) => { t.throws( () => - log4js.configure({ appenders: { thing: "cheese" }, categories: {} }), + log4js.configure({ appenders: { thing: 'cheese' }, categories: {} }), '- appender "thing" is not valid (must be an object with property "type")' ); t.end(); }); - batch.test("should require at least one appender", t => { + batch.test('should require at least one appender', (t) => { t.throws( () => log4js.configure({ appenders: {}, categories: {} }), - "- must define at least one appender." + '- must define at least one appender.' ); t.end(); }); - batch.test("should give error if categories are not all valid", t => { + batch.test('should give error if categories are not all valid', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { thing: "cheese" } + appenders: { stdout: { type: 'stdout' } }, + categories: { thing: 'cheese' }, }), '- category "thing" is not valid (must be an object with properties "appenders" and "level")' ); t.end(); }); - batch.test("should give error if default category not defined", t => { + batch.test('should give error if default category not defined', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { thing: { appenders: ["stdout"], level: "ERROR" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { thing: { appenders: ['stdout'], level: 'ERROR' } }, }), '- must define a "default" category.' ); t.end(); }); - batch.test("should require at least one category", t => { + batch.test('should require at least one category', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: {} + appenders: { stdout: { type: 'stdout' } }, + categories: {}, }), - "- must define at least one category." + '- must define at least one category.' ); t.end(); }); - batch.test("should give error if category.appenders is not an array", t => { + batch.test('should give error if category.appenders is not an array', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { thing: { appenders: {}, level: "ERROR" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { thing: { appenders: {}, level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must be an array of appender names)' ); t.end(); }); - batch.test("should give error if category.appenders is empty", t => { + batch.test('should give error if category.appenders is empty', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { thing: { appenders: [], level: "ERROR" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { thing: { appenders: [], level: 'ERROR' } }, }), '- category "thing" is not valid (appenders must contain at least one appender name)' ); @@ -156,13 +155,13 @@ test("log4js configuration validation", batch => { }); batch.test( - "should give error if categories do not refer to valid appenders", - t => { + 'should give error if categories do not refer to valid appenders', + (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { thing: { appenders: ["cheese"], level: "ERROR" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { thing: { appenders: ['cheese'], level: 'ERROR' } }, }), '- category "thing" is not valid (appender "cheese" is not defined)' ); @@ -170,12 +169,12 @@ test("log4js configuration validation", batch => { } ); - batch.test("should give error if category level is not valid", t => { + batch.test('should give error if category level is not valid', (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "Biscuits" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'Biscuits' } }, }), '- category "default" is not valid (level "Biscuits" not recognised; valid levels are ALL, TRACE' ); @@ -183,19 +182,19 @@ test("log4js configuration validation", batch => { }); batch.test( - "should give error if category enableCallStack is not valid", - t => { + 'should give error if category enableCallStack is not valid', + (t) => { t.throws( () => log4js.configure({ - appenders: { stdout: { type: "stdout" } }, + appenders: { stdout: { type: 'stdout' } }, categories: { default: { - appenders: ["stdout"], - level: "Debug", - enableCallStack: "123" - } - } + appenders: ['stdout'], + level: 'Debug', + enableCallStack: '123', + }, + }, }), '- category "default" is not valid (enableCallStack must be boolean type)' ); @@ -203,49 +202,49 @@ test("log4js configuration validation", batch => { } ); - batch.test("should give error if appender type cannot be found", t => { + batch.test('should give error if appender type cannot be found', (t) => { t.throws( () => log4js.configure({ - appenders: { thing: { type: "cheese" } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + appenders: { thing: { type: 'cheese' } }, + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }), '- appender "thing" is not valid (type "cheese" could not be found)' ); t.end(); }); - batch.test("should create appender instances", t => { + batch.test('should create appender instances', (t) => { const thing = {}; - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { - cheese: testAppender("cheesy", thing) + cheese: testAppender('cheesy', thing), }, - ignoreMissing: true + ignoreMissing: true, }); sandboxedLog4js.configure({ - appenders: { thing: { type: "cheese" } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + appenders: { thing: { type: 'cheese' } }, + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); - t.equal(thing.type, "cheese"); + t.equal(thing.type, 'cheese'); t.end(); }); batch.test( - "should use provided appender instance if instance provided", - t => { + 'should use provided appender instance if instance provided', + (t) => { const thing = {}; - const cheese = testAppender("cheesy", thing); - const sandboxedLog4js = sandbox.require("../../lib/log4js", { - ignoreMissing: true + const cheese = testAppender('cheesy', thing); + const sandboxedLog4js = sandbox.require('../../lib/log4js', { + ignoreMissing: true, }); sandboxedLog4js.configure({ appenders: { thing: { type: cheese } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(thing.configureCalled); @@ -254,8 +253,8 @@ test("log4js configuration validation", batch => { } ); - batch.test("should not throw error if configure object is freezed", t => { - const testFile = "test/tap/freeze-date-file-test"; + batch.test('should not throw error if configure object is freezed', (t) => { + const testFile = 'test/tap/freeze-date-file-test'; t.teardown(async () => { await removeFiles(testFile); }); @@ -264,188 +263,193 @@ test("log4js configuration validation", batch => { deepFreeze({ appenders: { dateFile: { - type: "dateFile", + type: 'dateFile', filename: testFile, - alwaysIncludePattern: false - } + alwaysIncludePattern: false, + }, }, categories: { - default: { appenders: ["dateFile"], level: log4js.levels.ERROR } - } + default: { appenders: ['dateFile'], level: log4js.levels.ERROR }, + }, }) ) ); t.end(); }); - batch.test("should load appenders from core first", t => { + batch.test('should load appenders from core first', (t) => { const result = {}; - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { - "./cheese": testAppender("correct", result), - cheese: testAppender("wrong", result) + './cheese': testAppender('correct', result), + cheese: testAppender('wrong', result), }, - ignoreMissing: true + ignoreMissing: true, }); sandboxedLog4js.configure({ - appenders: { thing: { type: "cheese" } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + appenders: { thing: { type: 'cheese' } }, + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); - t.equal(result.type, "cheese"); - t.equal(result.label, "correct"); + t.equal(result.type, 'cheese'); + t.equal(result.label, 'correct'); t.end(); }); batch.test( - "should load appenders relative to main file if not in core, or node_modules", - t => { + 'should load appenders relative to main file if not in core, or node_modules', + (t) => { const result = {}; const mainPath = path.dirname(require.main.filename); const sandboxConfig = { ignoreMissing: true, - requires: {} + requires: {}, }; sandboxConfig.requires[`${mainPath}/cheese`] = testAppender( - "correct", + 'correct', result ); // add this one, because when we're running coverage the main path is a bit different sandboxConfig.requires[ - `${path.join(mainPath, "../../node_modules/nyc/bin/cheese")}` - ] = testAppender("correct", result); + `${path.join(mainPath, '../../node_modules/nyc/bin/cheese')}` + ] = testAppender('correct', result); // in tap v15, the main path is at root of log4js (run `DEBUG=log4js:appenders npm test > /dev/null` to check) - sandboxConfig.requires[ - `${path.join(mainPath, "../../cheese")}` - ] = testAppender("correct", result); + sandboxConfig.requires[`${path.join(mainPath, '../../cheese')}`] = + testAppender('correct', result); // in node v6, there's an extra layer of node modules for some reason, so add this one to work around it sandboxConfig.requires[ `${path.join( mainPath, - "../../node_modules/tap/node_modules/nyc/bin/cheese" + '../../node_modules/tap/node_modules/nyc/bin/cheese' )}` - ] = testAppender("correct", result); + ] = testAppender('correct', result); const sandboxedLog4js = sandbox.require( - "../../lib/log4js", + '../../lib/log4js', sandboxConfig ); sandboxedLog4js.configure({ - appenders: { thing: { type: "cheese" } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + appenders: { thing: { type: 'cheese' } }, + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); - t.equal(result.type, "cheese"); - t.equal(result.label, "correct"); + t.equal(result.type, 'cheese'); + t.equal(result.label, 'correct'); t.end(); } ); batch.test( - "should load appenders relative to process.cwd if not found in core, node_modules", - t => { + 'should load appenders relative to process.cwd if not found in core, node_modules', + (t) => { const result = {}; const fakeProcess = new Proxy(process, { get(target, key) { - if (key === "cwd") { - return () => "/var/lib/cheese"; + if (key === 'cwd') { + return () => '/var/lib/cheese'; } return target[key]; - } + }, }); // windows file paths are different to unix, so let's make this work for both. const requires = {}; - requires[path.join("/var", "lib", "cheese", "cheese")] = testAppender("correct", result); + requires[path.join('/var', 'lib', 'cheese', 'cheese')] = testAppender( + 'correct', + result + ); - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires, globals: { - process: fakeProcess - } + process: fakeProcess, + }, }); sandboxedLog4js.configure({ - appenders: { thing: { type: "cheese" } }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + appenders: { thing: { type: 'cheese' } }, + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); - t.equal(result.type, "cheese"); - t.equal(result.label, "correct"); + t.equal(result.type, 'cheese'); + t.equal(result.label, 'correct'); t.end(); } ); - batch.test("should pass config, layout, findAppender to appenders", t => { + batch.test('should pass config, layout, findAppender to appenders', (t) => { const result = {}; - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + const sandboxedLog4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires: { - cheese: testAppender("cheesy", result), - notCheese: testAppender("notCheesy", {}) - } + cheese: testAppender('cheesy', result), + notCheese: testAppender('notCheesy', {}), + }, }); sandboxedLog4js.configure({ appenders: { - thing: { type: "cheese", foo: "bar" }, - thing2: { type: "notCheese" } + thing: { type: 'cheese', foo: 'bar' }, + thing2: { type: 'notCheese' }, }, - categories: { default: { appenders: ["thing"], level: "ERROR" } } + categories: { default: { appenders: ['thing'], level: 'ERROR' } }, }); t.ok(result.configureCalled); - t.equal(result.type, "cheese"); - t.equal(result.config.foo, "bar"); - t.type(result.layouts, "object"); - t.type(result.layouts.basicLayout, "function"); - t.type(result.findAppender, "function"); - t.type(result.findAppender("thing2"), "object"); + t.equal(result.type, 'cheese'); + t.equal(result.config.foo, 'bar'); + t.type(result.layouts, 'object'); + t.type(result.layouts.basicLayout, 'function'); + t.type(result.findAppender, 'function'); + t.type(result.findAppender('thing2'), 'object'); t.end(); }); batch.test( - "should not give error if level object is used instead of string", - t => { + 'should not give error if level object is used instead of string', + (t) => { t.doesNotThrow(() => log4js.configure({ - appenders: { thing: { type: "stdout" } }, + appenders: { thing: { type: 'stdout' } }, categories: { - default: { appenders: ["thing"], level: log4js.levels.ERROR } - } + default: { appenders: ['thing'], level: log4js.levels.ERROR }, + }, }) ); t.end(); } ); - batch.test("should not create appender instance if not used in categories", t => { - const used = {}; - const notUsed = {}; - const sandboxedLog4js = sandbox.require("../../lib/log4js", { - requires: { - cat: testAppender("meow", used), - dog: testAppender("woof", notUsed) - }, - ignoreMissing: true - }); + batch.test( + 'should not create appender instance if not used in categories', + (t) => { + const used = {}; + const notUsed = {}; + const sandboxedLog4js = sandbox.require('../../lib/log4js', { + requires: { + cat: testAppender('meow', used), + dog: testAppender('woof', notUsed), + }, + ignoreMissing: true, + }); - sandboxedLog4js.configure({ - appenders: { used: { type: "cat" }, notUsed: { type: "dog" } }, - categories: { default: { appenders: ["used"], level: "ERROR" } } - }); + sandboxedLog4js.configure({ + appenders: { used: { type: 'cat' }, notUsed: { type: 'dog' } }, + categories: { default: { appenders: ['used'], level: 'ERROR' } }, + }); - t.ok(used.configureCalled); - t.notOk(notUsed.configureCalled); - t.end(); - }); + t.ok(used.configureCalled); + t.notOk(notUsed.configureCalled); + t.end(); + } + ); batch.end(); }); diff --git a/test/tap/connect-context-test.js b/test/tap/connect-context-test.js index ea8dfd8b..f8432229 100644 --- a/test/tap/connect-context-test.js +++ b/test/tap/connect-context-test.js @@ -1,8 +1,8 @@ /* eslint max-classes-per-file: ["error", 2] */ -const { test } = require("tap"); -const EE = require("events").EventEmitter; -const levels = require("../../lib/levels"); +const { test } = require('tap'); +const EE = require('events').EventEmitter; +const levels = require('../../lib/levels'); class MockLogger { constructor() { @@ -32,8 +32,8 @@ function MockRequest(remoteAddr, method, originalUrl) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.method = method; - this.httpVersionMajor = "5"; - this.httpVersionMinor = "0"; + this.httpVersionMajor = '5'; + this.httpVersionMinor = '0'; this.headers = {}; } @@ -45,7 +45,7 @@ class MockResponse extends EE { } end() { - this.emit("finish"); + this.emit('finish'); } setHeader(key, value) { @@ -61,10 +61,10 @@ class MockResponse extends EE { } } -test("log4js connect logger", batch => { - const clm = require("../../lib/connect-logger"); +test('log4js connect logger', (batch) => { + const clm = require('../../lib/connect-logger'); - batch.test("with context config", t => { + batch.test('with context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, { context: true }); @@ -72,18 +72,18 @@ test("log4js connect logger", batch => { ml.contexts = []; }); - t.test("response should be included in context", assert => { + t.test('response should be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); - assert.type(contexts, "Array"); + assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, MockResponse); assert.end(); @@ -92,7 +92,7 @@ test("log4js connect logger", batch => { t.end(); }); - batch.test("without context config", t => { + batch.test('without context config', (t) => { const ml = new MockLogger(); const cl = clm(ml, {}); @@ -100,18 +100,18 @@ test("log4js connect logger", batch => { ml.contexts = []; }); - t.test("response should not be included in context", assert => { + t.test('response should not be included in context', (assert) => { const { contexts } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); - assert.type(contexts, "Array"); + assert.type(contexts, 'Array'); assert.equal(contexts.length, 1); assert.type(contexts[0].res, undefined); assert.end(); diff --git a/test/tap/connect-logger-test.js b/test/tap/connect-logger-test.js index 7bc747e3..4119f319 100644 --- a/test/tap/connect-logger-test.js +++ b/test/tap/connect-logger-test.js @@ -1,17 +1,17 @@ /* eslint max-classes-per-file: ["error", 2] */ -const { test } = require("tap"); -const EE = require("events").EventEmitter; -const levels = require("../../lib/levels"); +const { test } = require('tap'); +const EE = require('events').EventEmitter; +const levels = require('../../lib/levels'); class MockLogger { constructor() { this.level = levels.TRACE; this.messages = []; - this.log = function(level, message) { + this.log = function (level, message) { this.messages.push({ level, message }); }; - this.isLevelEnabled = function(level) { + this.isLevelEnabled = function (level) { return level.isGreaterThanOrEqualTo(this.level); }; } @@ -22,8 +22,8 @@ function MockRequest(remoteAddr, method, originalUrl, headers, url, custom) { this.originalUrl = originalUrl; this.url = url; this.method = method; - this.httpVersionMajor = "5"; - this.httpVersionMinor = "0"; + this.httpVersionMajor = '5'; + this.httpVersionMinor = '0'; this.headers = headers || {}; if (custom) { @@ -33,7 +33,7 @@ function MockRequest(remoteAddr, method, originalUrl, headers, url, custom) { } const self = this; - Object.keys(this.headers).forEach(key => { + Object.keys(this.headers).forEach((key) => { self.headers[key.toLowerCase()] = self.headers[key]; }); } @@ -45,7 +45,7 @@ class MockResponse extends EE { } end() { - this.emit("finish"); + this.emit('finish'); } setHeader(key, value) { @@ -73,7 +73,7 @@ function request( custom = undefined ) { const req = new MockRequest( - "my.remote.addr", + 'my.remote.addr', method, originalUrl, reqHeaders, @@ -88,302 +88,302 @@ function request( } cl(req, res, next); res.writeHead(code, resHeaders); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); } -test("log4js connect logger", batch => { - const clm = require("../../lib/connect-logger"); - batch.test("getConnectLoggerModule", t => { - t.type(clm, "function", "should return a connect logger factory"); +test('log4js connect logger', (batch) => { + const clm = require('../../lib/connect-logger'); + batch.test('getConnectLoggerModule', (t) => { + t.type(clm, 'function', 'should return a connect logger factory'); t.test( 'should take a log4js logger and return a "connect logger"', - assert => { + (assert) => { const ml = new MockLogger(); const cl = clm(ml); - assert.type(cl, "function"); + assert.type(cl, 'function'); assert.end(); } ); - t.test("log events", assert => { + t.test('log events', (assert) => { const ml = new MockLogger(); const cl = clm(ml); - request(cl, "GET", "http://url", 200); + request(cl, 'GET', 'http://url', 200); const { messages } = ml; - assert.type(messages, "Array"); + assert.type(messages, 'Array'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("log events with level below logging level", assert => { + t.test('log events with level below logging level', (assert) => { const ml = new MockLogger(); ml.level = levels.FATAL; const cl = clm(ml); - request(cl, "GET", "http://url", 200); + request(cl, 'GET', 'http://url', 200); - assert.type(ml.messages, "Array"); + assert.type(ml.messages, 'Array'); assert.equal(ml.messages.length, 0); assert.end(); }); - t.test("log events with non-default level and custom format", assert => { + t.test('log events with non-default level and custom format', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, { level: levels.WARN, format: ":method :url" }); - request(cl, "GET", "http://url", 200); + const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); + request(cl, 'GET', 'http://url', 200); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); - assert.equal(messages[0].message, "GET http://url"); + assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); - t.test("adding multiple loggers should only log once", assert => { + t.test('adding multiple loggers should only log once', (assert) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, { level: levels.WARN, format: ":method :url" }); - const nextLogger = clm(ml, { level: levels.INFO, format: ":method" }); - request(cl, "GET", "http://url", 200, null, null, nextLogger); + const cl = clm(ml, { level: levels.WARN, format: ':method :url' }); + const nextLogger = clm(ml, { level: levels.INFO, format: ':method' }); + request(cl, 'GET', 'http://url', 200, null, null, nextLogger); const { messages } = ml; assert.type(messages, Array); assert.equal(messages.length, 1); assert.ok(levels.WARN.isEqualTo(messages[0].level)); - assert.equal(messages[0].message, "GET http://url"); + assert.equal(messages[0].message, 'GET http://url'); assert.end(); }); t.end(); }); - batch.test("logger with options as string", t => { + batch.test('logger with options as string', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, ":method :url"); - request(cl, "POST", "http://meh", 200); + const cl = clm(ml, ':method :url'); + request(cl, 'POST', 'http://meh', 200); const { messages } = ml; - t.equal(messages[0].message, "POST http://meh"); + t.equal(messages[0].message, 'POST http://meh'); t.end(); }); - batch.test("auto log levels", t => { + batch.test('auto log levels', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, { level: "auto", format: ":method :url" }); - request(cl, "GET", "http://meh", 200); - request(cl, "GET", "http://meh", 201); - request(cl, "GET", "http://meh", 302); - request(cl, "GET", "http://meh", 404); - request(cl, "GET", "http://meh", 500); + const cl = clm(ml, { level: 'auto', format: ':method :url' }); + request(cl, 'GET', 'http://meh', 200); + request(cl, 'GET', 'http://meh', 201); + request(cl, 'GET', 'http://meh', 302); + request(cl, 'GET', 'http://meh', 404); + request(cl, 'GET', 'http://meh', 500); const { messages } = ml; - t.test("should use INFO for 2xx", assert => { + t.test('should use INFO for 2xx', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[0].level)); assert.ok(levels.INFO.isEqualTo(messages[1].level)); assert.end(); }); - t.test("should use WARN for 3xx", assert => { + t.test('should use WARN for 3xx', (assert) => { assert.ok(levels.WARN.isEqualTo(messages[2].level)); assert.end(); }); - t.test("should use ERROR for 4xx", assert => { + t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[3].level)); assert.end(); }); - t.test("should use ERROR for 5xx", assert => { + t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); t.end(); }); - batch.test("logger with status code rules applied", t => { + batch.test('logger with status code rules applied', (t) => { const ml = new MockLogger(); ml.level = levels.DEBUG; const clr = [ { codes: [201, 304], level: levels.DEBUG.toString() }, { from: 200, to: 299, level: levels.DEBUG.toString() }, - { from: 300, to: 399, level: levels.INFO.toString() } + { from: 300, to: 399, level: levels.INFO.toString() }, ]; const cl = clm(ml, { - level: "auto", - format: ":method :url", - statusRules: clr + level: 'auto', + format: ':method :url', + statusRules: clr, }); - request(cl, "GET", "http://meh", 200); - request(cl, "GET", "http://meh", 201); - request(cl, "GET", "http://meh", 302); - request(cl, "GET", "http://meh", 304); - request(cl, "GET", "http://meh", 404); - request(cl, "GET", "http://meh", 500); + request(cl, 'GET', 'http://meh', 200); + request(cl, 'GET', 'http://meh', 201); + request(cl, 'GET', 'http://meh', 302); + request(cl, 'GET', 'http://meh', 304); + request(cl, 'GET', 'http://meh', 404); + request(cl, 'GET', 'http://meh', 500); const { messages } = ml; - t.test("should use DEBUG for 2xx", assert => { + t.test('should use DEBUG for 2xx', (assert) => { assert.ok(levels.DEBUG.isEqualTo(messages[0].level)); assert.ok(levels.DEBUG.isEqualTo(messages[1].level)); assert.end(); }); - t.test("should use WARN for 3xx, DEBUG for 304", assert => { + t.test('should use WARN for 3xx, DEBUG for 304', (assert) => { assert.ok(levels.INFO.isEqualTo(messages[2].level)); assert.ok(levels.DEBUG.isEqualTo(messages[3].level)); assert.end(); }); - t.test("should use ERROR for 4xx", assert => { + t.test('should use ERROR for 4xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[4].level)); assert.end(); }); - t.test("should use ERROR for 5xx", assert => { + t.test('should use ERROR for 5xx', (assert) => { assert.ok(levels.ERROR.isEqualTo(messages[5].level)); assert.end(); }); t.end(); }); - batch.test("format using a function", t => { + batch.test('format using a function', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, () => "I was called"); - request(cl, "GET", "http://blah", 200); + const cl = clm(ml, () => 'I was called'); + request(cl, 'GET', 'http://blah', 200); - t.equal(ml.messages[0].message, "I was called"); + t.equal(ml.messages[0].message, 'I was called'); t.end(); }); - batch.test("format using a function that also uses tokens", t => { + batch.test('format using a function that also uses tokens', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm( ml, - (req, res, tokenReplacer) => `${req.method} ${tokenReplacer(":status")}` + (req, res, tokenReplacer) => `${req.method} ${tokenReplacer(':status')}` ); - request(cl, "GET", "http://blah", 200); + request(cl, 'GET', 'http://blah', 200); - t.equal(ml.messages[0].message, "GET 200"); + t.equal(ml.messages[0].message, 'GET 200'); t.end(); }); batch.test( - "format using a function, but do not log anything if the function returns nothing", - t => { + 'format using a function, but do not log anything if the function returns nothing', + (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, () => null); - request(cl, "GET", "http://blah", 200); + request(cl, 'GET', 'http://blah', 200); t.equal(ml.messages.length, 0); t.end(); } ); - batch.test("format that includes request headers", t => { + batch.test('format that includes request headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, ":req[Content-Type]"); - request(cl, "GET", "http://blah", 200, { - "Content-Type": "application/json" + const cl = clm(ml, ':req[Content-Type]'); + request(cl, 'GET', 'http://blah', 200, { + 'Content-Type': 'application/json', }); - t.equal(ml.messages[0].message, "application/json"); + t.equal(ml.messages[0].message, 'application/json'); t.end(); }); - batch.test("format that includes response headers", t => { + batch.test('format that includes response headers', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; - const cl = clm(ml, ":res[Content-Type]"); - request(cl, "GET", "http://blah", 200, null, { - "Content-Type": "application/cheese" + const cl = clm(ml, ':res[Content-Type]'); + request(cl, 'GET', 'http://blah', 200, null, { + 'Content-Type': 'application/cheese', }); - t.equal(ml.messages[0].message, "application/cheese"); + t.equal(ml.messages[0].message, 'application/cheese'); t.end(); }); - batch.test("url token should check originalUrl and url", t => { + batch.test('url token should check originalUrl and url', (t) => { const ml = new MockLogger(); - const cl = clm(ml, ":url"); - request(cl, "GET", null, 200, null, null, null, "http://cheese"); + const cl = clm(ml, ':url'); + request(cl, 'GET', null, 200, null, null, null, 'http://cheese'); - t.equal(ml.messages[0].message, "http://cheese"); + t.equal(ml.messages[0].message, 'http://cheese'); t.end(); }); - batch.test("log events with custom token", t => { + batch.test('log events with custom token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, - format: ":method :url :custom_string", + format: ':method :url :custom_string', tokens: [ { - token: ":custom_string", - replacement: "fooBAR" - } - ] + token: ':custom_string', + replacement: 'fooBAR', + }, + ], }); - request(cl, "GET", "http://url", 200); + request(cl, 'GET', 'http://url', 200); - t.type(ml.messages, "Array"); + t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); - t.equal(ml.messages[0].message, "GET http://url fooBAR"); + t.equal(ml.messages[0].message, 'GET http://url fooBAR'); t.end(); }); - batch.test("log events with custom override token", t => { + batch.test('log events with custom override token', (t) => { const ml = new MockLogger(); ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, - format: ":method :url :date", + format: ':method :url :date', tokens: [ { - token: ":date", - replacement: "20150310" - } - ] + token: ':date', + replacement: '20150310', + }, + ], }); - request(cl, "GET", "http://url", 200); + request(cl, 'GET', 'http://url', 200); - t.type(ml.messages, "Array"); + t.type(ml.messages, 'Array'); t.equal(ml.messages.length, 1); t.ok(levels.INFO.isEqualTo(ml.messages[0].level)); - t.equal(ml.messages[0].message, "GET http://url 20150310"); + t.equal(ml.messages[0].message, 'GET http://url 20150310'); t.end(); }); - batch.test("log events with custom format", t => { + batch.test('log events with custom format', (t) => { const ml = new MockLogger(); - const body = { say: "hi!" }; + const body = { say: 'hi!' }; ml.level = levels.INFO; const cl = clm(ml, { level: levels.INFO, format: (req, res, format) => - format(`:method :url ${JSON.stringify(req.body)}`) + format(`:method :url ${JSON.stringify(req.body)}`), }); request( cl, - "POST", - "http://url", + 'POST', + 'http://url', 200, - { "Content-Type": "application/json" }, + { 'Content-Type': 'application/json' }, null, null, null, @@ -396,43 +396,43 @@ test("log4js connect logger", batch => { }); batch.test( - "handle weird old node versions where socket contains socket", - t => { + 'handle weird old node versions where socket contains socket', + (t) => { const ml = new MockLogger(); - const cl = clm(ml, ":remote-addr"); - const req = new MockRequest(null, "GET", "http://blah"); - req.socket = { socket: { remoteAddress: "this is weird" } }; + const cl = clm(ml, ':remote-addr'); + const req = new MockRequest(null, 'GET', 'http://blah'); + req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); - t.equal(ml.messages[0].message, "this is weird"); + t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); batch.test( - "handles as soon as any of the events end/finish/error/close triggers (only once)", - t => { + 'handles as soon as any of the events end/finish/error/close triggers (only once)', + (t) => { const ml = new MockLogger(); - const cl = clm(ml, ":remote-addr"); - const req = new MockRequest(null, "GET", "http://blah"); - req.socket = { socket: { remoteAddress: "this is weird" } }; + const cl = clm(ml, ':remote-addr'); + const req = new MockRequest(null, 'GET', 'http://blah'); + req.socket = { socket: { remoteAddress: 'this is weird' } }; const res = new MockResponse(); cl(req, res, () => {}); res.writeHead(200, {}); t.equal(ml.messages.length, 0); - res.emit("end"); - res.emit("finish"); - res.emit("error"); - res.emit("close"); + res.emit('end'); + res.emit('finish'); + res.emit('error'); + res.emit('close'); t.equal(ml.messages.length, 1); - t.equal(ml.messages[0].message, "this is weird"); + t.equal(ml.messages[0].message, 'this is weird'); t.end(); } ); diff --git a/test/tap/connect-nolog-test.js b/test/tap/connect-nolog-test.js index b53228ec..0f49d606 100644 --- a/test/tap/connect-nolog-test.js +++ b/test/tap/connect-nolog-test.js @@ -1,19 +1,19 @@ /* eslint max-classes-per-file: ["error", 2] */ -const { test } = require("tap"); -const EE = require("events").EventEmitter; -const levels = require("../../lib/levels"); +const { test } = require('tap'); +const EE = require('events').EventEmitter; +const levels = require('../../lib/levels'); class MockLogger { constructor() { this.messages = []; this.level = levels.TRACE; - this.log = function(level, message) { + this.log = function (level, message) { this.messages.push({ level, message }); }; - this.isLevelEnabled = function(level) { + this.isLevelEnabled = function (level) { return level.isGreaterThanOrEqualTo(this.level); }; } @@ -23,8 +23,8 @@ function MockRequest(remoteAddr, method, originalUrl) { this.socket = { remoteAddress: remoteAddr }; this.originalUrl = originalUrl; this.method = method; - this.httpVersionMajor = "5"; - this.httpVersionMinor = "0"; + this.httpVersionMajor = '5'; + this.httpVersionMinor = '0'; this.headers = {}; } @@ -36,7 +36,7 @@ class MockResponse extends EE { } end() { - this.emit("finish"); + this.emit('finish'); } setHeader(key, value) { @@ -52,109 +52,109 @@ class MockResponse extends EE { } } -test("log4js connect logger", batch => { - const clm = require("../../lib/connect-logger"); +test('log4js connect logger', (batch) => { + const clm = require('../../lib/connect-logger'); - batch.test("with nolog config", t => { + batch.test('with nolog config', (t) => { const ml = new MockLogger(); - const cl = clm(ml, { nolog: "\\.gif" }); + const cl = clm(ml, { nolog: '\\.gif' }); t.beforeEach(() => { ml.messages = []; }); - t.test("check unmatch url request", assert => { - const {messages} = ml; + t.test('check unmatch url request', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); - assert.type(messages, "Array"); + assert.type(messages, 'Array'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("check match url request", assert => { - const {messages} = ml; + t.test('check match url request', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.gif" + 'my.remote.addr', + 'GET', + 'http://url/hoge.gif' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); - assert.type(messages, "Array"); + assert.type(messages, 'Array'); assert.equal(messages.length, 0); assert.end(); }); t.end(); }); - batch.test("nolog Strings", t => { + batch.test('nolog Strings', (t) => { const ml = new MockLogger(); - const cl = clm(ml, { nolog: "\\.gif|\\.jpe?g" }); + const cl = clm(ml, { nolog: '\\.gif|\\.jpe?g' }); t.beforeEach(() => { ml.messages = []; }); - t.test("check unmatch url request (png)", assert => { - const {messages} = ml; + t.test('check unmatch url request (png)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("check match url request (gif)", assert => { - const {messages} = ml; + t.test('check match url request (gif)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.gif" + 'my.remote.addr', + 'GET', + 'http://url/hoge.gif' ); const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); }); - t.test("check match url request (jpeg)", assert => { - const {messages} = ml; + t.test('check match url request (jpeg)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.jpeg" + 'my.remote.addr', + 'GET', + 'http://url/hoge.jpeg' ); const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); @@ -163,59 +163,59 @@ test("log4js connect logger", batch => { t.end(); }); - batch.test("nolog Array", t => { + batch.test('nolog Array', (t) => { const ml = new MockLogger(); - const cl = clm(ml, { nolog: ["\\.gif", "\\.jpe?g"] }); + const cl = clm(ml, { nolog: ['\\.gif', '\\.jpe?g'] }); t.beforeEach(() => { ml.messages = []; }); - t.test("check unmatch url request (png)", assert => { - const {messages} = ml; + t.test('check unmatch url request (png)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("check match url request (gif)", assert => { - const {messages} = ml; + t.test('check match url request (gif)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.gif" + 'my.remote.addr', + 'GET', + 'http://url/hoge.gif' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); }); - t.test("check match url request (jpeg)", assert => { - const {messages} = ml; + t.test('check match url request (jpeg)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.jpeg" + 'my.remote.addr', + 'GET', + 'http://url/hoge.jpeg' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); @@ -224,7 +224,7 @@ test("log4js connect logger", batch => { t.end(); }); - batch.test("nolog RegExp", t => { + batch.test('nolog RegExp', (t) => { const ml = new MockLogger(); const cl = clm(ml, { nolog: /\.gif|\.jpe?g/ }); @@ -232,51 +232,51 @@ test("log4js connect logger", batch => { ml.messages = []; }); - t.test("check unmatch url request (png)", assert => { - const {messages} = ml; + t.test('check unmatch url request (png)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("check match url request (gif)", assert => { - const {messages} = ml; + t.test('check match url request (gif)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.gif" + 'my.remote.addr', + 'GET', + 'http://url/hoge.gif' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); }); - t.test("check match url request (jpeg)", assert => { - const {messages} = ml; + t.test('check match url request (jpeg)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.jpeg" + 'my.remote.addr', + 'GET', + 'http://url/hoge.jpeg' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); @@ -285,7 +285,7 @@ test("log4js connect logger", batch => { t.end(); }); - batch.test("nolog Array", t => { + batch.test('nolog Array', (t) => { const ml = new MockLogger(); const cl = clm(ml, { nolog: [/\.gif/, /\.jpe?g/] }); @@ -293,51 +293,51 @@ test("log4js connect logger", batch => { ml.messages = []; }); - t.test("check unmatch url request (png)", assert => { - const {messages} = ml; + t.test('check unmatch url request (png)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.png" + 'my.remote.addr', + 'GET', + 'http://url/hoge.png' ); // not gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 1); assert.ok(levels.INFO.isEqualTo(messages[0].level)); - assert.match(messages[0].message, "GET"); - assert.match(messages[0].message, "http://url"); - assert.match(messages[0].message, "my.remote.addr"); - assert.match(messages[0].message, "200"); + assert.match(messages[0].message, 'GET'); + assert.match(messages[0].message, 'http://url'); + assert.match(messages[0].message, 'my.remote.addr'); + assert.match(messages[0].message, '200'); assert.end(); }); - t.test("check match url request (gif)", assert => { - const {messages} = ml; + t.test('check match url request (gif)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.gif" + 'my.remote.addr', + 'GET', + 'http://url/hoge.gif' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); }); - t.test("check match url request (jpeg)", assert => { - const {messages} = ml; + t.test('check match url request (jpeg)', (assert) => { + const { messages } = ml; const req = new MockRequest( - "my.remote.addr", - "GET", - "http://url/hoge.jpeg" + 'my.remote.addr', + 'GET', + 'http://url/hoge.jpeg' ); // gif const res = new MockResponse(200); cl(req, res, () => {}); - res.end("chunk", "encoding"); + res.end('chunk', 'encoding'); assert.equal(messages.length, 0); assert.end(); diff --git a/test/tap/consoleAppender-test.js b/test/tap/consoleAppender-test.js index dfd7fe15..6853add9 100644 --- a/test/tap/consoleAppender-test.js +++ b/test/tap/consoleAppender-test.js @@ -1,58 +1,58 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); -const consoleAppender = require("../../lib/appenders/console"); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); +const consoleAppender = require('../../lib/appenders/console'); -test("log4js console appender", batch => { - batch.test("should export a configure function", t => { - t.type(consoleAppender.configure, "function"); +test('log4js console appender', (batch) => { + batch.test('should export a configure function', (t) => { + t.type(consoleAppender.configure, 'function'); t.end(); }); - batch.test("should use default layout if none specified", t => { + batch.test('should use default layout if none specified', (t) => { const messages = []; const fakeConsole = { log(msg) { messages.push(msg); - } + }, }; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { globals: { - console: fakeConsole - } + console: fakeConsole, + }, }); log4js.configure({ - appenders: { console: { type: "console" } }, - categories: { default: { appenders: ["console"], level: "DEBUG" } } + appenders: { console: { type: 'console' } }, + categories: { default: { appenders: ['console'], level: 'DEBUG' } }, }); - log4js.getLogger().info("blah"); + log4js.getLogger().info('blah'); t.match(messages[0], /.*default.*blah/); t.end(); }); - batch.test("should output to console", t => { + batch.test('should output to console', (t) => { const messages = []; const fakeConsole = { log(msg) { messages.push(msg); - } + }, }; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { globals: { - console: fakeConsole - } + console: fakeConsole, + }, }); log4js.configure({ appenders: { - console: { type: "console", layout: { type: "messagePassThrough" } } + console: { type: 'console', layout: { type: 'messagePassThrough' } }, }, - categories: { default: { appenders: ["console"], level: "DEBUG" } } + categories: { default: { appenders: ['console'], level: 'DEBUG' } }, }); - log4js.getLogger().info("blah"); + log4js.getLogger().info('blah'); - t.equal(messages[0], "blah"); + t.equal(messages[0], 'blah'); t.end(); }); diff --git a/test/tap/dateFileAppender-test.js b/test/tap/dateFileAppender-test.js index e1b0a120..3f6ca213 100644 --- a/test/tap/dateFileAppender-test.js +++ b/test/tap/dateFileAppender-test.js @@ -1,12 +1,12 @@ /* eslint max-classes-per-file: ["error", 3] */ -const { test } = require("tap"); -const path = require("path"); -const fs = require("fs"); -const EOL = require("os").EOL || "\n"; -const format = require("date-format"); -const sandbox = require("@log4js-node/sandboxed-module"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const path = require('path'); +const fs = require('fs'); +const EOL = require('os').EOL || '\n'; +const format = require('date-format'); +const sandbox = require('@log4js-node/sandboxed-module'); +const log4js = require('../../lib/log4js'); function removeFile(filename) { try { @@ -16,24 +16,24 @@ function removeFile(filename) { } } -test("../../lib/appenders/dateFile", batch => { - batch.test("with default settings", t => { - const testFile = path.join(__dirname, "date-appender-default.log"); +test('../../lib/appenders/dateFile', (batch) => { + batch.test('with default settings', (t) => { + const testFile = path.join(__dirname, 'date-appender-default.log'); log4js.configure({ - appenders: { date: { type: "dateFile", filename: testFile } }, - categories: { default: { appenders: ["date"], level: "DEBUG" } } + appenders: { date: { type: 'dateFile', filename: testFile } }, + categories: { default: { appenders: ['date'], level: 'DEBUG' } }, }); - const logger = log4js.getLogger("default-settings"); + const logger = log4js.getLogger('default-settings'); - logger.info("This should be in the file."); + logger.info('This should be in the file.'); t.teardown(() => { - removeFile("date-appender-default.log"); + removeFile('date-appender-default.log'); }); setTimeout(() => { - fs.readFile(testFile, "utf8", (err, contents) => { - t.match(contents, "This should be in the file"); + fs.readFile(testFile, 'utf8', (err, contents) => { + t.match(contents, 'This should be in the file'); t.match( contents, /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}] \[INFO] default-settings - / @@ -43,30 +43,30 @@ test("../../lib/appenders/dateFile", batch => { }, 100); }); - batch.test("configure with dateFileAppender", t => { + batch.test('configure with dateFileAppender', (t) => { log4js.configure({ appenders: { date: { - type: "dateFile", - filename: "test/tap/date-file-test.log", - pattern: "-yyyy-MM-dd", - layout: { type: "messagePassThrough" } - } + type: 'dateFile', + filename: 'test/tap/date-file-test.log', + pattern: '-yyyy-MM-dd', + layout: { type: 'messagePassThrough' }, + }, }, - categories: { default: { appenders: ["date"], level: "WARN" } } + categories: { default: { appenders: ['date'], level: 'WARN' } }, }); - const logger = log4js.getLogger("tests"); - logger.info("this should not be written to the file"); - logger.warn("this should be written to the file"); + const logger = log4js.getLogger('tests'); + logger.info('this should not be written to the file'); + logger.warn('this should be written to the file'); log4js.shutdown(() => { fs.readFile( - path.join(__dirname, "date-file-test.log"), - "utf8", + path.join(__dirname, 'date-file-test.log'), + 'utf8', (err, contents) => { t.match(contents, `this should be written to the file${EOL}`); t.equal( - contents.indexOf("this should not be written to the file"), + contents.indexOf('this should not be written to the file'), -1 ); t.end(); @@ -75,25 +75,25 @@ test("../../lib/appenders/dateFile", batch => { }); t.teardown(() => { - removeFile("date-file-test.log"); + removeFile('date-file-test.log'); }); }); - batch.test("configure with options.alwaysIncludePattern", t => { + batch.test('configure with options.alwaysIncludePattern', (t) => { const options = { appenders: { date: { - category: "tests", - type: "dateFile", - filename: "test/tap/date-file-test", - pattern: "yyyy-MM-dd.log", + category: 'tests', + type: 'dateFile', + filename: 'test/tap/date-file-test', + pattern: 'yyyy-MM-dd.log', alwaysIncludePattern: true, layout: { - type: "messagePassThrough" - } - } + type: 'messagePassThrough', + }, + }, }, - categories: { default: { appenders: ["date"], level: "debug" } } + categories: { default: { appenders: ['date'], level: 'debug' } }, }; const thisTime = format.asString( @@ -101,14 +101,11 @@ test("../../lib/appenders/dateFile", batch => { new Date() ); const testFile = `date-file-test.${thisTime}`; - const existingFile = path.join( - __dirname, - testFile - ); - fs.writeFileSync(existingFile, `this is existing data${EOL}`, "utf8"); + const existingFile = path.join(__dirname, testFile); + fs.writeFileSync(existingFile, `this is existing data${EOL}`, 'utf8'); log4js.configure(options); - const logger = log4js.getLogger("tests"); - logger.warn("this should be written to the file with the appended date"); + const logger = log4js.getLogger('tests'); + logger.warn('this should be written to the file with the appended date'); t.teardown(() => { removeFile(testFile); @@ -116,38 +113,38 @@ test("../../lib/appenders/dateFile", batch => { // wait for filesystem to catch up log4js.shutdown(() => { - fs.readFile(existingFile, "utf8", (err, contents) => { + fs.readFile(existingFile, 'utf8', (err, contents) => { t.match( contents, - "this is existing data", - "should not overwrite the file on open (issue #132)" + 'this is existing data', + 'should not overwrite the file on open (issue #132)' ); t.match( contents, - "this should be written to the file with the appended date" + 'this should be written to the file with the appended date' ); t.end(); }); }); }); - batch.test("should flush logs on shutdown", t => { - const testFile = path.join(__dirname, "date-appender-flush.log"); + batch.test('should flush logs on shutdown', (t) => { + const testFile = path.join(__dirname, 'date-appender-flush.log'); log4js.configure({ - appenders: { test: { type: "dateFile", filename: testFile } }, - categories: { default: { appenders: ["test"], level: "trace" } } + appenders: { test: { type: 'dateFile', filename: testFile } }, + categories: { default: { appenders: ['test'], level: 'trace' } }, }); - const logger = log4js.getLogger("default-settings"); + const logger = log4js.getLogger('default-settings'); - logger.info("1"); - logger.info("2"); - logger.info("3"); + logger.info('1'); + logger.info('2'); + logger.info('3'); t.teardown(() => { - removeFile("date-appender-flush.log"); + removeFile('date-appender-flush.log'); }); log4js.shutdown(() => { - fs.readFile(testFile, "utf8", (err, fileContents) => { + fs.readFile(testFile, 'utf8', (err, fileContents) => { // 3 lines of output, plus the trailing newline. t.equal(fileContents.split(EOL).length, 4); t.match( @@ -159,7 +156,7 @@ test("../../lib/appenders/dateFile", batch => { }); }); - batch.test("should map maxLogSize to maxSize", t => { + batch.test('should map maxLogSize to maxSize', (t) => { const fakeStreamroller = {}; class DateRollingFileStream { constructor(filename, pattern, options) { @@ -168,20 +165,20 @@ test("../../lib/appenders/dateFile", batch => { fakeStreamroller.options = options; } - on() { } // eslint-disable-line class-methods-use-this + on() {} // eslint-disable-line class-methods-use-this } fakeStreamroller.DateRollingFileStream = DateRollingFileStream; const dateFileAppenderModule = sandbox.require( - "../../lib/appenders/dateFile", + '../../lib/appenders/dateFile', { - requires: { streamroller: fakeStreamroller } + requires: { streamroller: fakeStreamroller }, } ); dateFileAppenderModule.configure( { - filename: "cheese.log", - pattern: "yyyy", - maxLogSize: 100 + filename: 'cheese.log', + pattern: 'yyyy', + maxLogSize: 100, }, { basicLayout: () => {} } ); @@ -190,7 +187,7 @@ test("../../lib/appenders/dateFile", batch => { t.end(); }); - batch.test("handling of writer.writable", t => { + batch.test('handling of writer.writable', (t) => { const output = []; let writable = true; @@ -202,47 +199,50 @@ test("../../lib/appenders/dateFile", batch => { } // eslint-disable-next-line class-methods-use-this - on() { - } + on() {} // eslint-disable-next-line class-methods-use-this get writable() { return writable; } }; - const dateFileAppender = sandbox.require("../../lib/appenders/dateFile", { + const dateFileAppender = sandbox.require('../../lib/appenders/dateFile', { requires: { streamroller: { - DateRollingFileStream - } - } + DateRollingFileStream, + }, + }, }); const appender = dateFileAppender.configure( - { filename: "test1.log", maxLogSize: 100 }, - { basicLayout(loggingEvent) { return loggingEvent.data; } } + { filename: 'test1.log', maxLogSize: 100 }, + { + basicLayout(loggingEvent) { + return loggingEvent.data; + }, + } ); - t.test("should log when writer.writable=true", assert => { + t.test('should log when writer.writable=true', (assert) => { writable = true; - appender({data: "something to log"}); + appender({ data: 'something to log' }); assert.ok(output.length, 1); - assert.match(output[output.length - 1], "something to log"); + assert.match(output[output.length - 1], 'something to log'); assert.end(); }); - t.test("should not log when writer.writable=false", assert => { + t.test('should not log when writer.writable=false', (assert) => { writable = false; - appender({data: "this should not be logged"}); + appender({ data: 'this should not be logged' }); assert.ok(output.length, 1); - assert.notMatch(output[output.length - 1], "this should not be logged"); + assert.notMatch(output[output.length - 1], 'this should not be logged'); assert.end(); }); t.end(); }); - batch.test("when underlying stream errors", t => { + batch.test('when underlying stream errors', (t) => { let consoleArgs; let errorHandler; @@ -252,7 +252,7 @@ test("../../lib/appenders/dateFile", batch => { } on(evt, cb) { - if (evt === "error") { + if (evt === 'error') { this.errored = true; errorHandler = cb; } @@ -263,35 +263,35 @@ test("../../lib/appenders/dateFile", batch => { return true; } }; - const dateFileAppender = sandbox.require("../../lib/appenders/dateFile", { + const dateFileAppender = sandbox.require('../../lib/appenders/dateFile', { globals: { console: { error(...args) { consoleArgs = args; - } - } + }, + }, }, requires: { streamroller: { - DateRollingFileStream - } - } + DateRollingFileStream, + }, + }, }); dateFileAppender.configure( - { filename: "test1.log", maxLogSize: 100 }, + { filename: 'test1.log', maxLogSize: 100 }, { basicLayout() {} } ); - errorHandler({ error: "aargh" }); + errorHandler({ error: 'aargh' }); - t.test("should log the error to console.error", assert => { + t.test('should log the error to console.error', (assert) => { assert.ok(consoleArgs); assert.equal( consoleArgs[0], - "log4js.dateFileAppender - Writing to file %s, error happened " + 'log4js.dateFileAppender - Writing to file %s, error happened ' ); - assert.equal(consoleArgs[1], "test1.log"); - assert.equal(consoleArgs[2].error, "aargh"); + assert.equal(consoleArgs[1], 'test1.log'); + assert.equal(consoleArgs[2].error, 'aargh'); assert.end(); }); t.end(); diff --git a/test/tap/default-settings-test.js b/test/tap/default-settings-test.js index 77359c53..f7720380 100644 --- a/test/tap/default-settings-test.js +++ b/test/tap/default-settings-test.js @@ -1,21 +1,25 @@ -const { test } = require("tap"); -const debug = require("debug"); -const sandbox = require("@log4js-node/sandboxed-module"); +const { test } = require('tap'); +const debug = require('debug'); +const sandbox = require('@log4js-node/sandboxed-module'); -test("default settings", batch => { - const originalListener = process.listeners("warning")[process.listeners("warning").length - 1]; - const warningListener = error => { - if (error.name === "DeprecationWarning") { - if (error.code.startsWith("log4js-node-DEP0001") || error.code.startsWith("log4js-node-DEP0002")) { +test('default settings', (batch) => { + const originalListener = + process.listeners('warning')[process.listeners('warning').length - 1]; + const warningListener = (error) => { + if (error.name === 'DeprecationWarning') { + if ( + error.code.startsWith('log4js-node-DEP0001') || + error.code.startsWith('log4js-node-DEP0002') + ) { return; } } originalListener(error); }; - process.off("warning", originalListener); - process.on("warning", warningListener); + process.off('warning', originalListener); + process.on('warning', warningListener); - const debugWasEnabled = debug.enabled("log4js:appenders"); + const debugWasEnabled = debug.enabled('log4js:appenders'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -30,98 +34,128 @@ test("default settings", batch => { batch.teardown(async () => { // next event loop so that past warnings will not be printed setImmediate(() => { - process.off("warning", warningListener); - process.on("warning", originalListener); + process.off('warning', warningListener); + process.on('warning', originalListener); }); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const output = []; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - "./appenders/stdout": { - name: "stdout", - appender() { // deprecated - return function(evt) { + './appenders/stdout': { + name: 'stdout', + appender() { + // deprecated + return function (evt) { output.push(evt); }; }, - shutdown() { // deprecated + shutdown() { + // deprecated }, configure() { return this.appender(); - } + }, }, - debug - } + debug, + }, }); let logger; - batch.test("should call configure() on getLogger() if not configured", t => { - const DEP0001 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0001") > -1).length; - const DEP0002 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0002") > -1).length; - logger = log4js.getLogger("default-settings"); - t.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0001") > -1).length, - DEP0001 + 1, - "deprecation log4js-node-DEP0001 emitted" - ); - t.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0002") > -1).length, - DEP0002 + 1, - "deprecation log4js-node-DEP0002 emitted" - ); - t.end(); - }); - - batch.test("nothing should be logged until level is set or configure() is called", t => { - const originalLevel = logger.level; - t.equal( - originalLevel.levelStr, - "OFF", - "default logger.level should be OFF" - ); + batch.test( + 'should call configure() on getLogger() if not configured', + (t) => { + const DEP0001 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0001') > -1 + ).length; + const DEP0002 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0002') > -1 + ).length; + logger = log4js.getLogger('default-settings'); + t.equal( + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0001') > -1).length, + DEP0001 + 1, + 'deprecation log4js-node-DEP0001 emitted' + ); + t.equal( + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0002') > -1).length, + DEP0002 + 1, + 'deprecation log4js-node-DEP0002 emitted' + ); + t.end(); + } + ); - logger.info("This should not be logged yet."); - t.equal(output.length, 0, "nothing should be logged"); + batch.test( + 'nothing should be logged until level is set or configure() is called', + (t) => { + const originalLevel = logger.level; + t.equal( + originalLevel.levelStr, + 'OFF', + 'default logger.level should be OFF' + ); - t.test("after level is set", assert => { - logger.level = "debug"; - logger.info("This should be logged."); - assert.equal(output.length, 1, "should log the message if level is set"); - assert.equal(output[output.length - 1].data[0], "This should be logged."); - logger.level = originalLevel; - assert.end(); - }); + logger.info('This should not be logged yet.'); + t.equal(output.length, 0, 'nothing should be logged'); - t.test("after configure() is called", assert => { - const DEP0001 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0001") > -1).length; - const DEP0002 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0002") > -1).length; - log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "debug" } } + t.test('after level is set', (assert) => { + logger.level = 'debug'; + logger.info('This should be logged.'); + assert.equal( + output.length, + 1, + 'should log the message if level is set' + ); + assert.equal( + output[output.length - 1].data[0], + 'This should be logged.' + ); + logger.level = originalLevel; + assert.end(); }); - assert.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0001") > -1).length, - DEP0001 + 1, - "deprecation log4js-node-DEP0001 emitted" - ); - assert.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0002") > -1).length, - DEP0002 + 1, - "deprecation log4js-node-DEP0002 emitted" - ); - logger.info("This should go to stdout."); - assert.equal(output.length, 2, "should log the message after configure() is called"); - assert.equal(output[output.length - 1].data[0], "This should go to stdout."); - assert.end(); - }); + t.test('after configure() is called', (assert) => { + const DEP0001 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0001') > -1 + ).length; + const DEP0002 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0002') > -1 + ).length; + log4js.configure({ + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'debug' } }, + }); + assert.equal( + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0001') > -1).length, + DEP0001 + 1, + 'deprecation log4js-node-DEP0001 emitted' + ); + assert.equal( + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0002') > -1).length, + DEP0002 + 1, + 'deprecation log4js-node-DEP0002 emitted' + ); - t.end(); - }); + logger.info('This should go to stdout.'); + assert.equal( + output.length, + 2, + 'should log the message after configure() is called' + ); + assert.equal( + output[output.length - 1].data[0], + 'This should go to stdout.' + ); + assert.end(); + }); + + t.end(); + } + ); batch.end(); }); diff --git a/test/tap/disable-cluster-test.js b/test/tap/disable-cluster-test.js index 4d3ed741..4128eaa6 100644 --- a/test/tap/disable-cluster-test.js +++ b/test/tap/disable-cluster-test.js @@ -1,34 +1,34 @@ -const { test } = require("tap"); -const cluster = require("cluster"); -const log4js = require("../../lib/log4js"); -const recorder = require("../../lib/appenders/recording"); +const { test } = require('tap'); +const cluster = require('cluster'); +const log4js = require('../../lib/log4js'); +const recorder = require('../../lib/appenders/recording'); cluster.removeAllListeners(); log4js.configure({ appenders: { - vcr: { type: "recording" } + vcr: { type: 'recording' }, }, - categories: { default: { appenders: ["vcr"], level: "debug" } }, - disableClustering: true + categories: { default: { appenders: ['vcr'], level: 'debug' } }, + disableClustering: true, }); if (cluster.isMaster) { cluster.fork(); - const masterLogger = log4js.getLogger("master"); + const masterLogger = log4js.getLogger('master'); const masterPid = process.pid; - masterLogger.info("this is master"); + masterLogger.info('this is master'); - cluster.on("exit", () => { + cluster.on('exit', () => { const logEvents = recorder.replay(); - test("cluster master", batch => { - batch.test("only master events should be logged", t => { + test('cluster master', (batch) => { + batch.test('only master events should be logged', (t) => { t.equal(logEvents.length, 1); - t.equal(logEvents[0].categoryName, "master"); + t.equal(logEvents[0].categoryName, 'master'); t.equal(logEvents[0].pid, masterPid); - t.equal(logEvents[0].data[0], "this is master"); + t.equal(logEvents[0].data[0], 'this is master'); t.end(); }); @@ -36,22 +36,22 @@ if (cluster.isMaster) { }); }); } else { - const workerLogger = log4js.getLogger("worker"); - workerLogger.info("this is worker", new Error("oh dear")); + const workerLogger = log4js.getLogger('worker'); + workerLogger.info('this is worker', new Error('oh dear')); const workerEvents = recorder.replay(); - test("cluster worker", batch => { - batch.test("should send events to its own appender", t => { + test('cluster worker', (batch) => { + batch.test('should send events to its own appender', (t) => { t.equal(workerEvents.length, 1); - t.equal(workerEvents[0].categoryName, "worker"); - t.equal(workerEvents[0].data[0], "this is worker"); - t.type(workerEvents[0].data[1], "Error"); - t.match(workerEvents[0].data[1].stack, "Error: oh dear"); + t.equal(workerEvents[0].categoryName, 'worker'); + t.equal(workerEvents[0].data[0], 'this is worker'); + t.type(workerEvents[0].data[1], 'Error'); + t.match(workerEvents[0].data[1].stack, 'Error: oh dear'); t.end(); }); batch.end(); }); // test sending a cluster-style log message - process.send({ topic: "log4js:message", data: { cheese: "gouda" } }); + process.send({ topic: 'log4js:message', data: { cheese: 'gouda' } }); cluster.worker.disconnect(); } diff --git a/test/tap/dummy-appender.js b/test/tap/dummy-appender.js index f59cebad..4d1b0309 100644 --- a/test/tap/dummy-appender.js +++ b/test/tap/dummy-appender.js @@ -1,6 +1,7 @@ // Dummy appender for test purposes; set config.label to identify instances in a test -function createDummyAppender() { // This is the function that generates an appender function +function createDummyAppender() { + // This is the function that generates an appender function // This is the appender function itself return (/* loggingEvent */) => { // do nothing diff --git a/test/tap/file-descriptor-leak-test.js b/test/tap/file-descriptor-leak-test.js index da2924d9..2a1b9373 100644 --- a/test/tap/file-descriptor-leak-test.js +++ b/test/tap/file-descriptor-leak-test.js @@ -1,80 +1,102 @@ -const { test } = require("tap"); -const fs = require("fs"); -const path = require("path"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const fs = require('fs'); +const path = require('path'); +const log4js = require('../../lib/log4js'); -const removeFiles = async filenames => { - if (!Array.isArray(filenames)) - filenames = [filenames]; - const promises = filenames.map(filename => fs.promises.unlink(filename)); +const removeFiles = async (filenames) => { + if (!Array.isArray(filenames)) filenames = [filenames]; + const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; // no file descriptors on Windows, so don't run the tests -if (process.platform !== "win32") { - - test("multiple log4js configure fd leak test", batch => { +if (process.platform !== 'win32') { + test('multiple log4js configure fd leak test', (batch) => { const config = { appenders: {}, categories: { - default: { appenders: [], level: 'debug' } - } + default: { appenders: [], level: 'debug' }, + }, }; // create 11 appenders const numOfAppenders = 11; for (let i = 1; i <= numOfAppenders; i++) { - config.appenders[`app${i}`] = { type: 'file', filename: path.join(__dirname, `file${i}.log`) }; + config.appenders[`app${i}`] = { + type: 'file', + filename: path.join(__dirname, `file${i}.log`), + }; config.categories.default.appenders.push(`app${i}`); } const initialFd = fs.readdirSync('/proc/self/fd').length; let loadedFd; - batch.test("initial log4js configure to increase file descriptor count", t => { - log4js.configure(config); + batch.test( + 'initial log4js configure to increase file descriptor count', + (t) => { + log4js.configure(config); - // wait for the file system to catch up - setTimeout(() => { - loadedFd = fs.readdirSync('/proc/self/fd').length; - t.equal(loadedFd, initialFd + numOfAppenders, - `file descriptor count should increase by ${numOfAppenders} after 1st configure() call`); - t.end(); - }, 250); - }); + // wait for the file system to catch up + setTimeout(() => { + loadedFd = fs.readdirSync('/proc/self/fd').length; + t.equal( + loadedFd, + initialFd + numOfAppenders, + `file descriptor count should increase by ${numOfAppenders} after 1st configure() call` + ); + t.end(); + }, 250); + } + ); - batch.test("repeated log4js configure to not increase file descriptor count", t => { - log4js.configure(config); - log4js.configure(config); - log4js.configure(config); + batch.test( + 'repeated log4js configure to not increase file descriptor count', + (t) => { + log4js.configure(config); + log4js.configure(config); + log4js.configure(config); - // wait for the file system to catch up - setTimeout(() => { - t.equal(fs.readdirSync('/proc/self/fd').length, loadedFd, - `file descriptor count should be identical after repeated configure() calls`); - t.end(); - }, 250); - }); + // wait for the file system to catch up + setTimeout(() => { + t.equal( + fs.readdirSync('/proc/self/fd').length, + loadedFd, + `file descriptor count should be identical after repeated configure() calls` + ); + t.end(); + }, 250); + } + ); - batch.test("file descriptor count should return back to initial count", t => { - log4js.shutdown(); + batch.test( + 'file descriptor count should return back to initial count', + (t) => { + log4js.shutdown(); - // wait for the file system to catch up - setTimeout(() => { - t.equal(fs.readdirSync('/proc/self/fd').length, initialFd, - `file descriptor count should be back to initial`); - t.end(); - }, 250); - }); + // wait for the file system to catch up + setTimeout(() => { + t.equal( + fs.readdirSync('/proc/self/fd').length, + initialFd, + `file descriptor count should be back to initial` + ); + t.end(); + }, 250); + } + ); batch.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); - const filenames = Object.values(config.appenders).map(appender => appender.filename); + const filenames = Object.values(config.appenders).map( + (appender) => appender.filename + ); await removeFiles(filenames); }); batch.end(); }); - -} \ No newline at end of file +} diff --git a/test/tap/file-sighup-test.js b/test/tap/file-sighup-test.js index deb612a8..e8f3c032 100644 --- a/test/tap/file-sighup-test.js +++ b/test/tap/file-sighup-test.js @@ -1,75 +1,89 @@ -const { test } = require("tap"); -const path = require("path"); -const fs = require("fs"); -const sandbox = require("@log4js-node/sandboxed-module"); - -const removeFiles = async filenames => { - if (!Array.isArray(filenames)) - filenames = [filenames]; - const promises = filenames.map(filename => fs.promises.unlink(filename)); +const { test } = require('tap'); +const path = require('path'); +const fs = require('fs'); +const sandbox = require('@log4js-node/sandboxed-module'); + +const removeFiles = async (filenames) => { + if (!Array.isArray(filenames)) filenames = [filenames]; + const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; -test("file appender single SIGHUP handler", t => { - const initialListeners = process.listenerCount("SIGHUP"); +test('file appender single SIGHUP handler', (t) => { + const initialListeners = process.listenerCount('SIGHUP'); let warning; - const originalListener = process.listeners("warning")[process.listeners("warning").length - 1]; - const warningListener = error => { - if (error.type === "SIGHUP" && error.name === "MaxListenersExceededWarning") { + const originalListener = + process.listeners('warning')[process.listeners('warning').length - 1]; + const warningListener = (error) => { + if ( + error.type === 'SIGHUP' && + error.name === 'MaxListenersExceededWarning' + ) { warning = error; return; } originalListener(error); }; - process.off("warning", originalListener); - process.on("warning", warningListener); + process.off('warning', originalListener); + process.on('warning', warningListener); const config = { appenders: {}, categories: { - default: { appenders: [], level: 'debug' } - } + default: { appenders: [], level: 'debug' }, + }, }; // create 11 appenders to make nodejs warn for >10 max listeners const numOfAppenders = 11; for (let i = 1; i <= numOfAppenders; i++) { - config.appenders[`app${i}`] = { type: 'file', filename: path.join(__dirname, `file${i}.log`) }; + config.appenders[`app${i}`] = { + type: 'file', + filename: path.join(__dirname, `file${i}.log`), + }; config.categories.default.appenders.push(`app${i}`); } - const log4js = require("../../lib/log4js"); + const log4js = require('../../lib/log4js'); log4js.configure(config); t.teardown(async () => { // next event loop so that past warnings will not be printed setImmediate(() => { - process.off("warning", warningListener); - process.on("warning", originalListener); + process.off('warning', warningListener); + process.on('warning', originalListener); }); - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); - const filenames = Object.values(config.appenders).map(appender => appender.filename); + const filenames = Object.values(config.appenders).map( + (appender) => appender.filename + ); await removeFiles(filenames); }); t.plan(2); // next event loop to allow event emitter/listener to happen setImmediate(() => { - t.notOk(warning, "should not have MaxListenersExceededWarning for SIGHUP"); - t.equal(process.listenerCount("SIGHUP") - initialListeners, 1, "should be 1 SIGHUP listener"); + t.notOk(warning, 'should not have MaxListenersExceededWarning for SIGHUP'); + t.equal( + process.listenerCount('SIGHUP') - initialListeners, + 1, + 'should be 1 SIGHUP listener' + ); t.end(); }); }); -test("file appender SIGHUP", t => { +test('file appender SIGHUP', (t) => { let closeCalled = 0; let openCalled = 0; sandbox - .require("../../lib/appenders/file", { + .require('../../lib/appenders/file', { requires: { streamroller: { RollingFileStream: class RollingFileStream { @@ -79,7 +93,7 @@ test("file appender SIGHUP", t => { } on() { - this.dummy = "easier than turning off lint rule"; + this.dummy = 'easier than turning off lint rule'; } end(cb) { @@ -90,49 +104,49 @@ test("file appender SIGHUP", t => { write() { if (this.ended) { - throw new Error("write after end"); + throw new Error('write after end'); } return true; } - } - } - } + }, + }, + }, }) .configure( - { type: "file", filename: "sighup-test-file" }, + { type: 'file', filename: 'sighup-test-file' }, { basicLayout() { - return "whatever"; - } + return 'whatever'; + }, } ); - process.emit("SIGHUP", "SIGHUP", 1); + process.emit('SIGHUP', 'SIGHUP', 1); t.plan(2); setTimeout(() => { - t.equal(openCalled, 2, "open should be called twice"); - t.equal(closeCalled, 1, "close should be called once"); + t.equal(openCalled, 2, 'open should be called twice'); + t.equal(closeCalled, 1, 'close should be called once'); t.end(); }, 100); }); -test("file appender SIGHUP handler leak", t => { - const log4js = require("../../lib/log4js"); - const initialListeners = process.listenerCount("SIGHUP"); +test('file appender SIGHUP handler leak', (t) => { + const log4js = require('../../lib/log4js'); + const initialListeners = process.listenerCount('SIGHUP'); log4js.configure({ appenders: { - file: { type: "file", filename: "test.log" } + file: { type: 'file', filename: 'test.log' }, }, - categories: { default: { appenders: ["file"], level: "info" } } + categories: { default: { appenders: ['file'], level: 'info' } }, }); t.teardown(async () => { - await removeFiles("test.log"); + await removeFiles('test.log'); }); t.plan(2); - t.equal(process.listenerCount("SIGHUP"), initialListeners + 1); + t.equal(process.listenerCount('SIGHUP'), initialListeners + 1); log4js.shutdown(() => { - t.equal(process.listenerCount("SIGHUP"), initialListeners); + t.equal(process.listenerCount('SIGHUP'), initialListeners); t.end(); }); -}); \ No newline at end of file +}); diff --git a/test/tap/fileAppender-test.js b/test/tap/fileAppender-test.js index a2b1efd3..e7a79347 100644 --- a/test/tap/fileAppender-test.js +++ b/test/tap/fileAppender-test.js @@ -1,18 +1,18 @@ /* eslint max-classes-per-file: ["error", 2] */ -const { test } = require("tap"); -const fs = require("fs-extra"); -const path = require("path"); -const sandbox = require("@log4js-node/sandboxed-module"); -const zlib = require("zlib"); -const util = require("util"); +const { test } = require('tap'); +const fs = require('fs-extra'); +const path = require('path'); +const sandbox = require('@log4js-node/sandboxed-module'); +const zlib = require('zlib'); +const util = require('util'); const sleep = util.promisify(setTimeout); const gunzip = util.promisify(zlib.gunzip); -const EOL = require("os").EOL || "\n"; -const log4js = require("../../lib/log4js"); +const EOL = require('os').EOL || '\n'; +const log4js = require('../../lib/log4js'); -const removeFile = async filename => { +const removeFile = async (filename) => { try { await fs.unlink(filename); } catch (e) { @@ -20,26 +20,28 @@ const removeFile = async filename => { } }; -test("log4js fileAppender", batch => { - batch.test("with default fileAppender settings", async t => { - const testFile = path.join(__dirname, "fa-default-test.log"); - const logger = log4js.getLogger("default-settings"); +test('log4js fileAppender', (batch) => { + batch.test('with default fileAppender settings', async (t) => { + const testFile = path.join(__dirname, 'fa-default-test.log'); + const logger = log4js.getLogger('default-settings'); await removeFile(testFile); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await removeFile(testFile); }); log4js.configure({ - appenders: { file: { type: "file", filename: testFile } }, - categories: { default: { appenders: ["file"], level: "debug" } } + appenders: { file: { type: 'file', filename: testFile } }, + categories: { default: { appenders: ['file'], level: 'debug' } }, }); - logger.info("This should be in the file."); + logger.info('This should be in the file.'); await sleep(100); - const fileContents = await fs.readFile(testFile, "utf8"); + const fileContents = await fs.readFile(testFile, 'utf8'); t.match(fileContents, `This should be in the file.${EOL}`); t.match( fileContents, @@ -48,63 +50,67 @@ test("log4js fileAppender", batch => { t.end(); }); - batch.test("should give error if invalid filename", async t => { - const file = ""; + batch.test('should give error if invalid filename', async (t) => { + const file = ''; t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "file", - filename: file - } + type: 'file', + filename: file, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), new Error(`Invalid filename: ${file}`) ); const dir = `.${path.sep}`; t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "file", - filename: dir - } + type: 'file', + filename: dir, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), new Error(`Filename is a directory: ${dir}`) ); t.end(); }); - batch.test("should flush logs on shutdown", async t => { - const testFile = path.join(__dirname, "fa-default-test.log"); - const logger = log4js.getLogger("default-settings"); + batch.test('should flush logs on shutdown', async (t) => { + const testFile = path.join(__dirname, 'fa-default-test.log'); + const logger = log4js.getLogger('default-settings'); await removeFile(testFile); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await removeFile(testFile); }); log4js.configure({ - appenders: { test: { type: "file", filename: testFile } }, - categories: { default: { appenders: ["test"], level: "trace" } } + appenders: { test: { type: 'file', filename: testFile } }, + categories: { default: { appenders: ['test'], level: 'trace' } }, }); - logger.info("1"); - logger.info("2"); - logger.info("3"); + logger.info('1'); + logger.info('2'); + logger.info('3'); - await new Promise(resolve => { log4js.shutdown(resolve); }); - const fileContents = await fs.readFile(testFile, "utf8"); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); + const fileContents = await fs.readFile(testFile, 'utf8'); // 3 lines of output, plus the trailing newline. t.equal(fileContents.split(EOL).length, 4); t.match( @@ -114,13 +120,15 @@ test("log4js fileAppender", batch => { t.end(); }); - batch.test("with a max file size and no backups", async t => { - const testFile = path.join(__dirname, "fa-maxFileSize-test.log"); - const logger = log4js.getLogger("max-file-size"); + batch.test('with a max file size and no backups', async (t) => { + const testFile = path.join(__dirname, 'fa-maxFileSize-test.log'); + const logger = log4js.getLogger('max-file-size'); await removeFile(testFile); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await removeFile(testFile); }); @@ -128,61 +136,63 @@ test("log4js fileAppender", batch => { log4js.configure({ appenders: { file: { - type: "file", + type: 'file', filename: testFile, maxLogSize: 100, - backups: 0 - } + backups: 0, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }); - logger.info("This is the first log message."); - logger.info("This is an intermediate log message."); - logger.info("This is the second log message."); + logger.info('This is the first log message.'); + logger.info('This is an intermediate log message.'); + logger.info('This is the second log message.'); // wait for the file system to catch up await sleep(100); - const fileContents = await fs.readFile(testFile, "utf8"); - t.match(fileContents, "This is the second log message."); - t.equal(fileContents.indexOf("This is the first log message."), -1); + const fileContents = await fs.readFile(testFile, 'utf8'); + t.match(fileContents, 'This is the second log message.'); + t.equal(fileContents.indexOf('This is the first log message.'), -1); const files = await fs.readdir(__dirname); - const logFiles = files.filter(file => - file.includes("fa-maxFileSize-test.log") + const logFiles = files.filter((file) => + file.includes('fa-maxFileSize-test.log') ); - t.equal(logFiles.length, 1, "should be 1 file"); + t.equal(logFiles.length, 1, 'should be 1 file'); t.end(); }); - batch.test("with a max file size in wrong unit mode", async t => { - const invalidUnit = "1Z"; + batch.test('with a max file size in wrong unit mode', async (t) => { + const invalidUnit = '1Z'; const expectedError = new Error(`maxLogSize: "${invalidUnit}" is invalid`); t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "file", - maxLogSize: invalidUnit - } + type: 'file', + maxLogSize: invalidUnit, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), expectedError ); t.end(); }); - batch.test("with a max file size in unit mode and no backups", async t => { - const testFile = path.join(__dirname, "fa-maxFileSize-unit-test.log"); - const logger = log4js.getLogger("max-file-size-unit"); + batch.test('with a max file size in unit mode and no backups', async (t) => { + const testFile = path.join(__dirname, 'fa-maxFileSize-unit-test.log'); + const logger = log4js.getLogger('max-file-size-unit'); await Promise.all([removeFile(testFile), removeFile(`${testFile}.1`)]); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await Promise.all([removeFile(testFile), removeFile(`${testFile}.1`)]); }); @@ -190,55 +200,57 @@ test("log4js fileAppender", batch => { log4js.configure({ appenders: { file: { - type: "file", + type: 'file', filename: testFile, - maxLogSize: "1K", + maxLogSize: '1K', backups: 0, - layout: { type: "messagePassThrough" } - } + layout: { type: 'messagePassThrough' }, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }); const maxLine = 22; // 1024 max file size / 47 bytes per line for (let i = 0; i < maxLine; i++) { - logger.info("These are the log messages for the first file."); // 46 bytes per line + '\n' + logger.info('These are the log messages for the first file.'); // 46 bytes per line + '\n' } - logger.info("This is the second log message."); + logger.info('This is the second log message.'); // wait for the file system to catch up await sleep(100); - const fileContents = await fs.readFile(testFile, "utf8"); - t.match(fileContents, "This is the second log message."); - t.notMatch(fileContents, "These are the log messages for the first file."); + const fileContents = await fs.readFile(testFile, 'utf8'); + t.match(fileContents, 'This is the second log message.'); + t.notMatch(fileContents, 'These are the log messages for the first file.'); const files = await fs.readdir(__dirname); - const logFiles = files.filter(file => - file.includes("fa-maxFileSize-unit-test.log") + const logFiles = files.filter((file) => + file.includes('fa-maxFileSize-unit-test.log') ); - t.equal(logFiles.length, 1, "should be 1 file"); + t.equal(logFiles.length, 1, 'should be 1 file'); t.end(); }); - batch.test("with a max file size and 2 backups", async t => { + batch.test('with a max file size and 2 backups', async (t) => { const testFile = path.join( __dirname, - "fa-maxFileSize-with-backups-test.log" + 'fa-maxFileSize-with-backups-test.log' ); - const logger = log4js.getLogger("max-file-size-backups"); + const logger = log4js.getLogger('max-file-size-backups'); await Promise.all([ removeFile(testFile), removeFile(`${testFile}.1`), - removeFile(`${testFile}.2`) + removeFile(`${testFile}.2`), ]); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await Promise.all([ removeFile(testFile), removeFile(`${testFile}.1`), - removeFile(`${testFile}.2`) + removeFile(`${testFile}.2`), ]); }); @@ -246,59 +258,61 @@ test("log4js fileAppender", batch => { log4js.configure({ appenders: { file: { - type: "file", + type: 'file', filename: testFile, maxLogSize: 50, - backups: 2 - } + backups: 2, + }, }, - categories: { default: { appenders: ["file"], level: "debug" } } + categories: { default: { appenders: ['file'], level: 'debug' } }, }); - logger.info("This is the first log message."); - logger.info("This is the second log message."); - logger.info("This is the third log message."); - logger.info("This is the fourth log message."); + logger.info('This is the first log message.'); + logger.info('This is the second log message.'); + logger.info('This is the third log message.'); + logger.info('This is the fourth log message.'); // give the system a chance to open the stream await sleep(200); const files = await fs.readdir(__dirname); const logFiles = files .sort() - .filter(file => file.includes("fa-maxFileSize-with-backups-test.log")); + .filter((file) => file.includes('fa-maxFileSize-with-backups-test.log')); t.equal(logFiles.length, 3); t.same(logFiles, [ - "fa-maxFileSize-with-backups-test.log", - "fa-maxFileSize-with-backups-test.log.1", - "fa-maxFileSize-with-backups-test.log.2" + 'fa-maxFileSize-with-backups-test.log', + 'fa-maxFileSize-with-backups-test.log.1', + 'fa-maxFileSize-with-backups-test.log.2', ]); - let contents = await fs.readFile(path.join(__dirname, logFiles[0]), "utf8"); - t.match(contents, "This is the fourth log message."); - contents = await fs.readFile(path.join(__dirname, logFiles[1]), "utf8"); - t.match(contents, "This is the third log message."); - contents = await fs.readFile(path.join(__dirname, logFiles[2]), "utf8"); - t.match(contents, "This is the second log message."); + let contents = await fs.readFile(path.join(__dirname, logFiles[0]), 'utf8'); + t.match(contents, 'This is the fourth log message.'); + contents = await fs.readFile(path.join(__dirname, logFiles[1]), 'utf8'); + t.match(contents, 'This is the third log message.'); + contents = await fs.readFile(path.join(__dirname, logFiles[2]), 'utf8'); + t.match(contents, 'This is the second log message.'); t.end(); }); - batch.test("with a max file size and 2 compressed backups", async t => { + batch.test('with a max file size and 2 compressed backups', async (t) => { const testFile = path.join( __dirname, - "fa-maxFileSize-with-backups-compressed-test.log" + 'fa-maxFileSize-with-backups-compressed-test.log' ); - const logger = log4js.getLogger("max-file-size-backups"); + const logger = log4js.getLogger('max-file-size-backups'); await Promise.all([ removeFile(testFile), removeFile(`${testFile}.1.gz`), - removeFile(`${testFile}.2.gz`) + removeFile(`${testFile}.2.gz`), ]); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await Promise.all([ removeFile(testFile), removeFile(`${testFile}.1.gz`), - removeFile(`${testFile}.2.gz`) + removeFile(`${testFile}.2.gz`), ]); }); @@ -306,48 +320,48 @@ test("log4js fileAppender", batch => { log4js.configure({ appenders: { file: { - type: "file", + type: 'file', filename: testFile, maxLogSize: 50, backups: 2, - compress: true - } + compress: true, + }, }, - categories: { default: { appenders: ["file"], level: "debug" } } + categories: { default: { appenders: ['file'], level: 'debug' } }, }); - logger.info("This is the first log message."); - logger.info("This is the second log message."); - logger.info("This is the third log message."); - logger.info("This is the fourth log message."); + logger.info('This is the first log message.'); + logger.info('This is the second log message.'); + logger.info('This is the third log message.'); + logger.info('This is the fourth log message.'); // give the system a chance to open the stream await sleep(1000); const files = await fs.readdir(__dirname); const logFiles = files .sort() - .filter(file => - file.includes("fa-maxFileSize-with-backups-compressed-test.log") + .filter((file) => + file.includes('fa-maxFileSize-with-backups-compressed-test.log') ); - t.equal(logFiles.length, 3, "should be 3 files"); + t.equal(logFiles.length, 3, 'should be 3 files'); t.same(logFiles, [ - "fa-maxFileSize-with-backups-compressed-test.log", - "fa-maxFileSize-with-backups-compressed-test.log.1.gz", - "fa-maxFileSize-with-backups-compressed-test.log.2.gz" + 'fa-maxFileSize-with-backups-compressed-test.log', + 'fa-maxFileSize-with-backups-compressed-test.log.1.gz', + 'fa-maxFileSize-with-backups-compressed-test.log.2.gz', ]); - let contents = await fs.readFile(path.join(__dirname, logFiles[0]), "utf8"); - t.match(contents, "This is the fourth log message."); + let contents = await fs.readFile(path.join(__dirname, logFiles[0]), 'utf8'); + t.match(contents, 'This is the fourth log message.'); contents = await gunzip( await fs.readFile(path.join(__dirname, logFiles[1])) ); - t.match(contents.toString("utf8"), "This is the third log message."); + t.match(contents.toString('utf8'), 'This is the third log message.'); contents = await gunzip( await fs.readFile(path.join(__dirname, logFiles[2])) ); - t.match(contents.toString("utf8"), "This is the second log message."); + t.match(contents.toString('utf8'), 'This is the second log message.'); t.end(); }); - batch.test("handling of writer.writable", t => { + batch.test('handling of writer.writable', (t) => { const output = []; let writable = true; @@ -359,47 +373,50 @@ test("log4js fileAppender", batch => { } // eslint-disable-next-line class-methods-use-this - on() { - } + on() {} // eslint-disable-next-line class-methods-use-this get writable() { return writable; } }; - const fileAppender = sandbox.require("../../lib/appenders/file", { + const fileAppender = sandbox.require('../../lib/appenders/file', { requires: { streamroller: { - RollingFileStream - } - } + RollingFileStream, + }, + }, }); const appender = fileAppender.configure( - { filename: "test1.log", maxLogSize: 100 }, - { basicLayout(loggingEvent) { return loggingEvent.data; } } + { filename: 'test1.log', maxLogSize: 100 }, + { + basicLayout(loggingEvent) { + return loggingEvent.data; + }, + } ); - t.test("should log when writer.writable=true", assert => { + t.test('should log when writer.writable=true', (assert) => { writable = true; - appender({data: "something to log"}); + appender({ data: 'something to log' }); assert.ok(output.length, 1); - assert.match(output[output.length - 1], "something to log"); + assert.match(output[output.length - 1], 'something to log'); assert.end(); }); - t.test("should not log when writer.writable=false", assert => { + t.test('should not log when writer.writable=false', (assert) => { writable = false; - appender({data: "this should not be logged"}); + appender({ data: 'this should not be logged' }); assert.ok(output.length, 1); - assert.notMatch(output[output.length - 1], "this should not be logged"); + assert.notMatch(output[output.length - 1], 'this should not be logged'); assert.end(); }); t.end(); }); - batch.test("when underlying stream errors", t => { + batch.test('when underlying stream errors', (t) => { let consoleArgs; let errorHandler; @@ -409,7 +426,7 @@ test("log4js fileAppender", batch => { } on(evt, cb) { - if (evt === "error") { + if (evt === 'error') { this.errored = true; errorHandler = cb; } @@ -420,75 +437,89 @@ test("log4js fileAppender", batch => { return true; } }; - const fileAppender = sandbox.require("../../lib/appenders/file", { + const fileAppender = sandbox.require('../../lib/appenders/file', { globals: { console: { error(...args) { consoleArgs = args; - } - } + }, + }, }, requires: { streamroller: { - RollingFileStream - } - } + RollingFileStream, + }, + }, }); fileAppender.configure( - { filename: "test1.log", maxLogSize: 100 }, + { filename: 'test1.log', maxLogSize: 100 }, { basicLayout() {} } ); - errorHandler({ error: "aargh" }); + errorHandler({ error: 'aargh' }); - t.test("should log the error to console.error", assert => { + t.test('should log the error to console.error', (assert) => { assert.ok(consoleArgs); assert.equal( consoleArgs[0], - "log4js.fileAppender - Writing to file %s, error happened " + 'log4js.fileAppender - Writing to file %s, error happened ' ); - assert.equal(consoleArgs[1], "test1.log"); - assert.equal(consoleArgs[2].error, "aargh"); + assert.equal(consoleArgs[1], 'test1.log'); + assert.equal(consoleArgs[2].error, 'aargh'); assert.end(); }); t.end(); }); - batch.test("with removeColor fileAppender settings", async t => { - const testFilePlain = path.join(__dirname, "fa-removeColor-test.log"); - const testFileAsIs = path.join(__dirname, "fa-asIs-test.log"); - const logger = log4js.getLogger("default-settings"); + batch.test('with removeColor fileAppender settings', async (t) => { + const testFilePlain = path.join(__dirname, 'fa-removeColor-test.log'); + const testFileAsIs = path.join(__dirname, 'fa-asIs-test.log'); + const logger = log4js.getLogger('default-settings'); await removeFile(testFilePlain); await removeFile(testFileAsIs); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); await removeFile(testFilePlain); await removeFile(testFileAsIs); }); log4js.configure({ - appenders: { - plainFile: { type: "file", filename: testFilePlain, removeColor: true }, - asIsFile: { type: "file", filename: testFileAsIs, removeColor: false } + appenders: { + plainFile: { type: 'file', filename: testFilePlain, removeColor: true }, + asIsFile: { type: 'file', filename: testFileAsIs, removeColor: false }, + }, + categories: { + default: { appenders: ['plainFile', 'asIsFile'], level: 'debug' }, }, - categories: { default: { appenders: ["plainFile", "asIsFile"], level: "debug" } } }); - logger.info("This should be in the file.", - "\x1b[33mColor\x1b[0m \x1b[93;41mshould\x1b[0m be \x1b[38;5;8mplain\x1b[0m.", {}, []); + logger.info( + 'This should be in the file.', + '\x1b[33mColor\x1b[0m \x1b[93;41mshould\x1b[0m be \x1b[38;5;8mplain\x1b[0m.', + {}, + [] + ); await sleep(100); - let fileContents = await fs.readFile(testFilePlain, "utf8"); - t.match(fileContents, `This should be in the file. Color should be plain. {} []${EOL}`); + let fileContents = await fs.readFile(testFilePlain, 'utf8'); + t.match( + fileContents, + `This should be in the file. Color should be plain. {} []${EOL}` + ); t.match( fileContents, /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}] \[INFO] default-settings - / ); - fileContents = await fs.readFile(testFileAsIs, "utf8"); - t.match(fileContents, "This should be in the file.", - `\x1b[33mColor\x1b[0m \x1b[93;41mshould\x1b[0m be \x1b[38;5;8mplain\x1b[0m. {} []${EOL}`); + fileContents = await fs.readFile(testFileAsIs, 'utf8'); + t.match( + fileContents, + 'This should be in the file.', + `\x1b[33mColor\x1b[0m \x1b[93;41mshould\x1b[0m be \x1b[38;5;8mplain\x1b[0m. {} []${EOL}` + ); t.match( fileContents, /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}] \[INFO] default-settings - / diff --git a/test/tap/fileSyncAppender-test.js b/test/tap/fileSyncAppender-test.js index 4ea96ac3..1330d10b 100644 --- a/test/tap/fileSyncAppender-test.js +++ b/test/tap/fileSyncAppender-test.js @@ -1,9 +1,9 @@ -const { test } = require("tap"); -const fs = require("fs"); -const path = require("path"); -const EOL = require("os").EOL || "\n"; -const sandbox = require("@log4js-node/sandboxed-module"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const fs = require('fs'); +const path = require('path'); +const EOL = require('os').EOL || '\n'; +const sandbox = require('@log4js-node/sandboxed-module'); +const log4js = require('../../lib/log4js'); function remove(filename) { try { @@ -13,10 +13,10 @@ function remove(filename) { } } -test("log4js fileSyncAppender", batch => { - batch.test("with default fileSyncAppender settings", t => { - const testFile = path.join(__dirname, "/fa-default-sync-test.log"); - const logger = log4js.getLogger("default-settings"); +test('log4js fileSyncAppender', (batch) => { + batch.test('with default fileSyncAppender settings', (t) => { + const testFile = path.join(__dirname, '/fa-default-sync-test.log'); + const logger = log4js.getLogger('default-settings'); remove(testFile); t.teardown(() => { @@ -24,13 +24,13 @@ test("log4js fileSyncAppender", batch => { }); log4js.configure({ - appenders: { sync: { type: "fileSync", filename: testFile } }, - categories: { default: { appenders: ["sync"], level: "debug" } } + appenders: { sync: { type: 'fileSync', filename: testFile } }, + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - logger.info("This should be in the file."); + logger.info('This should be in the file.'); - fs.readFile(testFile, "utf8", (err, fileContents) => { + fs.readFile(testFile, 'utf8', (err, fileContents) => { t.match(fileContents, `This should be in the file.${EOL}`); t.match( fileContents, @@ -40,9 +40,9 @@ test("log4js fileSyncAppender", batch => { }); }); - batch.test("with existing file", t => { - const testFile = path.join(__dirname, "/fa-existing-file-sync-test.log"); - const logger = log4js.getLogger("default-settings"); + batch.test('with existing file', (t) => { + const testFile = path.join(__dirname, '/fa-existing-file-sync-test.log'); + const logger = log4js.getLogger('default-settings'); remove(testFile); t.teardown(() => { @@ -50,21 +50,21 @@ test("log4js fileSyncAppender", batch => { }); log4js.configure({ - appenders: { sync: { type: "fileSync", filename: testFile } }, - categories: { default: { appenders: ["sync"], level: "debug" } } + appenders: { sync: { type: 'fileSync', filename: testFile } }, + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - logger.info("This should be in the file."); + logger.info('This should be in the file.'); log4js.shutdown(() => { log4js.configure({ - appenders: { sync: { type: "fileSync", filename: testFile } }, - categories: { default: { appenders: ["sync"], level: "debug" } } + appenders: { sync: { type: 'fileSync', filename: testFile } }, + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - logger.info("This should also be in the file."); + logger.info('This should also be in the file.'); - fs.readFile(testFile, "utf8", (err, fileContents) => { + fs.readFile(testFile, 'utf8', (err, fileContents) => { t.match(fileContents, `This should be in the file.${EOL}`); t.match(fileContents, `This should also be in the file.${EOL}`); t.match( @@ -76,67 +76,70 @@ test("log4js fileSyncAppender", batch => { }); }); - batch.test("should give error if invalid filename", async t => { - const file = ""; + batch.test('should give error if invalid filename', async (t) => { + const file = ''; t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "fileSync", - filename: file - } + type: 'fileSync', + filename: file, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), new Error(`Invalid filename: ${file}`) ); const dir = `.${path.sep}`; t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "fileSync", - filename: dir - } + type: 'fileSync', + filename: dir, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), new Error(`Filename is a directory: ${dir}`) ); t.end(); }); - batch.test("should give error if invalid maxLogSize", async t => { + batch.test('should give error if invalid maxLogSize', async (t) => { const maxLogSize = -1; const expectedError = new Error(`maxLogSize (${maxLogSize}) should be > 0`); t.throws( - () => + () => log4js.configure({ appenders: { file: { - type: "fileSync", - filename: path.join(__dirname, "fa-invalidMaxFileSize-sync-test.log"), - maxLogSize: -1 - } + type: 'fileSync', + filename: path.join( + __dirname, + 'fa-invalidMaxFileSize-sync-test.log' + ), + maxLogSize: -1, + }, }, categories: { - default: { appenders: ["file"], level: "debug" } - } + default: { appenders: ['file'], level: 'debug' }, + }, }), expectedError ); t.end(); }); - batch.test("with a max file size and no backups", t => { - const testFile = path.join(__dirname, "/fa-maxFileSize-sync-test.log"); - const logger = log4js.getLogger("max-file-size"); + batch.test('with a max file size and no backups', (t) => { + const testFile = path.join(__dirname, '/fa-maxFileSize-sync-test.log'); + const logger = log4js.getLogger('max-file-size'); remove(testFile); t.teardown(() => { @@ -147,33 +150,33 @@ test("log4js fileSyncAppender", batch => { log4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, maxLogSize: 100, - backups: 0 - } + backups: 0, + }, }, - categories: { default: { appenders: ["sync"], level: "debug" } } + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - logger.info("This is the first log message."); - logger.info("This is an intermediate log message."); - logger.info("This is the second log message."); + logger.info('This is the first log message.'); + logger.info('This is an intermediate log message.'); + logger.info('This is the second log message.'); - t.test("log file should only contain the second message", assert => { - fs.readFile(testFile, "utf8", (err, fileContents) => { + t.test('log file should only contain the second message', (assert) => { + fs.readFile(testFile, 'utf8', (err, fileContents) => { assert.match(fileContents, `This is the second log message.${EOL}`); assert.equal( - fileContents.indexOf("This is the first log message."), + fileContents.indexOf('This is the first log message.'), -1 ); assert.end(); }); }); - t.test("there should be one test files", assert => { + t.test('there should be one test files', (assert) => { fs.readdir(__dirname, (err, files) => { - const logFiles = files.filter(file => - file.includes("fa-maxFileSize-sync-test.log") + const logFiles = files.filter((file) => + file.includes('fa-maxFileSize-sync-test.log') ); assert.equal(logFiles.length, 1); assert.end(); @@ -182,9 +185,9 @@ test("log4js fileSyncAppender", batch => { t.end(); }); - batch.test("with a max file size in unit mode and no backups", t => { - const testFile = path.join(__dirname, "/fa-maxFileSize-unit-sync-test.log"); - const logger = log4js.getLogger("max-file-size-unit"); + batch.test('with a max file size in unit mode and no backups', (t) => { + const testFile = path.join(__dirname, '/fa-maxFileSize-unit-sync-test.log'); + const logger = log4js.getLogger('max-file-size-unit'); remove(testFile); remove(`${testFile}.1`); @@ -197,34 +200,37 @@ test("log4js fileSyncAppender", batch => { log4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, - maxLogSize: "1K", + maxLogSize: '1K', backups: 0, - layout: { type: "messagePassThrough" } - } + layout: { type: 'messagePassThrough' }, + }, }, - categories: { default: { appenders: ["sync"], level: "debug" } } + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - const maxLine = 22; // 1024 max file size / 47 bytes per line + const maxLine = 22; // 1024 max file size / 47 bytes per line for (let i = 0; i < maxLine; i++) { - logger.info("These are the log messages for the first file."); // 46 bytes per line + '\n' + logger.info('These are the log messages for the first file.'); // 46 bytes per line + '\n' } - logger.info("This is the second log message."); + logger.info('This is the second log message.'); - t.test("log file should only contain the second message", assert => { - fs.readFile(testFile, "utf8", (err, fileContents) => { + t.test('log file should only contain the second message', (assert) => { + fs.readFile(testFile, 'utf8', (err, fileContents) => { assert.match(fileContents, `This is the second log message.${EOL}`); - assert.notMatch(fileContents, "These are the log messages for the first file."); + assert.notMatch( + fileContents, + 'These are the log messages for the first file.' + ); assert.end(); }); }); - t.test("there should be one test file", assert => { + t.test('there should be one test file', (assert) => { fs.readdir(__dirname, (err, files) => { - const logFiles = files.filter(file => - file.includes("fa-maxFileSize-unit-sync-test.log") + const logFiles = files.filter((file) => + file.includes('fa-maxFileSize-unit-sync-test.log') ); assert.equal(logFiles.length, 1); assert.end(); @@ -233,12 +239,12 @@ test("log4js fileSyncAppender", batch => { t.end(); }); - batch.test("with a max file size and 2 backups", t => { + batch.test('with a max file size and 2 backups', (t) => { const testFile = path.join( __dirname, - "/fa-maxFileSize-with-backups-sync-test.log" + '/fa-maxFileSize-with-backups-sync-test.log' ); - const logger = log4js.getLogger("max-file-size-backups"); + const logger = log4js.getLogger('max-file-size-backups'); remove(testFile); remove(`${testFile}.1`); remove(`${testFile}.2`); @@ -253,55 +259,55 @@ test("log4js fileSyncAppender", batch => { log4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, maxLogSize: 50, - backups: 2 - } + backups: 2, + }, }, - categories: { default: { appenders: ["sync"], level: "debug" } } + categories: { default: { appenders: ['sync'], level: 'debug' } }, }); - logger.info("This is the first log message."); - logger.info("This is the second log message."); - logger.info("This is the third log message."); - logger.info("This is the fourth log message."); + logger.info('This is the first log message.'); + logger.info('This is the second log message.'); + logger.info('This is the third log message.'); + logger.info('This is the fourth log message.'); - t.test("the log files", assert => { + t.test('the log files', (assert) => { assert.plan(5); fs.readdir(__dirname, (err, files) => { - const logFiles = files.filter(file => - file.includes("fa-maxFileSize-with-backups-sync-test.log") + const logFiles = files.filter((file) => + file.includes('fa-maxFileSize-with-backups-sync-test.log') ); - assert.equal(logFiles.length, 3, "should be 3 files"); + assert.equal(logFiles.length, 3, 'should be 3 files'); assert.same( logFiles, [ - "fa-maxFileSize-with-backups-sync-test.log", - "fa-maxFileSize-with-backups-sync-test.log.1", - "fa-maxFileSize-with-backups-sync-test.log.2" + 'fa-maxFileSize-with-backups-sync-test.log', + 'fa-maxFileSize-with-backups-sync-test.log.1', + 'fa-maxFileSize-with-backups-sync-test.log.2', ], - "should be named in sequence" + 'should be named in sequence' ); fs.readFile( path.join(__dirname, logFiles[0]), - "utf8", + 'utf8', (e, contents) => { - assert.match(contents, "This is the fourth log message."); + assert.match(contents, 'This is the fourth log message.'); } ); fs.readFile( path.join(__dirname, logFiles[1]), - "utf8", + 'utf8', (e, contents) => { - assert.match(contents, "This is the third log message."); + assert.match(contents, 'This is the third log message.'); } ); fs.readFile( path.join(__dirname, logFiles[2]), - "utf8", + 'utf8', (e, contents) => { - assert.match(contents, "This is the second log message."); + assert.match(contents, 'This is the second log message.'); } ); }); @@ -309,8 +315,8 @@ test("log4js fileSyncAppender", batch => { t.end(); }); - batch.test("configure with fileSyncAppender", t => { - const testFile = "tmp-sync-tests.log"; + batch.test('configure with fileSyncAppender', (t) => { + const testFile = 'tmp-sync-tests.log'; remove(testFile); t.teardown(() => { @@ -322,220 +328,235 @@ test("log4js fileSyncAppender", batch => { log4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, - layout: { type: "messagePassThrough" } - } + layout: { type: 'messagePassThrough' }, + }, }, categories: { - default: { appenders: ["sync"], level: "debug" }, - tests: { appenders: ["sync"], level: "warn" } - } + default: { appenders: ['sync'], level: 'debug' }, + tests: { appenders: ['sync'], level: 'warn' }, + }, }); - const logger = log4js.getLogger("tests"); - logger.info("this should not be written to the file"); - logger.warn("this should be written to the file"); + const logger = log4js.getLogger('tests'); + logger.info('this should not be written to the file'); + logger.warn('this should be written to the file'); - fs.readFile(testFile, "utf8", (err, contents) => { + fs.readFile(testFile, 'utf8', (err, contents) => { t.match(contents, `this should be written to the file${EOL}`); - t.equal(contents.indexOf("this should not be written to the file"), -1); + t.equal(contents.indexOf('this should not be written to the file'), -1); t.end(); }); }); - batch.test("configure with non-existent multi-directory (recursive, nodejs >= 10.12.0)", t => { - const testFile = "tmpA/tmpB/tmpC/tmp-sync-tests-recursive.log"; - remove(testFile); - - t.teardown(() => { + batch.test( + 'configure with non-existent multi-directory (recursive, nodejs >= 10.12.0)', + (t) => { + const testFile = 'tmpA/tmpB/tmpC/tmp-sync-tests-recursive.log'; remove(testFile); - try { - fs.rmdirSync("tmpA/tmpB/tmpC"); - fs.rmdirSync("tmpA/tmpB"); - fs.rmdirSync("tmpA"); - } catch (e) { - // doesn't matter - } - }); - log4js.configure({ - appenders: { - sync: { - type: "fileSync", - filename: testFile, - layout: { type: "messagePassThrough" } + t.teardown(() => { + remove(testFile); + try { + fs.rmdirSync('tmpA/tmpB/tmpC'); + fs.rmdirSync('tmpA/tmpB'); + fs.rmdirSync('tmpA'); + } catch (e) { + // doesn't matter } - }, - categories: { - default: { appenders: ["sync"], level: "debug" } - } - }); - const logger = log4js.getLogger(); - logger.info("this should be written to the file"); + }); - fs.readFile(testFile, "utf8", (err, contents) => { - t.match(contents, `this should be written to the file${EOL}`); - t.end(); - }); - }); + log4js.configure({ + appenders: { + sync: { + type: 'fileSync', + filename: testFile, + layout: { type: 'messagePassThrough' }, + }, + }, + categories: { + default: { appenders: ['sync'], level: 'debug' }, + }, + }); + const logger = log4js.getLogger(); + logger.info('this should be written to the file'); - batch.test("configure with non-existent multi-directory (non-recursive, nodejs < 10.12.0)", t => { - const testFile = "tmpA/tmpB/tmpC/tmp-sync-tests-non-recursive.log"; - remove(testFile); + fs.readFile(testFile, 'utf8', (err, contents) => { + t.match(contents, `this should be written to the file${EOL}`); + t.end(); + }); + } + ); - t.teardown(() => { + batch.test( + 'configure with non-existent multi-directory (non-recursive, nodejs < 10.12.0)', + (t) => { + const testFile = 'tmpA/tmpB/tmpC/tmp-sync-tests-non-recursive.log'; remove(testFile); - try { - fs.rmdirSync("tmpA/tmpB/tmpC"); - fs.rmdirSync("tmpA/tmpB"); - fs.rmdirSync("tmpA"); - } catch (e) { - // doesn't matter - } - }); - const sandboxedLog4js = sandbox.require("../../lib/log4js", { - requires: { - fs: { - ...fs, - mkdirSync(dirPath, options) { - return fs.mkdirSync(dirPath, { ...options, ...{ recursive: false } }); - } + t.teardown(() => { + remove(testFile); + try { + fs.rmdirSync('tmpA/tmpB/tmpC'); + fs.rmdirSync('tmpA/tmpB'); + fs.rmdirSync('tmpA'); + } catch (e) { + // doesn't matter } - } - }); - sandboxedLog4js.configure({ - appenders: { - sync: { - type: "fileSync", - filename: testFile, - layout: { type: "messagePassThrough" } - } - }, - categories: { - default: { appenders: ["sync"], level: "debug" } - } - }); - const logger = sandboxedLog4js.getLogger(); - logger.info("this should be written to the file"); + }); - fs.readFile(testFile, "utf8", (err, contents) => { - t.match(contents, `this should be written to the file${EOL}`); - t.end(); - }); - }); + const sandboxedLog4js = sandbox.require('../../lib/log4js', { + requires: { + fs: { + ...fs, + mkdirSync(dirPath, options) { + return fs.mkdirSync(dirPath, { + ...options, + ...{ recursive: false }, + }); + }, + }, + }, + }); + sandboxedLog4js.configure({ + appenders: { + sync: { + type: 'fileSync', + filename: testFile, + layout: { type: 'messagePassThrough' }, + }, + }, + categories: { + default: { appenders: ['sync'], level: 'debug' }, + }, + }); + const logger = sandboxedLog4js.getLogger(); + logger.info('this should be written to the file'); - batch.test("configure with non-existent multi-directory (error handling)", t => { - const testFile = "tmpA/tmpB/tmpC/tmp-sync-tests-error-handling.log"; - remove(testFile); + fs.readFile(testFile, 'utf8', (err, contents) => { + t.match(contents, `this should be written to the file${EOL}`); + t.end(); + }); + } + ); - t.teardown(() => { + batch.test( + 'configure with non-existent multi-directory (error handling)', + (t) => { + const testFile = 'tmpA/tmpB/tmpC/tmp-sync-tests-error-handling.log'; remove(testFile); - try { - fs.rmdirSync("tmpA/tmpB/tmpC"); - fs.rmdirSync("tmpA/tmpB"); - fs.rmdirSync("tmpA"); - } catch (e) { - // doesn't matter - } - }); - const errorEPERM = new Error("EPERM"); - errorEPERM.code = "EPERM"; - - let sandboxedLog4js = sandbox.require("../../lib/log4js", { - requires: { - fs: { - ...fs, - mkdirSync() { - throw errorEPERM ; - } + t.teardown(() => { + remove(testFile); + try { + fs.rmdirSync('tmpA/tmpB/tmpC'); + fs.rmdirSync('tmpA/tmpB'); + fs.rmdirSync('tmpA'); + } catch (e) { + // doesn't matter } - } - }); - t.throws( - () => - sandboxedLog4js.configure({ - appenders: { - sync: { - type: "fileSync", - filename: testFile, - layout: { type: "messagePassThrough" } - } - }, - categories: { - default: { appenders: ["sync"], level: "debug" } - } - }), - errorEPERM - ); + }); - const errorEROFS = new Error("EROFS"); - errorEROFS.code = "EROFS"; + const errorEPERM = new Error('EPERM'); + errorEPERM.code = 'EPERM'; - sandboxedLog4js = sandbox.require("../../lib/log4js", { - requires: { - fs: { - ...fs, - mkdirSync() { - throw errorEROFS; + let sandboxedLog4js = sandbox.require('../../lib/log4js', { + requires: { + fs: { + ...fs, + mkdirSync() { + throw errorEPERM; + }, }, - statSync() { - return { isDirectory() { return false; } }; - } - } - } - }); - t.throws( - () => - sandboxedLog4js.configure({ - appenders: { - sync: { - type: "fileSync", - filename: testFile, - layout: { type: "messagePassThrough" } - } + }, + }); + t.throws( + () => + sandboxedLog4js.configure({ + appenders: { + sync: { + type: 'fileSync', + filename: testFile, + layout: { type: 'messagePassThrough' }, + }, + }, + categories: { + default: { appenders: ['sync'], level: 'debug' }, + }, + }), + errorEPERM + ); + + const errorEROFS = new Error('EROFS'); + errorEROFS.code = 'EROFS'; + + sandboxedLog4js = sandbox.require('../../lib/log4js', { + requires: { + fs: { + ...fs, + mkdirSync() { + throw errorEROFS; + }, + statSync() { + return { + isDirectory() { + return false; + }, + }; + }, }, - categories: { - default: { appenders: ["sync"], level: "debug" } - } - }), - errorEROFS - ); + }, + }); + t.throws( + () => + sandboxedLog4js.configure({ + appenders: { + sync: { + type: 'fileSync', + filename: testFile, + layout: { type: 'messagePassThrough' }, + }, + }, + categories: { + default: { appenders: ['sync'], level: 'debug' }, + }, + }), + errorEROFS + ); - fs.mkdirSync("tmpA/tmpB/tmpC", { recursive: true }); + fs.mkdirSync('tmpA/tmpB/tmpC', { recursive: true }); - sandboxedLog4js = sandbox.require("../../lib/log4js", { - requires: { - fs: { - ...fs, - mkdirSync() { - throw errorEROFS; - } - } - } - }); - t.doesNotThrow( - () => + sandboxedLog4js = sandbox.require('../../lib/log4js', { + requires: { + fs: { + ...fs, + mkdirSync() { + throw errorEROFS; + }, + }, + }, + }); + t.doesNotThrow(() => sandboxedLog4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, - layout: { type: "messagePassThrough" } - } + layout: { type: 'messagePassThrough' }, + }, }, categories: { - default: { appenders: ["sync"], level: "debug" } - } + default: { appenders: ['sync'], level: 'debug' }, + }, }) - ); + ); - t.end(); - }); + t.end(); + } + ); - batch.test("test options", t => { - const testFile = "tmp-options-tests.log"; + batch.test('test options', (t) => { + const testFile = 'tmp-options-tests.log'; remove(testFile); t.teardown(() => { @@ -546,22 +567,22 @@ test("log4js fileSyncAppender", batch => { log4js.configure({ appenders: { sync: { - type: "fileSync", + type: 'fileSync', filename: testFile, - layout: { type: "messagePassThrough" }, - flags: "w", - encoding: "ascii", - mode: 0o666 - } + layout: { type: 'messagePassThrough' }, + flags: 'w', + encoding: 'ascii', + mode: 0o666, + }, }, categories: { - default: { appenders: ["sync"], level: "info" } - } + default: { appenders: ['sync'], level: 'info' }, + }, }); const logger = log4js.getLogger(); - logger.warn("log message"); + logger.warn('log message'); - fs.readFile(testFile, "ascii", (err, contents) => { + fs.readFile(testFile, 'ascii', (err, contents) => { t.match(contents, `log message${EOL}`); t.end(); }); diff --git a/test/tap/layouts-test.js b/test/tap/layouts-test.js index 5e5863ad..e925bf54 100644 --- a/test/tap/layouts-test.js +++ b/test/tap/layouts-test.js @@ -1,7 +1,7 @@ -const { test } = require("tap"); -const debug = require("debug"); -const os = require("os"); -const path = require("path"); +const { test } = require('tap'); +const debug = require('debug'); +const os = require('os'); +const path = require('path'); const { EOL } = os; @@ -10,189 +10,192 @@ function testPattern(assert, layout, event, tokens, pattern, value) { assert.equal(layout(pattern, tokens)(event), value); } -test("log4js layouts", batch => { - batch.test("colouredLayout", t => { - const layout = require("../../lib/layouts").colouredLayout; +test('log4js layouts', (batch) => { + batch.test('colouredLayout', (t) => { + const layout = require('../../lib/layouts').colouredLayout; - t.test("should apply level colour codes to output", assert => { + t.test('should apply level colour codes to output', (assert) => { const output = layout({ - data: ["nonsense"], + data: ['nonsense'], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { toString() { - return "ERROR"; + return 'ERROR'; }, - colour: "red" - } + colour: 'red', + }, }); assert.equal( output, - "\x1B[91m[2010-12-05T14:18:30.045] [ERROR] cheese - \x1B[39mnonsense" + '\x1B[91m[2010-12-05T14:18:30.045] [ERROR] cheese - \x1B[39mnonsense' ); assert.end(); }); - t.test("should support the console.log format for the message", assert => { - const output = layout({ - data: ["thing %d", 2], - startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", - level: { - toString() { - return "ERROR"; + t.test( + 'should support the console.log format for the message', + (assert) => { + const output = layout({ + data: ['thing %d', 2], + startTime: new Date(2010, 11, 5, 14, 18, 30, 45), + categoryName: 'cheese', + level: { + toString() { + return 'ERROR'; + }, + colour: 'red', }, - colour: "red" - } - }); - assert.equal( - output, - "\x1B[91m[2010-12-05T14:18:30.045] [ERROR] cheese - \x1B[39mthing 2" - ); - assert.end(); - }); + }); + assert.equal( + output, + '\x1B[91m[2010-12-05T14:18:30.045] [ERROR] cheese - \x1B[39mthing 2' + ); + assert.end(); + } + ); t.end(); }); - batch.test("messagePassThroughLayout", t => { - const layout = require("../../lib/layouts").messagePassThroughLayout; + batch.test('messagePassThroughLayout', (t) => { + const layout = require('../../lib/layouts').messagePassThroughLayout; t.equal( layout({ - data: ["nonsense"], + data: ['nonsense'], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { - colour: "green", + colour: 'green', toString() { - return "ERROR"; - } - } + return 'ERROR'; + }, + }, }), - "nonsense", - "should take a logevent and output only the message" + 'nonsense', + 'should take a logevent and output only the message' ); t.equal( layout({ - data: ["thing %d", 1, "cheese"], + data: ['thing %d', 1, 'cheese'], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { - colour: "green", + colour: 'green', toString() { - return "ERROR"; - } - } + return 'ERROR'; + }, + }, }), - "thing 1 cheese", - "should support the console.log format for the message" + 'thing 1 cheese', + 'should support the console.log format for the message' ); t.equal( layout({ data: [{ thing: 1 }], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { - colour: "green", + colour: 'green', toString() { - return "ERROR"; - } - } + return 'ERROR'; + }, + }, }), - "{ thing: 1 }", - "should output the first item even if it is not a string" + '{ thing: 1 }', + 'should output the first item even if it is not a string' ); t.match( layout({ data: [new Error()], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { - colour: "green", + colour: 'green', toString() { - return "ERROR"; - } - } + return 'ERROR'; + }, + }, }), /at (Test\.batch\.test\.t|Test\.)\s+\((.*)test[\\/]tap[\\/]layouts-test\.js:\d+:\d+\)/, - "regexp did not return a match - should print the stacks of a passed error objects" + 'regexp did not return a match - should print the stacks of a passed error objects' ); - t.test("with passed augmented errors", assert => { - const e = new Error("My Unique Error Message"); - e.augmented = "My Unique attribute value"; - e.augObj = { at1: "at2" }; + t.test('with passed augmented errors', (assert) => { + const e = new Error('My Unique Error Message'); + e.augmented = 'My Unique attribute value'; + e.augObj = { at1: 'at2' }; const layoutOutput = layout({ data: [e], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "cheese", + categoryName: 'cheese', level: { - colour: "green", + colour: 'green', toString() { - return "ERROR"; - } - } + return 'ERROR'; + }, + }, }); assert.match( layoutOutput, /Error: My Unique Error Message/, - "should print the contained error message" + 'should print the contained error message' ); assert.match( layoutOutput, /augmented:\s'My Unique attribute value'/, - "should print error augmented string attributes" + 'should print error augmented string attributes' ); assert.match( layoutOutput, /augObj:\s\{ at1: 'at2' \}/, - "should print error augmented object attributes" + 'should print error augmented object attributes' ); assert.end(); }); t.end(); }); - batch.test("basicLayout", t => { - const layout = require("../../lib/layouts").basicLayout; + batch.test('basicLayout', (t) => { + const layout = require('../../lib/layouts').basicLayout; const event = { - data: ["this is a test"], + data: ['this is a test'], startTime: new Date(2010, 11, 5, 14, 18, 30, 45), - categoryName: "tests", + categoryName: 'tests', level: { toString() { - return "DEBUG"; - } - } + return 'DEBUG'; + }, + }, }; t.equal( layout(event), - "[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test" + '[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test' ); t.test( - "should output a stacktrace, message if the event has an error attached", - assert => { + 'should output a stacktrace, message if the event has an error attached', + (assert) => { let i; - const error = new Error("Some made-up error"); + const error = new Error('Some made-up error'); const stack = error.stack.split(/\n/); - event.data = ["this is a test", error]; + event.data = ['this is a test', error]; const output = layout(event); const lines = output.split(/\n/); assert.equal(lines.length, stack.length); assert.equal( lines[0], - "[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test Error: Some made-up error" + '[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test Error: Some made-up error' ); for (i = 1; i < stack.length; i++) { assert.equal(lines[i], stack[i]); @@ -202,19 +205,19 @@ test("log4js layouts", batch => { ); t.test( - "should output any extra data in the log event as util.inspect strings", - assert => { + 'should output any extra data in the log event as util.inspect strings', + (assert) => { event.data = [ - "this is a test", + 'this is a test', { - name: "Cheese", - message: "Gorgonzola smells." - } + name: 'Cheese', + message: 'Gorgonzola smells.', + }, ]; const output = layout(event); assert.equal( output, - "[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test " + + '[2010-12-05T14:18:30.045] [DEBUG] tests - this is a test ' + "{ name: 'Cheese', message: 'Gorgonzola smells.' }" ); assert.end(); @@ -223,42 +226,46 @@ test("log4js layouts", batch => { t.end(); }); - batch.test("dummyLayout", t => { - const layout = require("../../lib/layouts").dummyLayout; + batch.test('dummyLayout', (t) => { + const layout = require('../../lib/layouts').dummyLayout; - t.test("should output just the first element of the log data", assert => { + t.test('should output just the first element of the log data', (assert) => { const event = { - data: ["this is the first value", "this is not"], - startTime: new Date("2010-12-05 14:18:30.045"), - categoryName: "multiple.levels.of.tests", + data: ['this is the first value', 'this is not'], + startTime: new Date('2010-12-05 14:18:30.045'), + categoryName: 'multiple.levels.of.tests', level: { toString() { - return "DEBUG"; + return 'DEBUG'; }, - colour: "cyan" - } + colour: 'cyan', + }, }; - assert.equal(layout(event), "this is the first value"); + assert.equal(layout(event), 'this is the first value'); assert.end(); }); t.end(); }); - batch.test("patternLayout", t => { - const originalListener = process.listeners("warning")[process.listeners("warning").length - 1]; - const warningListener = error => { - if (error.name === "DeprecationWarning") { - if (error.code.startsWith("log4js-node-DEP0003") || error.code.startsWith("log4js-node-DEP0004")) { + batch.test('patternLayout', (t) => { + const originalListener = + process.listeners('warning')[process.listeners('warning').length - 1]; + const warningListener = (error) => { + if (error.name === 'DeprecationWarning') { + if ( + error.code.startsWith('log4js-node-DEP0003') || + error.code.startsWith('log4js-node-DEP0004') + ) { return; } } originalListener(error); }; - process.off("warning", originalListener); - process.on("warning", warningListener); + process.off('warning', originalListener); + process.on('warning', warningListener); - const debugWasEnabled = debug.enabled("log4js:layouts"); + const debugWasEnabled = debug.enabled('log4js:layouts'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -273,38 +280,38 @@ test("log4js layouts", batch => { batch.teardown(async () => { // next event loop so that past warnings will not be printed setImmediate(() => { - process.off("warning", warningListener); - process.on("warning", originalListener); + process.off('warning', warningListener); + process.on('warning', originalListener); }); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); const tokens = { - testString: "testStringToken", + testString: 'testStringToken', testFunction() { - return "testFunctionToken"; + return 'testFunctionToken'; }, fnThatUsesLogEvent(logEvent) { return logEvent.level.toString(); - } + }, }; // console.log([Error('123').stack.split('\n').slice(1).join('\n')]) const callStack = - " at repl:1:14\n at ContextifyScript.Script.runInThisContext (vm.js:50:33)\n at REPLServer.defaultEval (repl.js:240:29)\n at bound (domain.js:301:14)\n at REPLServer.runBound [as eval] (domain.js:314:12)\n at REPLServer.onLine (repl.js:468:10)\n at emitOne (events.js:121:20)\n at REPLServer.emit (events.js:211:7)\n at REPLServer.Interface._onLine (readline.js:280:10)\n at REPLServer.Interface._line (readline.js:629:8)"; // eslint-disable-line max-len - const fileName = path.normalize("/log4js-node/test/tap/layouts-test.js"); + ' at repl:1:14\n at ContextifyScript.Script.runInThisContext (vm.js:50:33)\n at REPLServer.defaultEval (repl.js:240:29)\n at bound (domain.js:301:14)\n at REPLServer.runBound [as eval] (domain.js:314:12)\n at REPLServer.onLine (repl.js:468:10)\n at emitOne (events.js:121:20)\n at REPLServer.emit (events.js:211:7)\n at REPLServer.Interface._onLine (readline.js:280:10)\n at REPLServer.Interface._line (readline.js:629:8)'; // eslint-disable-line max-len + const fileName = path.normalize('/log4js-node/test/tap/layouts-test.js'); const lineNumber = 1; const columnNumber = 14; const event = { - data: ["this is a test"], - startTime: new Date("2010-12-05 14:18:30.045"), - categoryName: "multiple.levels.of.tests", + data: ['this is a test'], + startTime: new Date('2010-12-05 14:18:30.045'), + categoryName: 'multiple.levels.of.tests', level: { toString() { - return "DEBUG"; + return 'DEBUG'; }, - colour: "cyan" + colour: 'cyan', }, context: tokens, @@ -312,139 +319,142 @@ test("log4js layouts", batch => { callStack, fileName, lineNumber, - columnNumber + columnNumber, }; event.startTime.getTimezoneOffset = () => -600; - const layout = require("../../lib/layouts").patternLayout; + const layout = require('../../lib/layouts').patternLayout; - t.test('should default to "time logLevel loggerName - message"', assert => { - testPattern( - assert, - layout, - event, - tokens, - null, - `14:18:30 DEBUG multiple.levels.of.tests - this is a test${EOL}` - ); - assert.end(); - }); + t.test( + 'should default to "time logLevel loggerName - message"', + (assert) => { + testPattern( + assert, + layout, + event, + tokens, + null, + `14:18:30 DEBUG multiple.levels.of.tests - this is a test${EOL}` + ); + assert.end(); + } + ); - t.test("%r should output time only", assert => { - testPattern(assert, layout, event, tokens, "%r", "14:18:30"); + t.test('%r should output time only', (assert) => { + testPattern(assert, layout, event, tokens, '%r', '14:18:30'); assert.end(); }); - t.test("%p should output the log level", assert => { - testPattern(assert, layout, event, tokens, "%p", "DEBUG"); + t.test('%p should output the log level', (assert) => { + testPattern(assert, layout, event, tokens, '%p', 'DEBUG'); assert.end(); }); - t.test("%c should output the log category", assert => { + t.test('%c should output the log category', (assert) => { testPattern( assert, layout, event, tokens, - "%c", - "multiple.levels.of.tests" + '%c', + 'multiple.levels.of.tests' ); assert.end(); }); - t.test("%m should output the log data", assert => { - testPattern(assert, layout, event, tokens, "%m", "this is a test"); + t.test('%m should output the log data', (assert) => { + testPattern(assert, layout, event, tokens, '%m', 'this is a test'); assert.end(); }); - t.test("%n should output a new line", assert => { - testPattern(assert, layout, event, tokens, "%n", EOL); + t.test('%n should output a new line', (assert) => { + testPattern(assert, layout, event, tokens, '%n', EOL); assert.end(); }); - t.test("%h should output hostname", assert => { + t.test('%h should output hostname', (assert) => { testPattern( assert, layout, event, tokens, - "%h", + '%h', os.hostname().toString() ); assert.end(); }); - t.test("%z should output pid", assert => { - testPattern(assert, layout, event, tokens, "%z", process.pid.toString()); + t.test('%z should output pid', (assert) => { + testPattern(assert, layout, event, tokens, '%z', process.pid.toString()); assert.end(); }); - t.test("%z should pick up pid from log event if present", assert => { - event.pid = "1234"; - testPattern(assert, layout, event, tokens, "%z", "1234"); + t.test('%z should pick up pid from log event if present', (assert) => { + event.pid = '1234'; + testPattern(assert, layout, event, tokens, '%z', '1234'); delete event.pid; assert.end(); }); - t.test("%y should output pid (was cluster info)", assert => { - testPattern(assert, layout, event, tokens, "%y", process.pid.toString()); + t.test('%y should output pid (was cluster info)', (assert) => { + testPattern(assert, layout, event, tokens, '%y', process.pid.toString()); assert.end(); }); t.test( - "%c should handle category names like java-style package names", - assert => { - testPattern(assert, layout, event, tokens, "%c{1}", "tests"); - testPattern(assert, layout, event, tokens, "%c{2}", "of.tests"); - testPattern(assert, layout, event, tokens, "%c{3}", "levels.of.tests"); + '%c should handle category names like java-style package names', + (assert) => { + testPattern(assert, layout, event, tokens, '%c{1}', 'tests'); + testPattern(assert, layout, event, tokens, '%c{2}', 'of.tests'); + testPattern(assert, layout, event, tokens, '%c{3}', 'levels.of.tests'); testPattern( assert, layout, event, tokens, - "%c{4}", - "multiple.levels.of.tests" + '%c{4}', + 'multiple.levels.of.tests' ); testPattern( assert, layout, event, tokens, - "%c{5}", - "multiple.levels.of.tests" + '%c{5}', + 'multiple.levels.of.tests' ); testPattern( assert, layout, event, tokens, - "%c{99}", - "multiple.levels.of.tests" + '%c{99}', + 'multiple.levels.of.tests' ); assert.end(); } ); - t.test("%d should output the date in ISO8601 format", assert => { + t.test('%d should output the date in ISO8601 format', (assert) => { testPattern( assert, layout, event, tokens, - "%d", - "2010-12-05T14:18:30.045" + '%d', + '2010-12-05T14:18:30.045' ); assert.end(); }); - t.test("%d should allow for format specification", assert => { + t.test('%d should allow for format specification', (assert) => { testPattern( assert, layout, event, tokens, - "%d{ISO8601}", - "2010-12-05T14:18:30.045" + '%d{ISO8601}', + '2010-12-05T14:18:30.045' ); testPattern( @@ -452,54 +462,58 @@ test("log4js layouts", batch => { layout, event, tokens, - "%d{ISO8601_WITH_TZ_OFFSET}", - "2010-12-05T14:18:30.045+10:00" + '%d{ISO8601_WITH_TZ_OFFSET}', + '2010-12-05T14:18:30.045+10:00' ); - const DEP0003 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0003") > -1).length; + const DEP0003 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0003') > -1 + ).length; testPattern( assert, layout, event, tokens, - "%d{ABSOLUTE}", // deprecated - "14:18:30.045" + '%d{ABSOLUTE}', // deprecated + '14:18:30.045' ); assert.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0003") > -1).length, + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0003') > -1).length, DEP0003 + 1, - "deprecation log4js-node-DEP0003 emitted" + 'deprecation log4js-node-DEP0003 emitted' ); testPattern( assert, layout, event, tokens, - "%d{ABSOLUTETIME}", - "14:18:30.045" + '%d{ABSOLUTETIME}', + '14:18:30.045' ); - const DEP0004 = debugLogs.filter((e) => e.indexOf("log4js-node-DEP0004") > -1).length; + const DEP0004 = debugLogs.filter( + (e) => e.indexOf('log4js-node-DEP0004') > -1 + ).length; testPattern( assert, layout, event, tokens, - "%d{DATE}", // deprecated - "05 12 2010 14:18:30.045" + '%d{DATE}', // deprecated + '05 12 2010 14:18:30.045' ); assert.equal( - debugLogs.filter((e) => e.indexOf("log4js-node-DEP0004") > -1).length, + debugLogs.filter((e) => e.indexOf('log4js-node-DEP0004') > -1).length, DEP0004 + 1, - "deprecation log4js-node-DEP0004 emitted" + 'deprecation log4js-node-DEP0004 emitted' ); testPattern( assert, layout, event, tokens, - "%d{DATETIME}", - "05 12 2010 14:18:30.045" + '%d{DATETIME}', + '05 12 2010 14:18:30.045' ); testPattern( @@ -507,180 +521,200 @@ test("log4js layouts", batch => { layout, event, tokens, - "%d{yy MM dd hh mm ss}", - "10 12 05 14 18 30" + '%d{yy MM dd hh mm ss}', + '10 12 05 14 18 30' ); testPattern( assert, layout, event, tokens, - "%d{yyyy MM dd}", - "2010 12 05" + '%d{yyyy MM dd}', + '2010 12 05' ); testPattern( assert, layout, event, tokens, - "%d{yyyy MM dd hh mm ss SSS}", - "2010 12 05 14 18 30 045" + '%d{yyyy MM dd hh mm ss SSS}', + '2010 12 05 14 18 30 045' ); assert.end(); }); - t.test("%% should output %", assert => { - testPattern(assert, layout, event, tokens, "%%", "%"); + t.test('%% should output %', (assert) => { + testPattern(assert, layout, event, tokens, '%%', '%'); assert.end(); }); - t.test("%f should output filename", assert => { - testPattern(assert, layout, event, tokens, "%f", fileName); + t.test('%f should output filename', (assert) => { + testPattern(assert, layout, event, tokens, '%f', fileName); assert.end(); }); - t.test("%f should handle filename depth", assert => { - testPattern(assert, layout, event, tokens, "%f{1}", "layouts-test.js"); + t.test('%f should handle filename depth', (assert) => { + testPattern(assert, layout, event, tokens, '%f{1}', 'layouts-test.js'); testPattern( assert, layout, event, tokens, - "%f{2}", - path.join("tap", "layouts-test.js") + '%f{2}', + path.join('tap', 'layouts-test.js') ); testPattern( assert, layout, event, tokens, - "%f{3}", - path.join("test", "tap", "layouts-test.js") + '%f{3}', + path.join('test', 'tap', 'layouts-test.js') ); testPattern( assert, layout, event, tokens, - "%f{4}", - path.join("log4js-node","test","tap","layouts-test.js") + '%f{4}', + path.join('log4js-node', 'test', 'tap', 'layouts-test.js') ); testPattern( assert, layout, event, tokens, - "%f{5}", - path.join("/log4js-node","test","tap","layouts-test.js") + '%f{5}', + path.join('/log4js-node', 'test', 'tap', 'layouts-test.js') ); testPattern( assert, layout, event, tokens, - "%f{99}", - path.join("/log4js-node","test","tap","layouts-test.js") + '%f{99}', + path.join('/log4js-node', 'test', 'tap', 'layouts-test.js') ); assert.end(); }); - t.test("%f should accept truncation and padding", assert => { - testPattern(assert, layout, event, tokens, "%.5f", fileName.slice(0, 5)); - testPattern(assert, layout, event, tokens, "%20f{1}", " layouts-test.js"); - testPattern(assert, layout, event, tokens, "%30.30f{2}", ` ${ path.join("tap","layouts-test.js")}`); - testPattern(assert, layout, event, tokens, "%10.-5f{1}", " st.js"); + t.test('%f should accept truncation and padding', (assert) => { + testPattern(assert, layout, event, tokens, '%.5f', fileName.slice(0, 5)); + testPattern( + assert, + layout, + event, + tokens, + '%20f{1}', + ' layouts-test.js' + ); + testPattern( + assert, + layout, + event, + tokens, + '%30.30f{2}', + ` ${path.join('tap', 'layouts-test.js')}` + ); + testPattern(assert, layout, event, tokens, '%10.-5f{1}', ' st.js'); assert.end(); }); - t.test("%l should output line number", assert => { - testPattern(assert, layout, event, tokens, "%l", lineNumber.toString()); + t.test('%l should output line number', (assert) => { + testPattern(assert, layout, event, tokens, '%l', lineNumber.toString()); assert.end(); }); - t.test("%l should accept truncation and padding", assert => { - testPattern(assert, layout, event, tokens, "%5.10l", " 1"); - testPattern(assert, layout, event, tokens, "%.5l", "1"); - testPattern(assert, layout, event, tokens, "%.-5l", "1"); - testPattern(assert, layout, event, tokens, "%-5l", "1 "); + t.test('%l should accept truncation and padding', (assert) => { + testPattern(assert, layout, event, tokens, '%5.10l', ' 1'); + testPattern(assert, layout, event, tokens, '%.5l', '1'); + testPattern(assert, layout, event, tokens, '%.-5l', '1'); + testPattern(assert, layout, event, tokens, '%-5l', '1 '); assert.end(); }); - t.test("%o should output column postion", assert => { - testPattern(assert, layout, event, tokens, "%o", columnNumber.toString()); + t.test('%o should output column postion', (assert) => { + testPattern(assert, layout, event, tokens, '%o', columnNumber.toString()); assert.end(); }); - t.test("%o should accept truncation and padding", assert => { - testPattern(assert, layout, event, tokens, "%5.10o", " 14"); - testPattern(assert, layout, event, tokens, "%.5o", "14"); - testPattern(assert, layout, event, tokens, "%.1o", "1"); - testPattern(assert, layout, event, tokens, "%.-1o", "4"); - testPattern(assert, layout, event, tokens, "%-5o", "14 "); + t.test('%o should accept truncation and padding', (assert) => { + testPattern(assert, layout, event, tokens, '%5.10o', ' 14'); + testPattern(assert, layout, event, tokens, '%.5o', '14'); + testPattern(assert, layout, event, tokens, '%.1o', '1'); + testPattern(assert, layout, event, tokens, '%.-1o', '4'); + testPattern(assert, layout, event, tokens, '%-5o', '14 '); assert.end(); }); - t.test("%s should output stack", assert => { - testPattern(assert, layout, event, tokens, "%s", callStack); + t.test('%s should output stack', (assert) => { + testPattern(assert, layout, event, tokens, '%s', callStack); assert.end(); }); - t.test("%f should output empty string when fileName not exist", assert => { - delete event.fileName; - testPattern(assert, layout, event, tokens, "%f", ""); - assert.end(); - }); + t.test( + '%f should output empty string when fileName not exist', + (assert) => { + delete event.fileName; + testPattern(assert, layout, event, tokens, '%f', ''); + assert.end(); + } + ); t.test( - "%l should output empty string when lineNumber not exist", - assert => { + '%l should output empty string when lineNumber not exist', + (assert) => { delete event.lineNumber; - testPattern(assert, layout, event, tokens, "%l", ""); + testPattern(assert, layout, event, tokens, '%l', ''); assert.end(); } ); t.test( - "%o should output empty string when columnNumber not exist", - assert => { + '%o should output empty string when columnNumber not exist', + (assert) => { delete event.columnNumber; - testPattern(assert, layout, event, tokens, "%o", ""); + testPattern(assert, layout, event, tokens, '%o', ''); assert.end(); } ); - t.test("%s should output empty string when callStack not exist", assert => { - delete event.callStack; - testPattern(assert, layout, event, tokens, "%s", ""); - assert.end(); - }); + t.test( + '%s should output empty string when callStack not exist', + (assert) => { + delete event.callStack; + testPattern(assert, layout, event, tokens, '%s', ''); + assert.end(); + } + ); - t.test("should output anything not preceded by % as literal", assert => { + t.test('should output anything not preceded by % as literal', (assert) => { testPattern( assert, layout, event, tokens, - "blah blah blah", - "blah blah blah" + 'blah blah blah', + 'blah blah blah' ); assert.end(); }); t.test( - "should output the original string if no replacer matches the token", - assert => { - testPattern(assert, layout, event, tokens, "%a{3}", "a{3}"); + 'should output the original string if no replacer matches the token', + (assert) => { + testPattern(assert, layout, event, tokens, '%a{3}', 'a{3}'); assert.end(); } ); - t.test("should handle complicated patterns", assert => { + t.test('should handle complicated patterns', (assert) => { testPattern( assert, layout, event, tokens, - "%m%n %c{2} at %d{ABSOLUTE} cheese %p%n", // deprecated + '%m%n %c{2} at %d{ABSOLUTE} cheese %p%n', // deprecated `this is a test${EOL} of.tests at 14:18:30.045 cheese DEBUG${EOL}` ); testPattern( @@ -688,214 +722,214 @@ test("log4js layouts", batch => { layout, event, tokens, - "%m%n %c{2} at %d{ABSOLUTETIME} cheese %p%n", + '%m%n %c{2} at %d{ABSOLUTETIME} cheese %p%n', `this is a test${EOL} of.tests at 14:18:30.045 cheese DEBUG${EOL}` ); assert.end(); }); - t.test("should truncate fields if specified", assert => { - testPattern(assert, layout, event, tokens, "%.4m", "this"); - testPattern(assert, layout, event, tokens, "%.7m", "this is"); - testPattern(assert, layout, event, tokens, "%.9m", "this is a"); - testPattern(assert, layout, event, tokens, "%.14m", "this is a test"); + t.test('should truncate fields if specified', (assert) => { + testPattern(assert, layout, event, tokens, '%.4m', 'this'); + testPattern(assert, layout, event, tokens, '%.7m', 'this is'); + testPattern(assert, layout, event, tokens, '%.9m', 'this is a'); + testPattern(assert, layout, event, tokens, '%.14m', 'this is a test'); testPattern( assert, layout, event, tokens, - "%.2919102m", - "this is a test" + '%.2919102m', + 'this is a test' ); - testPattern(assert, layout, event, tokens, "%.-4m", "test"); + testPattern(assert, layout, event, tokens, '%.-4m', 'test'); assert.end(); }); - t.test("should pad fields if specified", assert => { - testPattern(assert, layout, event, tokens, "%10p", " DEBUG"); - testPattern(assert, layout, event, tokens, "%8p", " DEBUG"); - testPattern(assert, layout, event, tokens, "%6p", " DEBUG"); - testPattern(assert, layout, event, tokens, "%4p", "DEBUG"); - testPattern(assert, layout, event, tokens, "%-4p", "DEBUG"); - testPattern(assert, layout, event, tokens, "%-6p", "DEBUG "); - testPattern(assert, layout, event, tokens, "%-8p", "DEBUG "); - testPattern(assert, layout, event, tokens, "%-10p", "DEBUG "); + t.test('should pad fields if specified', (assert) => { + testPattern(assert, layout, event, tokens, '%10p', ' DEBUG'); + testPattern(assert, layout, event, tokens, '%8p', ' DEBUG'); + testPattern(assert, layout, event, tokens, '%6p', ' DEBUG'); + testPattern(assert, layout, event, tokens, '%4p', 'DEBUG'); + testPattern(assert, layout, event, tokens, '%-4p', 'DEBUG'); + testPattern(assert, layout, event, tokens, '%-6p', 'DEBUG '); + testPattern(assert, layout, event, tokens, '%-8p', 'DEBUG '); + testPattern(assert, layout, event, tokens, '%-10p', 'DEBUG '); assert.end(); }); - t.test("%[%r%] should output colored time", assert => { + t.test('%[%r%] should output colored time', (assert) => { testPattern( assert, layout, event, tokens, - "%[%r%]", - "\x1B[36m14:18:30\x1B[39m" + '%[%r%]', + '\x1B[36m14:18:30\x1B[39m' ); assert.end(); }); t.test( - "%x{testString} should output the string stored in tokens", - assert => { + '%x{testString} should output the string stored in tokens', + (assert) => { testPattern( assert, layout, event, tokens, - "%x{testString}", - "testStringToken" + '%x{testString}', + 'testStringToken' ); assert.end(); } ); t.test( - "%x{testFunction} should output the result of the function stored in tokens", - assert => { + '%x{testFunction} should output the result of the function stored in tokens', + (assert) => { testPattern( assert, layout, event, tokens, - "%x{testFunction}", - "testFunctionToken" + '%x{testFunction}', + 'testFunctionToken' ); assert.end(); } ); t.test( - "%x{doesNotExist} should output the string stored in tokens", - assert => { - testPattern(assert, layout, event, tokens, "%x{doesNotExist}", "null"); + '%x{doesNotExist} should output the string stored in tokens', + (assert) => { + testPattern(assert, layout, event, tokens, '%x{doesNotExist}', 'null'); assert.end(); } ); t.test( - "%x{fnThatUsesLogEvent} should be able to use the logEvent", - assert => { + '%x{fnThatUsesLogEvent} should be able to use the logEvent', + (assert) => { testPattern( assert, layout, event, tokens, - "%x{fnThatUsesLogEvent}", - "DEBUG" + '%x{fnThatUsesLogEvent}', + 'DEBUG' ); assert.end(); } ); - t.test("%x should output the string stored in tokens", assert => { - testPattern(assert, layout, event, tokens, "%x", "null"); + t.test('%x should output the string stored in tokens', (assert) => { + testPattern(assert, layout, event, tokens, '%x', 'null'); assert.end(); }); t.test( - "%X{testString} should output the string stored in tokens", - assert => { + '%X{testString} should output the string stored in tokens', + (assert) => { testPattern( assert, layout, event, {}, - "%X{testString}", - "testStringToken" + '%X{testString}', + 'testStringToken' ); assert.end(); } ); t.test( - "%X{testFunction} should output the result of the function stored in tokens", - assert => { + '%X{testFunction} should output the result of the function stored in tokens', + (assert) => { testPattern( assert, layout, event, {}, - "%X{testFunction}", - "testFunctionToken" + '%X{testFunction}', + 'testFunctionToken' ); assert.end(); } ); t.test( - "%X{doesNotExist} should output the string stored in tokens", - assert => { - testPattern(assert, layout, event, {}, "%X{doesNotExist}", "null"); + '%X{doesNotExist} should output the string stored in tokens', + (assert) => { + testPattern(assert, layout, event, {}, '%X{doesNotExist}', 'null'); assert.end(); } ); t.test( - "%X{fnThatUsesLogEvent} should be able to use the logEvent", - assert => { + '%X{fnThatUsesLogEvent} should be able to use the logEvent', + (assert) => { testPattern( assert, layout, event, {}, - "%X{fnThatUsesLogEvent}", - "DEBUG" + '%X{fnThatUsesLogEvent}', + 'DEBUG' ); assert.end(); } ); - t.test("%X should output the string stored in tokens", assert => { - testPattern(assert, layout, event, {}, "%X", "null"); + t.test('%X should output the string stored in tokens', (assert) => { + testPattern(assert, layout, event, {}, '%X', 'null'); assert.end(); }); t.end(); }); - batch.test("layout makers", t => { - const layouts = require("../../lib/layouts"); + batch.test('layout makers', (t) => { + const layouts = require('../../lib/layouts'); - t.test("should have a maker for each layout", assert => { - assert.ok(layouts.layout("messagePassThrough")); - assert.ok(layouts.layout("basic")); - assert.ok(layouts.layout("colored")); - assert.ok(layouts.layout("coloured")); - assert.ok(layouts.layout("pattern")); - assert.ok(layouts.layout("dummy")); + t.test('should have a maker for each layout', (assert) => { + assert.ok(layouts.layout('messagePassThrough')); + assert.ok(layouts.layout('basic')); + assert.ok(layouts.layout('colored')); + assert.ok(layouts.layout('coloured')); + assert.ok(layouts.layout('pattern')); + assert.ok(layouts.layout('dummy')); assert.end(); }); t.test( - "layout pattern maker should pass pattern and tokens to layout from config", - assert => { - let layout = layouts.layout("pattern", { pattern: "%%" }); - assert.equal(layout({}), "%"); - layout = layouts.layout("pattern", { - pattern: "%x{testStringToken}", - tokens: { testStringToken: "cheese" } + 'layout pattern maker should pass pattern and tokens to layout from config', + (assert) => { + let layout = layouts.layout('pattern', { pattern: '%%' }); + assert.equal(layout({}), '%'); + layout = layouts.layout('pattern', { + pattern: '%x{testStringToken}', + tokens: { testStringToken: 'cheese' }, }); - assert.equal(layout({}), "cheese"); + assert.equal(layout({}), 'cheese'); assert.end(); } ); t.end(); }); - batch.test("add layout", t => { - const layouts = require("../../lib/layouts"); + batch.test('add layout', (t) => { + const layouts = require('../../lib/layouts'); - t.test("should be able to add a layout", assert => { - layouts.addLayout("test_layout", config => { - assert.equal(config, "test_config"); - return function(logEvent) { + t.test('should be able to add a layout', (assert) => { + layouts.addLayout('test_layout', (config) => { + assert.equal(config, 'test_config'); + return function (logEvent) { return `TEST LAYOUT >${logEvent.data}`; }; }); - const serializer = layouts.layout("test_layout", "test_config"); + const serializer = layouts.layout('test_layout', 'test_config'); assert.ok(serializer); - assert.equal(serializer({ data: "INPUT" }), "TEST LAYOUT >INPUT"); + assert.equal(serializer({ data: 'INPUT' }), 'TEST LAYOUT >INPUT'); assert.end(); }); t.end(); diff --git a/test/tap/levels-before-configure-test.js b/test/tap/levels-before-configure-test.js index b1a0b2b4..e75820ae 100644 --- a/test/tap/levels-before-configure-test.js +++ b/test/tap/levels-before-configure-test.js @@ -1,8 +1,8 @@ -const { test } = require("tap"); +const { test } = require('tap'); -test("Accessing things setup in configure before configure is called", batch => { - batch.test("should work", t => { - const log4js = require("../../lib/log4js"); +test('Accessing things setup in configure before configure is called', (batch) => { + batch.test('should work', (t) => { + const log4js = require('../../lib/log4js'); t.ok(log4js.levels); t.ok(log4js.connectLogger); t.end(); diff --git a/test/tap/levels-test.js b/test/tap/levels-test.js index 69fdbfee..89d7980b 100644 --- a/test/tap/levels-test.js +++ b/test/tap/levels-test.js @@ -1,9 +1,9 @@ -const { test } = require("tap"); -const levels = require("../../lib/levels"); +const { test } = require('tap'); +const levels = require('../../lib/levels'); function assertThat(assert, level) { function assertForEach(assertion, testFn, otherLevels) { - otherLevels.forEach(other => { + otherLevels.forEach((other) => { assertion.call(assert, testFn.call(level, other)); }); } @@ -26,13 +26,13 @@ function assertThat(assert, level) { }, isNotEqualTo(lvls) { assertForEach(assert.notOk, level.isEqualTo, lvls); - } + }, }; } -test("levels", batch => { - batch.test("values", t => { - t.test("should define some levels", assert => { +test('levels', (batch) => { + batch.test('values', (t) => { + t.test('should define some levels', (assert) => { assert.ok(levels.ALL); assert.ok(levels.TRACE); assert.ok(levels.DEBUG); @@ -45,7 +45,7 @@ test("levels", batch => { assert.end(); }); - t.test("ALL", assert => { + t.test('ALL', (assert) => { const all = levels.ALL; assertThat(assert, all).isLessThanOrEqualTo([ levels.ALL, @@ -56,7 +56,7 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, all).isNotGreaterThanOrEqualTo([ levels.TRACE, @@ -66,9 +66,9 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, all).isEqualTo([levels.getLevel("ALL")]); + assertThat(assert, all).isEqualTo([levels.getLevel('ALL')]); assertThat(assert, all).isNotEqualTo([ levels.TRACE, levels.DEBUG, @@ -77,12 +77,12 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("TRACE", assert => { + t.test('TRACE', (assert) => { const trace = levels.TRACE; assertThat(assert, trace).isLessThanOrEqualTo([ levels.DEBUG, @@ -91,12 +91,12 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, trace).isNotLessThanOrEqualTo([levels.ALL]); assertThat(assert, trace).isGreaterThanOrEqualTo([ levels.ALL, - levels.TRACE + levels.TRACE, ]); assertThat(assert, trace).isNotGreaterThanOrEqualTo([ levels.DEBUG, @@ -105,9 +105,9 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, trace).isEqualTo([levels.getLevel("TRACE")]); + assertThat(assert, trace).isEqualTo([levels.getLevel('TRACE')]); assertThat(assert, trace).isNotEqualTo([ levels.ALL, levels.DEBUG, @@ -116,12 +116,12 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("DEBUG", assert => { + t.test('DEBUG', (assert) => { const debug = levels.DEBUG; assertThat(assert, debug).isLessThanOrEqualTo([ levels.INFO, @@ -129,15 +129,15 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, debug).isNotLessThanOrEqualTo([ levels.ALL, - levels.TRACE + levels.TRACE, ]); assertThat(assert, debug).isGreaterThanOrEqualTo([ levels.ALL, - levels.TRACE + levels.TRACE, ]); assertThat(assert, debug).isNotGreaterThanOrEqualTo([ levels.INFO, @@ -145,9 +145,9 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, debug).isEqualTo([levels.getLevel("DEBUG")]); + assertThat(assert, debug).isEqualTo([levels.getLevel('DEBUG')]); assertThat(assert, debug).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -156,38 +156,38 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("INFO", assert => { + t.test('INFO', (assert) => { const info = levels.INFO; assertThat(assert, info).isLessThanOrEqualTo([ levels.WARN, levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, info).isNotLessThanOrEqualTo([ levels.ALL, levels.TRACE, - levels.DEBUG + levels.DEBUG, ]); assertThat(assert, info).isGreaterThanOrEqualTo([ levels.ALL, levels.TRACE, - levels.DEBUG + levels.DEBUG, ]); assertThat(assert, info).isNotGreaterThanOrEqualTo([ levels.WARN, levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, info).isEqualTo([levels.getLevel("INFO")]); + assertThat(assert, info).isEqualTo([levels.getLevel('INFO')]); assertThat(assert, info).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -196,38 +196,38 @@ test("levels", batch => { levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("WARN", assert => { + t.test('WARN', (assert) => { const warn = levels.WARN; assertThat(assert, warn).isLessThanOrEqualTo([ levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, warn).isNotLessThanOrEqualTo([ levels.ALL, levels.TRACE, levels.DEBUG, - levels.INFO + levels.INFO, ]); assertThat(assert, warn).isGreaterThanOrEqualTo([ levels.ALL, levels.TRACE, levels.DEBUG, - levels.INFO + levels.INFO, ]); assertThat(assert, warn).isNotGreaterThanOrEqualTo([ levels.ERROR, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, warn).isEqualTo([levels.getLevel("WARN")]); + assertThat(assert, warn).isEqualTo([levels.getLevel('WARN')]); assertThat(assert, warn).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -235,38 +235,38 @@ test("levels", batch => { levels.INFO, levels.ERROR, levels.FATAL, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("ERROR", assert => { + t.test('ERROR', (assert) => { const error = levels.ERROR; assertThat(assert, error).isLessThanOrEqualTo([ levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assertThat(assert, error).isNotLessThanOrEqualTo([ levels.ALL, levels.TRACE, levels.DEBUG, levels.INFO, - levels.WARN + levels.WARN, ]); assertThat(assert, error).isGreaterThanOrEqualTo([ levels.ALL, levels.TRACE, levels.DEBUG, levels.INFO, - levels.WARN + levels.WARN, ]); assertThat(assert, error).isNotGreaterThanOrEqualTo([ levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, error).isEqualTo([levels.getLevel("ERROR")]); + assertThat(assert, error).isEqualTo([levels.getLevel('ERROR')]); assertThat(assert, error).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -275,12 +275,12 @@ test("levels", batch => { levels.WARN, levels.FATAL, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("FATAL", assert => { + t.test('FATAL', (assert) => { const fatal = levels.FATAL; assertThat(assert, fatal).isLessThanOrEqualTo([levels.MARK, levels.OFF]); assertThat(assert, fatal).isNotLessThanOrEqualTo([ @@ -289,7 +289,7 @@ test("levels", batch => { levels.DEBUG, levels.INFO, levels.WARN, - levels.ERROR + levels.ERROR, ]); assertThat(assert, fatal).isGreaterThanOrEqualTo([ levels.ALL, @@ -297,13 +297,13 @@ test("levels", batch => { levels.DEBUG, levels.INFO, levels.WARN, - levels.ERROR + levels.ERROR, ]); assertThat(assert, fatal).isNotGreaterThanOrEqualTo([ levels.MARK, - levels.OFF + levels.OFF, ]); - assertThat(assert, fatal).isEqualTo([levels.getLevel("FATAL")]); + assertThat(assert, fatal).isEqualTo([levels.getLevel('FATAL')]); assertThat(assert, fatal).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -312,12 +312,12 @@ test("levels", batch => { levels.WARN, levels.ERROR, levels.MARK, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("MARK", assert => { + t.test('MARK', (assert) => { const mark = levels.MARK; assertThat(assert, mark).isLessThanOrEqualTo([levels.OFF]); assertThat(assert, mark).isNotLessThanOrEqualTo([ @@ -327,7 +327,7 @@ test("levels", batch => { levels.INFO, levels.WARN, levels.FATAL, - levels.ERROR + levels.ERROR, ]); assertThat(assert, mark).isGreaterThanOrEqualTo([ levels.ALL, @@ -336,10 +336,10 @@ test("levels", batch => { levels.INFO, levels.WARN, levels.ERROR, - levels.FATAL + levels.FATAL, ]); assertThat(assert, mark).isNotGreaterThanOrEqualTo([levels.OFF]); - assertThat(assert, mark).isEqualTo([levels.getLevel("MARK")]); + assertThat(assert, mark).isEqualTo([levels.getLevel('MARK')]); assertThat(assert, mark).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -348,12 +348,12 @@ test("levels", batch => { levels.WARN, levels.ERROR, levels.FATAL, - levels.OFF + levels.OFF, ]); assert.end(); }); - t.test("OFF", assert => { + t.test('OFF', (assert) => { const off = levels.OFF; assertThat(assert, off).isNotLessThanOrEqualTo([ levels.ALL, @@ -363,7 +363,7 @@ test("levels", batch => { levels.WARN, levels.ERROR, levels.FATAL, - levels.MARK + levels.MARK, ]); assertThat(assert, off).isGreaterThanOrEqualTo([ levels.ALL, @@ -373,9 +373,9 @@ test("levels", batch => { levels.WARN, levels.ERROR, levels.FATAL, - levels.MARK + levels.MARK, ]); - assertThat(assert, off).isEqualTo([levels.getLevel("OFF")]); + assertThat(assert, off).isEqualTo([levels.getLevel('OFF')]); assertThat(assert, off).isNotEqualTo([ levels.ALL, levels.TRACE, @@ -384,53 +384,53 @@ test("levels", batch => { levels.WARN, levels.ERROR, levels.FATAL, - levels.MARK + levels.MARK, ]); assert.end(); }); t.end(); }); - batch.test("isGreaterThanOrEqualTo", t => { + batch.test('isGreaterThanOrEqualTo', (t) => { const info = levels.INFO; - assertThat(t, info).isGreaterThanOrEqualTo(["all", "trace", "debug"]); + assertThat(t, info).isGreaterThanOrEqualTo(['all', 'trace', 'debug']); assertThat(t, info).isNotGreaterThanOrEqualTo([ - "warn", - "ERROR", - "Fatal", - "MARK", - "off" + 'warn', + 'ERROR', + 'Fatal', + 'MARK', + 'off', ]); t.end(); }); - batch.test("isLessThanOrEqualTo", t => { + batch.test('isLessThanOrEqualTo', (t) => { const info = levels.INFO; - assertThat(t, info).isNotLessThanOrEqualTo(["all", "trace", "debug"]); + assertThat(t, info).isNotLessThanOrEqualTo(['all', 'trace', 'debug']); assertThat(t, info).isLessThanOrEqualTo([ - "warn", - "ERROR", - "Fatal", - "MARK", - "off" + 'warn', + 'ERROR', + 'Fatal', + 'MARK', + 'off', ]); t.end(); }); - batch.test("isEqualTo", t => { + batch.test('isEqualTo', (t) => { const info = levels.INFO; - assertThat(t, info).isEqualTo(["info", "INFO", "iNfO"]); + assertThat(t, info).isEqualTo(['info', 'INFO', 'iNfO']); t.end(); }); - batch.test("getLevel", t => { - t.equal(levels.getLevel("debug"), levels.DEBUG); - t.equal(levels.getLevel("DEBUG"), levels.DEBUG); - t.equal(levels.getLevel("DeBuG"), levels.DEBUG); - t.notOk(levels.getLevel("cheese")); - t.equal(levels.getLevel("cheese", levels.DEBUG), levels.DEBUG); + batch.test('getLevel', (t) => { + t.equal(levels.getLevel('debug'), levels.DEBUG); + t.equal(levels.getLevel('DEBUG'), levels.DEBUG); + t.equal(levels.getLevel('DeBuG'), levels.DEBUG); + t.notOk(levels.getLevel('cheese')); + t.equal(levels.getLevel('cheese', levels.DEBUG), levels.DEBUG); t.equal( - levels.getLevel({ level: 10000, levelStr: "DEBUG", colour: "cyan" }), + levels.getLevel({ level: 10000, levelStr: 'DEBUG', colour: 'cyan' }), levels.DEBUG ); t.end(); diff --git a/test/tap/log4js.json b/test/tap/log4js.json index 3a4e54a9..1bae43a3 100644 --- a/test/tap/log4js.json +++ b/test/tap/log4js.json @@ -1,16 +1,16 @@ { "appenders": [ - { - "category": "tests", - "type": "file", - "filename": "tmp-tests.log", - "layout": { - "type": "messagePassThrough" - } + { + "category": "tests", + "type": "file", + "filename": "tmp-tests.log", + "layout": { + "type": "messagePassThrough" + } } ], - + "levels": { - "tests": "WARN" + "tests": "WARN" } } diff --git a/test/tap/logLevelFilter-test.js b/test/tap/logLevelFilter-test.js index de022d95..aebf8b4a 100644 --- a/test/tap/logLevelFilter-test.js +++ b/test/tap/logLevelFilter-test.js @@ -1,8 +1,8 @@ -const { test } = require("tap"); -const fs = require("fs"); -const os = require("os"); +const { test } = require('tap'); +const fs = require('fs'); +const os = require('os'); -const EOL = os.EOL || "\n"; +const EOL = os.EOL || '\n'; function remove(filename) { try { @@ -12,47 +12,47 @@ function remove(filename) { } } -test("log4js logLevelFilter", batch => { - batch.test("appender", t => { - const log4js = require("../../lib/log4js"); - const recording = require("../../lib/appenders/recording"); +test('log4js logLevelFilter', (batch) => { + batch.test('appender', (t) => { + const log4js = require('../../lib/log4js'); + const recording = require('../../lib/appenders/recording'); log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "logLevelFilter", - appender: "recorder", - level: "ERROR" - } + type: 'logLevelFilter', + appender: 'recorder', + level: 'ERROR', + }, }, categories: { - default: { appenders: ["filtered"], level: "debug" } - } + default: { appenders: ['filtered'], level: 'debug' }, + }, }); - const logger = log4js.getLogger("logLevelTest"); - logger.debug("this should not trigger an event"); - logger.warn("neither should this"); - logger.error("this should, though"); - logger.fatal("so should this"); + const logger = log4js.getLogger('logLevelTest'); + logger.debug('this should not trigger an event'); + logger.warn('neither should this'); + logger.error('this should, though'); + logger.fatal('so should this'); const logEvents = recording.replay(); t.test( - "should only pass log events greater than or equal to its own level", - assert => { + 'should only pass log events greater than or equal to its own level', + (assert) => { assert.equal(logEvents.length, 2); - assert.equal(logEvents[0].data[0], "this should, though"); - assert.equal(logEvents[1].data[0], "so should this"); + assert.equal(logEvents[0].data[0], 'this should, though'); + assert.equal(logEvents[1].data[0], 'so should this'); assert.end(); } ); t.end(); }); - batch.test("configure", t => { - const log4js = require("../../lib/log4js"); + batch.test('configure', (t) => { + const log4js = require('../../lib/log4js'); remove(`${__dirname}/logLevelFilter.log`); remove(`${__dirname}/logLevelFilter-warnings.log`); @@ -66,89 +66,89 @@ test("log4js logLevelFilter", batch => { log4js.configure({ appenders: { - "warning-file": { - type: "file", - filename: "test/tap/logLevelFilter-warnings.log", - layout: { type: "messagePassThrough" } + 'warning-file': { + type: 'file', + filename: 'test/tap/logLevelFilter-warnings.log', + layout: { type: 'messagePassThrough' }, }, warnings: { - type: "logLevelFilter", - level: "WARN", - appender: "warning-file" + type: 'logLevelFilter', + level: 'WARN', + appender: 'warning-file', }, - "debug-file": { - type: "file", - filename: "test/tap/logLevelFilter-debugs.log", - layout: { type: "messagePassThrough" } + 'debug-file': { + type: 'file', + filename: 'test/tap/logLevelFilter-debugs.log', + layout: { type: 'messagePassThrough' }, }, debugs: { - type: "logLevelFilter", - level: "TRACE", - maxLevel: "DEBUG", - appender: "debug-file" + type: 'logLevelFilter', + level: 'TRACE', + maxLevel: 'DEBUG', + appender: 'debug-file', }, tests: { - type: "file", - filename: "test/tap/logLevelFilter.log", + type: 'file', + filename: 'test/tap/logLevelFilter.log', layout: { - type: "messagePassThrough" - } - } + type: 'messagePassThrough', + }, + }, }, categories: { - default: { appenders: ["tests", "warnings", "debugs"], level: "trace" } - } + default: { appenders: ['tests', 'warnings', 'debugs'], level: 'trace' }, + }, }); - const logger = log4js.getLogger("tests"); - logger.debug("debug"); - logger.info("info"); - logger.error("error"); - logger.warn("warn"); - logger.debug("debug"); - logger.trace("trace"); + const logger = log4js.getLogger('tests'); + logger.debug('debug'); + logger.info('info'); + logger.error('error'); + logger.warn('warn'); + logger.debug('debug'); + logger.trace('trace'); // wait for the file system to catch up setTimeout(() => { - t.test("tmp-tests.log should contain all log messages", assert => { + t.test('tmp-tests.log should contain all log messages', (assert) => { fs.readFile( `${__dirname}/logLevelFilter.log`, - "utf8", + 'utf8', (err, contents) => { const messages = contents.trim().split(EOL); assert.same(messages, [ - "debug", - "info", - "error", - "warn", - "debug", - "trace" + 'debug', + 'info', + 'error', + 'warn', + 'debug', + 'trace', ]); assert.end(); } ); }); t.test( - "tmp-tests-warnings.log should contain only error and warning logs", - assert => { + 'tmp-tests-warnings.log should contain only error and warning logs', + (assert) => { fs.readFile( `${__dirname}/logLevelFilter-warnings.log`, - "utf8", + 'utf8', (err, contents) => { const messages = contents.trim().split(EOL); - assert.same(messages, ["error", "warn"]); + assert.same(messages, ['error', 'warn']); assert.end(); } ); } ); t.test( - "tmp-tests-debugs.log should contain only trace and debug logs", - assert => { + 'tmp-tests-debugs.log should contain only trace and debug logs', + (assert) => { fs.readFile( `${__dirname}/logLevelFilter-debugs.log`, - "utf8", + 'utf8', (err, contents) => { const messages = contents.trim().split(EOL); - assert.same(messages, ["debug", "debug", "trace"]); + assert.same(messages, ['debug', 'debug', 'trace']); assert.end(); } ); diff --git a/test/tap/logger-test.js b/test/tap/logger-test.js index 6582dfb2..a3eb7386 100644 --- a/test/tap/logger-test.js +++ b/test/tap/logger-test.js @@ -1,85 +1,85 @@ -const { test } = require("tap"); -const debug = require("debug")("log4js:test.logger"); -const sandbox = require("@log4js-node/sandboxed-module"); -const callsites = require("callsites"); -const levels = require("../../lib/levels"); -const categories = require("../../lib/categories"); +const { test } = require('tap'); +const debug = require('debug')('log4js:test.logger'); +const sandbox = require('@log4js-node/sandboxed-module'); +const callsites = require('callsites'); +const levels = require('../../lib/levels'); +const categories = require('../../lib/categories'); const events = []; const messages = []; -const Logger = sandbox.require("../../lib/logger", { +const Logger = sandbox.require('../../lib/logger', { requires: { - "./levels": levels, - "./categories": categories, - "./clustering": { + './levels': levels, + './categories': categories, + './clustering': { isMaster: () => true, - onlyOnMaster: fn => fn(), - send: evt => { - debug("fake clustering got event:", evt); + onlyOnMaster: (fn) => fn(), + send: (evt) => { + debug('fake clustering got event:', evt); events.push(evt); - } - } + }, + }, }, globals: { console: { ...console, error(msg) { messages.push(msg); - } - } - } + }, + }, + }, }); const testConfig = { - level: levels.TRACE + level: levels.TRACE, }; -test("../../lib/logger", batch => { +test('../../lib/logger', (batch) => { batch.beforeEach(() => { events.length = 0; testConfig.level = levels.TRACE; }); - batch.test("constructor with no parameters", t => { - t.throws(() => new Logger(), new Error("No category provided.")); + batch.test('constructor with no parameters', (t) => { + t.throws(() => new Logger(), new Error('No category provided.')); t.end(); }); - batch.test("constructor with category", t => { - const logger = new Logger("cheese"); - t.equal(logger.category, "cheese", "should use category"); - t.equal(logger.level, levels.OFF, "should use OFF log level"); + batch.test('constructor with category', (t) => { + const logger = new Logger('cheese'); + t.equal(logger.category, 'cheese', 'should use category'); + t.equal(logger.level, levels.OFF, 'should use OFF log level'); t.end(); }); - batch.test("set level should delegate", t => { - const logger = new Logger("cheese"); - logger.level = "debug"; - t.equal(logger.category, "cheese", "should use category"); - t.equal(logger.level, levels.DEBUG, "should use level"); + batch.test('set level should delegate', (t) => { + const logger = new Logger('cheese'); + logger.level = 'debug'; + t.equal(logger.category, 'cheese', 'should use category'); + t.equal(logger.level, levels.DEBUG, 'should use level'); t.end(); }); - batch.test("isLevelEnabled", t => { - const logger = new Logger("cheese"); + batch.test('isLevelEnabled', (t) => { + const logger = new Logger('cheese'); const functions = [ - "isTraceEnabled", - "isDebugEnabled", - "isInfoEnabled", - "isWarnEnabled", - "isErrorEnabled", - "isFatalEnabled" + 'isTraceEnabled', + 'isDebugEnabled', + 'isInfoEnabled', + 'isWarnEnabled', + 'isErrorEnabled', + 'isFatalEnabled', ]; t.test( - "should provide a level enabled function for all levels", - subtest => { + 'should provide a level enabled function for all levels', + (subtest) => { subtest.plan(functions.length); - functions.forEach(fn => { - subtest.type(logger[fn], "function"); + functions.forEach((fn) => { + subtest.type(logger[fn], 'function'); }); } ); - logger.level = "INFO"; + logger.level = 'INFO'; t.notOk(logger.isTraceEnabled()); t.notOk(logger.isDebugEnabled()); t.ok(logger.isInfoEnabled()); @@ -89,101 +89,104 @@ test("../../lib/logger", batch => { t.end(); }); - batch.test("should send log events to dispatch function", t => { - const logger = new Logger("cheese"); - logger.level = "debug"; - logger.debug("Event 1"); - logger.debug("Event 2"); - logger.debug("Event 3"); + batch.test('should send log events to dispatch function', (t) => { + const logger = new Logger('cheese'); + logger.level = 'debug'; + logger.debug('Event 1'); + logger.debug('Event 2'); + logger.debug('Event 3'); t.equal(events.length, 3); - t.equal(events[0].data[0], "Event 1"); - t.equal(events[1].data[0], "Event 2"); - t.equal(events[2].data[0], "Event 3"); + t.equal(events[0].data[0], 'Event 1'); + t.equal(events[1].data[0], 'Event 2'); + t.equal(events[2].data[0], 'Event 3'); t.end(); }); - batch.test("should add context values to every event", t => { - const logger = new Logger("fromage"); - logger.level = "debug"; - logger.debug("Event 1"); - logger.addContext("cheese", "edam"); - logger.debug("Event 2"); - logger.debug("Event 3"); - logger.addContext("biscuits", "timtam"); - logger.debug("Event 4"); - logger.removeContext("cheese"); - logger.debug("Event 5"); + batch.test('should add context values to every event', (t) => { + const logger = new Logger('fromage'); + logger.level = 'debug'; + logger.debug('Event 1'); + logger.addContext('cheese', 'edam'); + logger.debug('Event 2'); + logger.debug('Event 3'); + logger.addContext('biscuits', 'timtam'); + logger.debug('Event 4'); + logger.removeContext('cheese'); + logger.debug('Event 5'); logger.clearContext(); - logger.debug("Event 6"); + logger.debug('Event 6'); t.equal(events.length, 6); t.same(events[0].context, {}); - t.same(events[1].context, { cheese: "edam" }); - t.same(events[2].context, { cheese: "edam" }); - t.same(events[3].context, { cheese: "edam", biscuits: "timtam" }); - t.same(events[4].context, { biscuits: "timtam" }); + t.same(events[1].context, { cheese: 'edam' }); + t.same(events[2].context, { cheese: 'edam' }); + t.same(events[3].context, { cheese: 'edam', biscuits: 'timtam' }); + t.same(events[4].context, { biscuits: 'timtam' }); t.same(events[5].context, {}); t.end(); }); - batch.test("should not break when log data has no toString", t => { - const logger = new Logger("thing"); - logger.level = "debug"; - logger.info("Just testing ", Object.create(null)); + batch.test('should not break when log data has no toString', (t) => { + const logger = new Logger('thing'); + logger.level = 'debug'; + logger.info('Just testing ', Object.create(null)); t.equal(events.length, 1); t.end(); }); - batch.test("default should disable useCallStack unless manual enable", t => { - const logger = new Logger("stack"); - logger.level = "debug"; + batch.test( + 'default should disable useCallStack unless manual enable', + (t) => { + const logger = new Logger('stack'); + logger.level = 'debug'; - t.equal(logger.useCallStack, false); + t.equal(logger.useCallStack, false); - logger.useCallStack = false; - t.equal(logger.useCallStack, false); + logger.useCallStack = false; + t.equal(logger.useCallStack, false); - logger.useCallStack = 0; - t.equal(logger.useCallStack, false); + logger.useCallStack = 0; + t.equal(logger.useCallStack, false); - logger.useCallStack = ""; - t.equal(logger.useCallStack, false); + logger.useCallStack = ''; + t.equal(logger.useCallStack, false); - logger.useCallStack = null; - t.equal(logger.useCallStack, false); + logger.useCallStack = null; + t.equal(logger.useCallStack, false); - logger.useCallStack = undefined; - t.equal(logger.useCallStack, false); + logger.useCallStack = undefined; + t.equal(logger.useCallStack, false); - logger.useCallStack = "true"; - t.equal(logger.useCallStack, false); + logger.useCallStack = 'true'; + t.equal(logger.useCallStack, false); - logger.useCallStack = true; - t.equal(logger.useCallStack, true); - t.end(); - }); + logger.useCallStack = true; + t.equal(logger.useCallStack, true); + t.end(); + } + ); - batch.test("should correctly switch on/off useCallStack", t => { - const logger = new Logger("stack"); - logger.level = "debug"; + batch.test('should correctly switch on/off useCallStack', (t) => { + const logger = new Logger('stack'); + logger.level = 'debug'; logger.useCallStack = true; t.equal(logger.useCallStack, true); - logger.info("hello world"); + logger.info('hello world'); const callsite = callsites()[0]; t.equal(events.length, 1); - t.equal(events[0].data[0], "hello world"); + t.equal(events[0].data[0], 'hello world'); t.equal(events[0].fileName, callsite.getFileName()); t.equal(events[0].lineNumber, callsite.getLineNumber() - 1); t.equal(events[0].columnNumber, 12); logger.useCallStack = false; - logger.info("disabled"); + logger.info('disabled'); t.equal(logger.useCallStack, false); - t.equal(events[1].data[0], "disabled"); + t.equal(events[1].data[0], 'disabled'); t.equal(events[1].fileName, undefined); t.equal(events[1].lineNumber, undefined); t.equal(events[1].columnNumber, undefined); @@ -191,37 +194,37 @@ test("../../lib/logger", batch => { }); batch.test( - "Once switch on/off useCallStack will apply all same category loggers", - t => { - const logger1 = new Logger("stack"); - logger1.level = "debug"; + 'Once switch on/off useCallStack will apply all same category loggers', + (t) => { + const logger1 = new Logger('stack'); + logger1.level = 'debug'; logger1.useCallStack = true; - const logger2 = new Logger("stack"); - logger2.level = "debug"; + const logger2 = new Logger('stack'); + logger2.level = 'debug'; - logger1.info("hello world"); + logger1.info('hello world'); const callsite = callsites()[0]; t.equal(logger1.useCallStack, true); t.equal(events.length, 1); - t.equal(events[0].data[0], "hello world"); + t.equal(events[0].data[0], 'hello world'); t.equal(events[0].fileName, callsite.getFileName()); t.equal(events[0].lineNumber, callsite.getLineNumber() - 1); t.equal(events[0].columnNumber, 15); // col of the '.' in logger1.info(...) - logger2.info("hello world"); + logger2.info('hello world'); const callsite2 = callsites()[0]; t.equal(logger2.useCallStack, true); - t.equal(events[1].data[0], "hello world"); + t.equal(events[1].data[0], 'hello world'); t.equal(events[1].fileName, callsite2.getFileName()); t.equal(events[1].lineNumber, callsite2.getLineNumber() - 1); t.equal(events[1].columnNumber, 15); // col of the '.' in logger1.info(...) logger1.useCallStack = false; - logger2.info("hello world"); + logger2.info('hello world'); t.equal(logger2.useCallStack, false); - t.equal(events[2].data[0], "hello world"); + t.equal(events[2].data[0], 'hello world'); t.equal(events[2].fileName, undefined); t.equal(events[2].lineNumber, undefined); t.equal(events[2].columnNumber, undefined); @@ -230,84 +233,137 @@ test("../../lib/logger", batch => { } ); - batch.test("parseCallStack function coverage", t => { - const logger = new Logger("stack"); + batch.test('parseCallStack function coverage', (t) => { + const logger = new Logger('stack'); logger.useCallStack = true; let results; results = logger.parseCallStack(new Error()); t.ok(results); - t.equal(messages.length, 0, "should not have error"); + t.equal(messages.length, 0, 'should not have error'); - results = logger.parseCallStack(""); + results = logger.parseCallStack(''); t.notOk(results); - t.equal(messages.length, 1, "should have error"); + t.equal(messages.length, 1, 'should have error'); t.end(); }); - batch.test("should correctly change the parseCallStack function", t => { - const logger = new Logger("stack"); - const parseFunction = function() { + batch.test('should correctly change the parseCallStack function', (t) => { + const logger = new Logger('stack'); + const parseFunction = function () { return { - functionName: "test function name", - fileName: "test file name", + functionName: 'test function name', + fileName: 'test file name', lineNumber: 15, columnNumber: 25, - callStack: "test callstack" + callStack: 'test callstack', }; }; - logger.level = "debug"; + logger.level = 'debug'; logger.useCallStack = true; logger.setParseCallStackFunction(parseFunction); t.equal(logger.parseCallStack, parseFunction); - logger.info("test parseCallStack"); - t.equal(events[0].functionName, "test function name"); - t.equal(events[0].fileName, "test file name"); + logger.info('test parseCallStack'); + t.equal(events[0].functionName, 'test function name'); + t.equal(events[0].fileName, 'test file name'); t.equal(events[0].lineNumber, 15); t.equal(events[0].columnNumber, 25); - t.equal(events[0].callStack, "test callstack"); + t.equal(events[0].callStack, 'test callstack'); t.end(); }); - batch.test("creating/cloning of category", t => { - const defaultLogger = new Logger("default"); - defaultLogger.level = "trace"; + batch.test('creating/cloning of category', (t) => { + const defaultLogger = new Logger('default'); + defaultLogger.level = 'trace'; defaultLogger.useCallStack = true; - t.test("category should be cloned from parent/default if does not exist", assert => { - const originalLength = categories.size; - - const logger = new Logger("cheese1"); - assert.equal(categories.size, originalLength + 1, "category should be cloned"); - assert.equal(logger.level, levels.TRACE, "should inherit level=TRACE from default-category"); - assert.equal(logger.useCallStack, true, "should inherit useCallStack=true from default-category"); - assert.end(); - }); - - t.test("changing level should not impact default-category or useCallStack", assert => { - const logger = new Logger("cheese2"); - logger.level = "debug"; - assert.equal(logger.level, levels.DEBUG, "should be changed to level=DEBUG"); - assert.equal(defaultLogger.level, levels.TRACE, "default-category should remain as level=TRACE"); - assert.equal(logger.useCallStack, true, "should remain as useCallStack=true"); - assert.equal(defaultLogger.useCallStack, true, "default-category should remain as useCallStack=true"); - assert.end(); - }); - - t.test("changing useCallStack should not impact default-category or level", assert => { - const logger = new Logger("cheese3"); - logger.useCallStack = false; - assert.equal(logger.useCallStack, false, "should be changed to useCallStack=false"); - assert.equal(defaultLogger.useCallStack, true, "default-category should remain as useCallStack=true"); - assert.equal(logger.level, levels.TRACE, "should remain as level=TRACE"); - assert.equal(defaultLogger.level, levels.TRACE, "default-category should remain as level=TRACE"); - assert.end(); - }); + t.test( + 'category should be cloned from parent/default if does not exist', + (assert) => { + const originalLength = categories.size; + + const logger = new Logger('cheese1'); + assert.equal( + categories.size, + originalLength + 1, + 'category should be cloned' + ); + assert.equal( + logger.level, + levels.TRACE, + 'should inherit level=TRACE from default-category' + ); + assert.equal( + logger.useCallStack, + true, + 'should inherit useCallStack=true from default-category' + ); + assert.end(); + } + ); + + t.test( + 'changing level should not impact default-category or useCallStack', + (assert) => { + const logger = new Logger('cheese2'); + logger.level = 'debug'; + assert.equal( + logger.level, + levels.DEBUG, + 'should be changed to level=DEBUG' + ); + assert.equal( + defaultLogger.level, + levels.TRACE, + 'default-category should remain as level=TRACE' + ); + assert.equal( + logger.useCallStack, + true, + 'should remain as useCallStack=true' + ); + assert.equal( + defaultLogger.useCallStack, + true, + 'default-category should remain as useCallStack=true' + ); + assert.end(); + } + ); + + t.test( + 'changing useCallStack should not impact default-category or level', + (assert) => { + const logger = new Logger('cheese3'); + logger.useCallStack = false; + assert.equal( + logger.useCallStack, + false, + 'should be changed to useCallStack=false' + ); + assert.equal( + defaultLogger.useCallStack, + true, + 'default-category should remain as useCallStack=true' + ); + assert.equal( + logger.level, + levels.TRACE, + 'should remain as level=TRACE' + ); + assert.equal( + defaultLogger.level, + levels.TRACE, + 'default-category should remain as level=TRACE' + ); + assert.end(); + } + ); t.end(); }); diff --git a/test/tap/logging-test.js b/test/tap/logging-test.js index 9cfdab8b..4461d14f 100644 --- a/test/tap/logging-test.js +++ b/test/tap/logging-test.js @@ -1,148 +1,151 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); -const util = require("util"); -const recording = require("../../lib/appenders/recording"); - -test("log4js", batch => { - batch.test("shutdown should return appenders and categories back to initial state", t => { - const stringifyMap = (map) => JSON.stringify(Array.from(map)); - const deepCopyMap = (map) => new Map(JSON.parse(stringifyMap(map))); - - const log4js = require("../../lib/log4js"); - - const appenders = require("../../lib/appenders"); - const categories = require("../../lib/categories"); - const initialAppenders = deepCopyMap(appenders); - const initialCategories = deepCopyMap(categories); - - log4js.configure({ - appenders: { recorder: { type: "recording" } }, - categories: { default: { appenders: ["recorder"], level: "DEBUG" } } - }); - - const configuredAppenders = deepCopyMap(appenders); - const configuredCategories = deepCopyMap(categories); - t.not( - stringifyMap(configuredAppenders), - stringifyMap(initialAppenders), - "appenders should be different from initial state" - ); - t.not( - stringifyMap(configuredCategories), - stringifyMap(initialCategories), - "categories should be different from initial state" - ); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); +const util = require('util'); +const recording = require('../../lib/appenders/recording'); + +test('log4js', (batch) => { + batch.test( + 'shutdown should return appenders and categories back to initial state', + (t) => { + const stringifyMap = (map) => JSON.stringify(Array.from(map)); + const deepCopyMap = (map) => new Map(JSON.parse(stringifyMap(map))); + + const log4js = require('../../lib/log4js'); + + const appenders = require('../../lib/appenders'); + const categories = require('../../lib/categories'); + const initialAppenders = deepCopyMap(appenders); + const initialCategories = deepCopyMap(categories); + + log4js.configure({ + appenders: { recorder: { type: 'recording' } }, + categories: { default: { appenders: ['recorder'], level: 'DEBUG' } }, + }); - log4js.shutdown(() => { - const finalAppenders = deepCopyMap(appenders); - const finalCategories = deepCopyMap(categories); - t.equal( - stringifyMap(finalAppenders), - stringifyMap(initialAppenders), - "appenders should revert back to initial state" + const configuredAppenders = deepCopyMap(appenders); + const configuredCategories = deepCopyMap(categories); + t.not( + stringifyMap(configuredAppenders), + stringifyMap(initialAppenders), + 'appenders should be different from initial state' ); - t.equal( - stringifyMap(finalCategories), - stringifyMap(initialCategories), - "categories should revert back to initial state" + t.not( + stringifyMap(configuredCategories), + stringifyMap(initialCategories), + 'categories should be different from initial state' ); - t.end(); - }); - }); - batch.test("getLogger", t => { - const log4js = require("../../lib/log4js"); + log4js.shutdown(() => { + const finalAppenders = deepCopyMap(appenders); + const finalCategories = deepCopyMap(categories); + t.equal( + stringifyMap(finalAppenders), + stringifyMap(initialAppenders), + 'appenders should revert back to initial state' + ); + t.equal( + stringifyMap(finalCategories), + stringifyMap(initialCategories), + 'categories should revert back to initial state' + ); + t.end(); + }); + } + ); + + batch.test('getLogger', (t) => { + const log4js = require('../../lib/log4js'); log4js.configure({ - appenders: { recorder: { type: "recording" } }, - categories: { default: { appenders: ["recorder"], level: "DEBUG" } } + appenders: { recorder: { type: 'recording' } }, + categories: { default: { appenders: ['recorder'], level: 'DEBUG' } }, }); - const logger = log4js.getLogger("tests"); - - t.test("should take a category and return a logger", assert => { - assert.equal(logger.category, "tests"); - assert.equal(logger.level.toString(), "DEBUG"); - assert.type(logger.debug, "function"); - assert.type(logger.info, "function"); - assert.type(logger.warn, "function"); - assert.type(logger.error, "function"); - assert.type(logger.fatal, "function"); + const logger = log4js.getLogger('tests'); + + t.test('should take a category and return a logger', (assert) => { + assert.equal(logger.category, 'tests'); + assert.equal(logger.level.toString(), 'DEBUG'); + assert.type(logger.debug, 'function'); + assert.type(logger.info, 'function'); + assert.type(logger.warn, 'function'); + assert.type(logger.error, 'function'); + assert.type(logger.fatal, 'function'); assert.end(); }); - t.test("log events", assert => { + t.test('log events', (assert) => { recording.reset(); - logger.debug("Debug event"); - logger.trace("Trace event 1"); - logger.trace("Trace event 2"); - logger.warn("Warning event"); - logger.error("Aargh!", new Error("Pants are on fire!")); - logger.error("Simulated CouchDB problem", { + logger.debug('Debug event'); + logger.trace('Trace event 1'); + logger.trace('Trace event 2'); + logger.warn('Warning event'); + logger.error('Aargh!', new Error('Pants are on fire!')); + logger.error('Simulated CouchDB problem', { err: 127, - cause: "incendiary underwear" + cause: 'incendiary underwear', }); const events = recording.replay(); - assert.equal(events[0].level.toString(), "DEBUG"); - assert.equal(events[0].data[0], "Debug event"); - assert.type(events[0].startTime, "Date"); + assert.equal(events[0].level.toString(), 'DEBUG'); + assert.equal(events[0].data[0], 'Debug event'); + assert.type(events[0].startTime, 'Date'); - assert.equal(events.length, 4, "should not emit events of a lower level"); - assert.equal(events[1].level.toString(), "WARN"); + assert.equal(events.length, 4, 'should not emit events of a lower level'); + assert.equal(events[1].level.toString(), 'WARN'); assert.type( events[2].data[1], - "Error", - "should include the error if passed in" + 'Error', + 'should include the error if passed in' ); - assert.equal(events[2].data[1].message, "Pants are on fire!"); + assert.equal(events[2].data[1].message, 'Pants are on fire!'); assert.end(); }); t.end(); }); - batch.test("when shutdown is called", t => { + batch.test('when shutdown is called', (t) => { const events = { - shutdownCalled: [] + shutdownCalled: [], }; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - "./appenders/file": { - name: "file", + './appenders/file': { + name: 'file', configure() { function thing(evt) { events.event = evt; return null; } - thing.shutdown = function(cb) { + thing.shutdown = function (cb) { events.shutdownCalled.push(true); cb(); }; return thing; - } - } - } + }, + }, + }, }); const config = { appenders: { file: { - type: "file", - filename: "cheesy-wotsits.log", + type: 'file', + filename: 'cheesy-wotsits.log', maxLogSize: 1024, - backups: 3 + backups: 3, }, alsoFile: { - type: "file" - } + type: 'file', + }, }, categories: { - default: { appenders: ["file", "alsoFile"], level: "DEBUG" } - } + default: { appenders: ['file', 'alsoFile'], level: 'DEBUG' }, + }, }; log4js.configure(config); @@ -151,21 +154,23 @@ test("log4js", batch => { t.equal( events.shutdownCalled.length, 2, - "should invoke appender shutdowns" + 'should invoke appender shutdowns' ); - logger.info("this should not go to the appenders"); - logger.log("info", "this should not go to the appenders"); - logger._log(require("../../lib/levels").INFO, ["this should not go to the appenders"]); + logger.info('this should not go to the appenders'); + logger.log('info', 'this should not go to the appenders'); + logger._log(require('../../lib/levels').INFO, [ + 'this should not go to the appenders', + ]); t.notOk(events.event); t.end(); }); }); - batch.test("configuration when passed as filename", t => { + batch.test('configuration when passed as filename', (t) => { let appenderConfig; let configFilename; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { ignoreMissing: true, requires: { fs: { @@ -177,66 +182,66 @@ test("log4js", batch => { return JSON.stringify({ appenders: { file: { - type: "file", - filename: "whatever.log" - } + type: 'file', + filename: 'whatever.log', + }, }, - categories: { default: { appenders: ["file"], level: "DEBUG" } } + categories: { default: { appenders: ['file'], level: 'DEBUG' } }, }); }, readdirSync() { - return ["file"]; - } + return ['file']; + }, }, - "./file": { + './file': { configure(configuration) { appenderConfig = configuration; - return function() {}; - } - } - } + return function () {}; + }, + }, + }, }); - log4js.configure("/path/to/cheese.json"); + log4js.configure('/path/to/cheese.json'); t.equal( configFilename, - "/path/to/cheese.json", - "should read the config from a file" + '/path/to/cheese.json', + 'should read the config from a file' ); t.equal( appenderConfig.filename, - "whatever.log", - "should pass config to appender" + 'whatever.log', + 'should pass config to appender' ); t.end(); }); - batch.test("with configure not called", t => { + batch.test('with configure not called', (t) => { const fakeStdoutAppender = { configure() { this.required = true; - return function(evt) { + return function (evt) { fakeStdoutAppender.evt = evt; }; - } + }, }; - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - "./appenders/stdout": fakeStdoutAppender - } + './appenders/stdout': fakeStdoutAppender, + }, }); - const logger = log4js.getLogger("some-logger"); - logger.debug("This is a test"); - t.ok(fakeStdoutAppender.required, "stdout should be required"); - t.notOk(fakeStdoutAppender.evt, "should not log anything"); + const logger = log4js.getLogger('some-logger'); + logger.debug('This is a test'); + t.ok(fakeStdoutAppender.required, 'stdout should be required'); + t.notOk(fakeStdoutAppender.evt, 'should not log anything'); t.end(); }); - batch.test("with configure called with empty values", t => { - [null, undefined, "", " ", []].forEach(config => { - const log4js = require("../../lib/log4js"); + batch.test('with configure called with empty values', (t) => { + [null, undefined, '', ' ', []].forEach((config) => { + const log4js = require('../../lib/log4js'); const expectedError = `Problem reading config from file "${util.inspect( config )}". Error was ENOENT: no such file or directory`; @@ -246,22 +251,22 @@ test("log4js", batch => { t.end(); }); - batch.test("configuration persistence", t => { - const firstLog4js = require("../../lib/log4js"); + batch.test('configuration persistence', (t) => { + const firstLog4js = require('../../lib/log4js'); firstLog4js.configure({ - appenders: { recorder: { type: "recording" } }, - categories: { default: { appenders: ["recorder"], level: "DEBUG" } } + appenders: { recorder: { type: 'recording' } }, + categories: { default: { appenders: ['recorder'], level: 'DEBUG' } }, }); recording.reset(); - const secondLog4js = require("../../lib/log4js"); + const secondLog4js = require('../../lib/log4js'); secondLog4js .getLogger() - .info("This should go to the appender defined in firstLog4js"); + .info('This should go to the appender defined in firstLog4js'); t.equal( recording.replay()[0].data[0], - "This should go to the appender defined in firstLog4js" + 'This should go to the appender defined in firstLog4js' ); t.end(); }); diff --git a/test/tap/multi-file-appender-test.js b/test/tap/multi-file-appender-test.js index 3becca37..937ccda0 100644 --- a/test/tap/multi-file-appender-test.js +++ b/test/tap/multi-file-appender-test.js @@ -1,83 +1,82 @@ -const process = require("process"); -const { test } = require("tap"); -const debug = require("debug"); -const fs = require("fs"); -const sandbox = require("@log4js-node/sandboxed-module"); -const log4js = require("../../lib/log4js"); +const process = require('process'); +const { test } = require('tap'); +const debug = require('debug'); +const fs = require('fs'); +const sandbox = require('@log4js-node/sandboxed-module'); +const log4js = require('../../lib/log4js'); -const removeFiles = async filenames => { - if (!Array.isArray(filenames)) - filenames = [filenames]; - const promises = filenames.map(filename => fs.promises.unlink(filename)); +const removeFiles = async (filenames) => { + if (!Array.isArray(filenames)) filenames = [filenames]; + const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; -test("multiFile appender", batch => { +test('multiFile appender', (batch) => { batch.test( - "should write to multiple files based on the loggingEvent property", - t => { + 'should write to multiple files based on the loggingEvent property', + (t) => { t.teardown(async () => { - await removeFiles(["logs/A.log", "logs/B.log"]); + await removeFiles(['logs/A.log', 'logs/B.log']); }); log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "categoryName", - extension: ".log" - } + type: 'multiFile', + base: 'logs/', + property: 'categoryName', + extension: '.log', + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerA = log4js.getLogger("A"); - const loggerB = log4js.getLogger("B"); - loggerA.info("I am in logger A"); - loggerB.info("I am in logger B"); + const loggerA = log4js.getLogger('A'); + const loggerB = log4js.getLogger('B'); + loggerA.info('I am in logger A'); + loggerB.info('I am in logger B'); log4js.shutdown(() => { - t.match(fs.readFileSync("logs/A.log", "utf-8"), "I am in logger A"); - t.match(fs.readFileSync("logs/B.log", "utf-8"), "I am in logger B"); + t.match(fs.readFileSync('logs/A.log', 'utf-8'), 'I am in logger A'); + t.match(fs.readFileSync('logs/B.log', 'utf-8'), 'I am in logger B'); t.end(); }); } ); batch.test( - "should write to multiple files based on loggingEvent.context properties", - t => { + 'should write to multiple files based on loggingEvent.context properties', + (t) => { t.teardown(async () => { - await removeFiles(["logs/C.log", "logs/D.log"]); + await removeFiles(['logs/C.log', 'logs/D.log']); }); log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log" - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerC = log4js.getLogger("cheese"); - const loggerD = log4js.getLogger("biscuits"); - loggerC.addContext("label", "C"); - loggerD.addContext("label", "D"); - loggerC.info("I am in logger C"); - loggerD.info("I am in logger D"); + const loggerC = log4js.getLogger('cheese'); + const loggerD = log4js.getLogger('biscuits'); + loggerC.addContext('label', 'C'); + loggerD.addContext('label', 'D'); + loggerC.info('I am in logger C'); + loggerD.info('I am in logger D'); log4js.shutdown(() => { - t.match(fs.readFileSync("logs/C.log", "utf-8"), "I am in logger C"); - t.match(fs.readFileSync("logs/D.log", "utf-8"), "I am in logger D"); + t.match(fs.readFileSync('logs/C.log', 'utf-8'), 'I am in logger C'); + t.match(fs.readFileSync('logs/D.log', 'utf-8'), 'I am in logger D'); t.end(); }); } ); - batch.test("should close file after timeout", t => { + batch.test('should close file after timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ - const debugWasEnabled = debug.enabled("log4js:multiFile"); + const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -90,8 +89,10 @@ test("multiFile appender", batch => { debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); - await removeFiles("logs/C.log"); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); + await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); @@ -100,52 +101,55 @@ test("multiFile appender", batch => { log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log", - timeout: timeoutMs - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + timeout: timeoutMs, + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerC = log4js.getLogger("cheese"); - loggerC.addContext("label", "C"); - loggerC.info("I am in logger C"); + const loggerC = log4js.getLogger('cheese'); + loggerC.addContext('label', 'C'); + loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `C not used for > ${timeoutMs} ms => close`, - "(timeout1) should have closed" + '(timeout1) should have closed' ); t.end(); - }, timeoutMs*1 + 50); // add a 50 ms delay + }, timeoutMs * 1 + 50); // add a 50 ms delay }); - batch.test("should close file safely after timeout", t => { - const error = new Error("fileAppender shutdown error"); - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + batch.test('should close file safely after timeout', (t) => { + const error = new Error('fileAppender shutdown error'); + const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { - "./appenders/file": { + './appenders/file': { configure(config, layouts) { - const fileAppender = require("../../lib/appenders/file").configure(config, layouts); + const fileAppender = require('../../lib/appenders/file').configure( + config, + layouts + ); const originalShutdown = fileAppender.shutdown; fileAppender.shutdown = function (complete) { - const onCallback = function() { + const onCallback = function () { complete(error); }; originalShutdown(onCallback); }; return fileAppender; - } + }, }, - debug - } + debug, + }, }); /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ - const debugWasEnabled = debug.enabled("log4js:multiFile"); + const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -158,8 +162,10 @@ test("multiFile appender", batch => { debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { - await new Promise(resolve => { sandboxedLog4js.shutdown(resolve); }); - await removeFiles("logs/C.log"); + await new Promise((resolve) => { + sandboxedLog4js.shutdown(resolve); + }); + await removeFiles('logs/C.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); @@ -168,38 +174,38 @@ test("multiFile appender", batch => { sandboxedLog4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log", - timeout: timeoutMs - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + timeout: timeoutMs, + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerC = sandboxedLog4js.getLogger("cheese"); - loggerC.addContext("label", "C"); - loggerC.info("I am in logger C"); + const loggerC = sandboxedLog4js.getLogger('cheese'); + loggerC.addContext('label', 'C'); + loggerC.info('I am in logger C'); setTimeout(() => { t.match( debugLogs[debugLogs.length - 2], `C not used for > ${timeoutMs} ms => close`, - "(timeout1) should have closed" + '(timeout1) should have closed' ); t.match( debugLogs[debugLogs.length - 1], `ignore error on file shutdown: ${error.message}`, - "safely shutdown" + 'safely shutdown' ); t.end(); - }, timeoutMs*1 + 50); // add a 50 ms delay + }, timeoutMs * 1 + 50); // add a 50 ms delay }); - batch.test("should close file after extended timeout", t => { + batch.test('should close file after extended timeout', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ - const debugWasEnabled = debug.enabled("log4js:multiFile"); + const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -212,8 +218,10 @@ test("multiFile appender", batch => { debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { - await new Promise(resolve => { log4js.shutdown(resolve); }); - await removeFiles("logs/D.log"); + await new Promise((resolve) => { + log4js.shutdown(resolve); + }); + await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); @@ -222,47 +230,49 @@ test("multiFile appender", batch => { log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log", - timeout: timeoutMs - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + timeout: timeoutMs, + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerD = log4js.getLogger("cheese"); - loggerD.addContext("label", "D"); - loggerD.info("I am in logger D"); + const loggerD = log4js.getLogger('cheese'); + loggerD.addContext('label', 'D'); + loggerD.info('I am in logger D'); setTimeout(() => { - loggerD.info("extending activity!"); + loggerD.info('extending activity!'); t.match( debugLogs[debugLogs.length - 1], - "D extending activity", - "should have extended" + 'D extending activity', + 'should have extended' ); - }, timeoutMs/2); + }, timeoutMs / 2); setTimeout(() => { t.notOk( - debugLogs.some(s => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1), - "(timeout1) should not have closed" + debugLogs.some( + (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 + ), + '(timeout1) should not have closed' ); - }, timeoutMs*1 + 50); // add a 50 ms delay + }, timeoutMs * 1 + 50); // add a 50 ms delay setTimeout(() => { t.match( debugLogs[debugLogs.length - 1], `D not used for > ${timeoutMs} ms => close`, - "(timeout2) should have closed" + '(timeout2) should have closed' ); t.end(); - }, timeoutMs*2 + 50); // add a 50 ms delay + }, timeoutMs * 2 + 50); // add a 50 ms delay }); - batch.test("should clear interval for active timers on shutdown", t => { + batch.test('should clear interval for active timers on shutdown', (t) => { /* checking that the file is closed after a timeout is done by looking at the debug logs since detecting file locks with node.js is platform specific. */ - const debugWasEnabled = debug.enabled("log4js:multiFile"); + const debugWasEnabled = debug.enabled('log4js:multiFile'); const debugLogs = []; const originalWrite = process.stderr.write; process.stderr.write = (string, encoding, fd) => { @@ -275,7 +285,7 @@ test("multiFile appender", batch => { debug.enable(`${originalNamespace}, log4js:multiFile`); t.teardown(async () => { - await removeFiles("logs/D.log"); + await removeFiles('logs/D.log'); process.stderr.write = originalWrite; debug.enable(originalNamespace); }); @@ -284,160 +294,162 @@ test("multiFile appender", batch => { log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log", - timeout: timeoutMs - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + timeout: timeoutMs, + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); - const loggerD = log4js.getLogger("cheese"); - loggerD.addContext("label", "D"); - loggerD.info("I am in logger D"); + const loggerD = log4js.getLogger('cheese'); + loggerD.addContext('label', 'D'); + loggerD.info('I am in logger D'); log4js.shutdown(() => { t.notOk( - debugLogs.some(s => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1), - "should not have closed" + debugLogs.some( + (s) => s.indexOf(`D not used for > ${timeoutMs} ms => close`) !== -1 + ), + 'should not have closed' ); t.ok( - debugLogs.some(s => s.indexOf("clearing timer for D") !== -1), - "should have cleared timers" + debugLogs.some((s) => s.indexOf('clearing timer for D') !== -1), + 'should have cleared timers' ); t.match( debugLogs[debugLogs.length - 1], - "calling shutdown for D", - "should have called shutdown" + 'calling shutdown for D', + 'should have called shutdown' ); t.end(); }); }); batch.test( - "should fail silently if loggingEvent property has no value", - t => { + 'should fail silently if loggingEvent property has no value', + (t) => { t.teardown(async () => { - await removeFiles("logs/E.log"); + await removeFiles('logs/E.log'); }); log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log" - } + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerE = log4js.getLogger(); - loggerE.addContext("label", "E"); - loggerE.info("I am in logger E"); - loggerE.removeContext("label"); - loggerE.info("I am not in logger E"); - loggerE.addContext("label", null); - loggerE.info("I am also not in logger E"); + loggerE.addContext('label', 'E'); + loggerE.info('I am in logger E'); + loggerE.removeContext('label'); + loggerE.info('I am not in logger E'); + loggerE.addContext('label', null); + loggerE.info('I am also not in logger E'); log4js.shutdown(() => { - const contents = fs.readFileSync("logs/E.log", "utf-8"); - t.match(contents, "I am in logger E"); - t.notMatch(contents, "I am not in logger E"); - t.notMatch(contents, "I am also not in logger E"); + const contents = fs.readFileSync('logs/E.log', 'utf-8'); + t.match(contents, 'I am in logger E'); + t.notMatch(contents, 'I am not in logger E'); + t.notMatch(contents, 'I am also not in logger E'); t.end(); }); } ); - batch.test("should pass options to rolling file stream", t => { + batch.test('should pass options to rolling file stream', (t) => { t.teardown(async () => { - await removeFiles(["logs/F.log", "logs/F.log.1", "logs/F.log.2"]); + await removeFiles(['logs/F.log', 'logs/F.log.1', 'logs/F.log.2']); }); log4js.configure({ appenders: { multi: { - type: "multiFile", - base: "logs/", - property: "label", - extension: ".log", + type: 'multiFile', + base: 'logs/', + property: 'label', + extension: '.log', maxLogSize: 30, backups: 2, - layout: { type: "messagePassThrough" } - } + layout: { type: 'messagePassThrough' }, + }, }, - categories: { default: { appenders: ["multi"], level: "info" } } + categories: { default: { appenders: ['multi'], level: 'info' } }, }); const loggerF = log4js.getLogger(); - loggerF.addContext("label", "F"); - loggerF.info("Being in logger F is the best."); - loggerF.info("I am also in logger F, awesome"); - loggerF.info("I am in logger F"); + loggerF.addContext('label', 'F'); + loggerF.info('Being in logger F is the best.'); + loggerF.info('I am also in logger F, awesome'); + loggerF.info('I am in logger F'); log4js.shutdown(() => { - let contents = fs.readFileSync("logs/F.log", "utf-8"); - t.match(contents, "I am in logger F"); - contents = fs.readFileSync("logs/F.log.1", "utf-8"); - t.match(contents, "I am also in logger F"); - contents = fs.readFileSync("logs/F.log.2", "utf-8"); - t.match(contents, "Being in logger F is the best"); + let contents = fs.readFileSync('logs/F.log', 'utf-8'); + t.match(contents, 'I am in logger F'); + contents = fs.readFileSync('logs/F.log.1', 'utf-8'); + t.match(contents, 'I am also in logger F'); + contents = fs.readFileSync('logs/F.log.2', 'utf-8'); + t.match(contents, 'Being in logger F is the best'); t.end(); }); }); - batch.test("should inherit config from category hierarchy", t => { + batch.test('should inherit config from category hierarchy', (t) => { t.teardown(async () => { - await removeFiles("logs/test.someTest.log"); + await removeFiles('logs/test.someTest.log'); }); log4js.configure({ appenders: { - out: { type: "stdout" }, + out: { type: 'stdout' }, test: { - type: "multiFile", - base: "logs/", - property: "categoryName", - extension: ".log" - } + type: 'multiFile', + base: 'logs/', + property: 'categoryName', + extension: '.log', + }, }, categories: { - default: { appenders: ["out"], level: "info" }, - test: { appenders: ["test"], level: "debug" } - } + default: { appenders: ['out'], level: 'info' }, + test: { appenders: ['test'], level: 'debug' }, + }, }); - const testLogger = log4js.getLogger("test.someTest"); - testLogger.debug("This should go to the file"); + const testLogger = log4js.getLogger('test.someTest'); + testLogger.debug('This should go to the file'); log4js.shutdown(() => { - const contents = fs.readFileSync("logs/test.someTest.log", "utf-8"); - t.match(contents, "This should go to the file"); + const contents = fs.readFileSync('logs/test.someTest.log', 'utf-8'); + t.match(contents, 'This should go to the file'); t.end(); }); }); - batch.test("should shutdown safely even if it is not used", t => { + batch.test('should shutdown safely even if it is not used', (t) => { log4js.configure({ appenders: { - out: { type: "stdout" }, + out: { type: 'stdout' }, test: { - type: "multiFile", - base: "logs/", - property: "categoryName", - extension: ".log" - } + type: 'multiFile', + base: 'logs/', + property: 'categoryName', + extension: '.log', + }, }, categories: { - default: { appenders: ["out"], level: "info" }, - test: { appenders: ["test"], level: "debug" } - } + default: { appenders: ['out'], level: 'info' }, + test: { appenders: ['test'], level: 'debug' }, + }, }); log4js.shutdown(() => { - t.ok("callback is called"); + t.ok('callback is called'); t.end(); }); }); batch.teardown(async () => { try { - const files = fs.readdirSync("logs"); - await removeFiles(files.map(filename => `logs/${filename}`)); - fs.rmdirSync("logs"); + const files = fs.readdirSync('logs'); + await removeFiles(files.map((filename) => `logs/${filename}`)); + fs.rmdirSync('logs'); } catch (e) { // doesn't matter } diff --git a/test/tap/multiprocess-shutdown-test.js b/test/tap/multiprocess-shutdown-test.js index 8395d0be..e46fede7 100644 --- a/test/tap/multiprocess-shutdown-test.js +++ b/test/tap/multiprocess-shutdown-test.js @@ -1,21 +1,21 @@ -const { test } = require("tap"); -const net = require("net"); -const childProcess = require("child_process"); -const sandbox = require("@log4js-node/sandboxed-module"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const net = require('net'); +const childProcess = require('child_process'); +const sandbox = require('@log4js-node/sandboxed-module'); +const log4js = require('../../lib/log4js'); -test("multiprocess appender shutdown (master)", { timeout: 5000 }, t => { +test('multiprocess appender shutdown (master)', { timeout: 5000 }, (t) => { log4js.configure({ appenders: { - stdout: { type: "stdout" }, + stdout: { type: 'stdout' }, multi: { - type: "multiprocess", - mode: "master", + type: 'multiprocess', + mode: 'master', loggerPort: 12345, - appender: "stdout" - } + appender: 'stdout', + }, }, - categories: { default: { appenders: ["multi"], level: "debug" } } + categories: { default: { appenders: ['multi'], level: 'debug' } }, }); setTimeout(() => { @@ -23,11 +23,11 @@ test("multiprocess appender shutdown (master)", { timeout: 5000 }, t => { setTimeout(() => { net .connect({ port: 12345 }, () => { - t.fail("connection should not still work"); + t.fail('connection should not still work'); t.end(); }) - .on("error", err => { - t.ok(err, "we got a connection error"); + .on('error', (err) => { + t.ok(err, 'we got a connection error'); t.end(); }); }, 1000); @@ -35,7 +35,7 @@ test("multiprocess appender shutdown (master)", { timeout: 5000 }, t => { }, 1000); }); -test("multiprocess appender shutdown (worker)", t => { +test('multiprocess appender shutdown (worker)', (t) => { const fakeConnection = { evts: {}, msgs: [], @@ -50,26 +50,26 @@ test("multiprocess appender shutdown (worker)", t => { }, end(cb) { this.endCb = cb; - } + }, }; - const logLib = sandbox.require("../../lib/log4js", { + const logLib = sandbox.require('../../lib/log4js', { requires: { net: { createConnection() { return fakeConnection; - } - } - } + }, + }, + }, }); logLib.configure({ - appenders: { worker: { type: "multiprocess", mode: "worker" } }, - categories: { default: { appenders: ["worker"], level: "debug" } } + appenders: { worker: { type: 'multiprocess', mode: 'worker' } }, + categories: { default: { appenders: ['worker'], level: 'debug' } }, }); logLib .getLogger() .info( - "Putting something in the buffer before the connection is established" + 'Putting something in the buffer before the connection is established' ); // nothing been written yet. t.equal(fakeConnection.msgs.length, 0); @@ -94,32 +94,32 @@ test("multiprocess appender shutdown (worker)", t => { }, 500); }); -test("multiprocess appender crash (worker)", t => { +test('multiprocess appender crash (worker)', (t) => { const loggerPort = 12346; - const vcr = require("../../lib/appenders/recording"); + const vcr = require('../../lib/appenders/recording'); log4js.configure({ appenders: { - console: { type: "recording" }, + console: { type: 'recording' }, multi: { - type: "multiprocess", - mode: "master", + type: 'multiprocess', + mode: 'master', loggerPort, - appender: "console" - } + appender: 'console', + }, }, - categories: { default: { appenders: ["multi"], level: "debug" } } + categories: { default: { appenders: ['multi'], level: 'debug' } }, }); - const worker = childProcess.fork(require.resolve("../multiprocess-worker"), [ - "start-multiprocess-worker", - loggerPort + const worker = childProcess.fork(require.resolve('../multiprocess-worker'), [ + 'start-multiprocess-worker', + loggerPort, ]); - worker.on("message", m => { - if (m === "worker is done") { + worker.on('message', (m) => { + if (m === 'worker is done') { setTimeout(() => { worker.kill(); - t.equal(vcr.replay()[0].data[0], "Logging from worker"); + t.equal(vcr.replay()[0].data[0], 'Logging from worker'); log4js.shutdown(() => t.end()); }, 100); } diff --git a/test/tap/multiprocess-test.js b/test/tap/multiprocess-test.js index 4e615213..b67aa555 100644 --- a/test/tap/multiprocess-test.js +++ b/test/tap/multiprocess-test.js @@ -1,8 +1,8 @@ -const childProcess = require("child_process"); -const { test } = require("tap"); -const flatted = require("flatted"); -const sandbox = require("@log4js-node/sandboxed-module"); -const recording = require("../../lib/appenders/recording"); +const childProcess = require('child_process'); +const { test } = require('tap'); +const flatted = require('flatted'); +const sandbox = require('@log4js-node/sandboxed-module'); +const recording = require('../../lib/appenders/recording'); function makeFakeNet() { return { @@ -24,104 +24,107 @@ function makeFakeNet() { }, end() { fakeNet.closeCalled = true; - } + }, }; }, createServer(cb) { const fakeNet = this; cb({ - remoteAddress: "1.2.3.4", - remotePort: "1234", + remoteAddress: '1.2.3.4', + remotePort: '1234', setEncoding(encoding) { fakeNet.encoding = encoding; }, on(event, cb2) { fakeNet.cbs[event] = cb2; - } + }, }); return { listen(port, host) { fakeNet.port = port; fakeNet.host = host; - } + }, }; - } + }, }; } -test("Multiprocess Appender", async batch => { +test('Multiprocess Appender', async (batch) => { batch.beforeEach(() => { recording.erase(); }); - batch.test("worker", t => { + batch.test('worker', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); log4js.configure({ appenders: { worker: { - type: "multiprocess", - mode: "worker", + type: 'multiprocess', + mode: 'worker', loggerPort: 1234, - loggerHost: "pants" - } + loggerHost: 'pants', + }, }, - categories: { default: { appenders: ["worker"], level: "trace" } } + categories: { default: { appenders: ['worker'], level: 'trace' } }, }); const logger = log4js.getLogger(); - logger.info("before connect"); + logger.info('before connect'); fakeNet.cbs.connect(); - logger.info("after connect"); + logger.info('after connect'); fakeNet.cbs.close(); - logger.info("after error, before connect"); + logger.info('after error, before connect'); fakeNet.cbs.connect(); - logger.info("after error, after connect"); - logger.error(new Error("Error test")); + logger.info('after error, after connect'); + logger.error(new Error('Error test')); const net = fakeNet; - t.test("should open a socket to the loggerPort and loggerHost", assert => { - assert.equal(net.port, 1234); - assert.equal(net.host, "pants"); - assert.end(); - }); + t.test( + 'should open a socket to the loggerPort and loggerHost', + (assert) => { + assert.equal(net.port, 1234); + assert.equal(net.host, 'pants'); + assert.end(); + } + ); t.test( - "should buffer messages written before socket is connected", - assert => { - assert.match(net.data[0], "before connect"); + 'should buffer messages written before socket is connected', + (assert) => { + assert.match(net.data[0], 'before connect'); assert.end(); } ); t.test( - "should write log messages to socket as flatted strings with a terminator string", - assert => { - assert.match(net.data[0], "before connect"); - assert.equal(net.data[1], "__LOG4JS__"); - assert.match(net.data[2], "after connect"); - assert.equal(net.data[3], "__LOG4JS__"); - assert.equal(net.encoding, "utf8"); + 'should write log messages to socket as flatted strings with a terminator string', + (assert) => { + assert.match(net.data[0], 'before connect'); + assert.equal(net.data[1], '__LOG4JS__'); + assert.match(net.data[2], 'after connect'); + assert.equal(net.data[3], '__LOG4JS__'); + assert.equal(net.encoding, 'utf8'); assert.end(); } ); - t.test("should attempt to re-open the socket on error", assert => { - assert.match(net.data[4], "after error, before connect"); - assert.equal(net.data[5], "__LOG4JS__"); - assert.match(net.data[6], "after error, after connect"); - assert.equal(net.data[7], "__LOG4JS__"); + t.test('should attempt to re-open the socket on error', (assert) => { + assert.match(net.data[4], 'after error, before connect'); + assert.equal(net.data[5], '__LOG4JS__'); + assert.match(net.data[6], 'after error, after connect'); + assert.equal(net.data[7], '__LOG4JS__'); assert.equal(net.createConnectionCalled, 2); assert.end(); }); - t.test("should serialize an Error correctly", assert => { + t.test('should serialize an Error correctly', (assert) => { assert.ok( flatted.parse(net.data[8]).data[0].stack, `Expected:\n\n${net.data[8]}\n\n to have a 'data[0].stack' property` @@ -134,172 +137,172 @@ test("Multiprocess Appender", async batch => { t.end(); }); - batch.test("worker with timeout", t => { + batch.test('worker with timeout', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); log4js.configure({ - appenders: { worker: { type: "multiprocess", mode: "worker" } }, - categories: { default: { appenders: ["worker"], level: "trace" } } + appenders: { worker: { type: 'multiprocess', mode: 'worker' } }, + categories: { default: { appenders: ['worker'], level: 'trace' } }, }); const logger = log4js.getLogger(); - logger.info("before connect"); + logger.info('before connect'); fakeNet.cbs.connect(); - logger.info("after connect"); + logger.info('after connect'); fakeNet.cbs.timeout(); - logger.info("after timeout, before close"); + logger.info('after timeout, before close'); fakeNet.cbs.close(); - logger.info("after close, before connect"); + logger.info('after close, before connect'); fakeNet.cbs.connect(); - logger.info("after close, after connect"); + logger.info('after close, after connect'); const net = fakeNet; - t.test("should attempt to re-open the socket", assert => { + t.test('should attempt to re-open the socket', (assert) => { // skipping the __LOG4JS__ separators - assert.match(net.data[0], "before connect"); - assert.match(net.data[2], "after connect"); - assert.match(net.data[4], "after timeout, before close"); - assert.match(net.data[6], "after close, before connect"); - assert.match(net.data[8], "after close, after connect"); + assert.match(net.data[0], 'before connect'); + assert.match(net.data[2], 'after connect'); + assert.match(net.data[4], 'after timeout, before close'); + assert.match(net.data[6], 'after close, before connect'); + assert.match(net.data[8], 'after close, after connect'); assert.equal(net.createConnectionCalled, 2); assert.end(); }); t.end(); }); - batch.test("worker with error", t => { + batch.test('worker with error', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); log4js.configure({ - appenders: { worker: { type: "multiprocess", mode: "worker" } }, - categories: { default: { appenders: ["worker"], level: "trace" } } + appenders: { worker: { type: 'multiprocess', mode: 'worker' } }, + categories: { default: { appenders: ['worker'], level: 'trace' } }, }); const logger = log4js.getLogger(); - logger.info("before connect"); + logger.info('before connect'); fakeNet.cbs.connect(); - logger.info("after connect"); + logger.info('after connect'); fakeNet.cbs.error(); - logger.info("after error, before close"); + logger.info('after error, before close'); fakeNet.cbs.close(); - logger.info("after close, before connect"); + logger.info('after close, before connect'); fakeNet.cbs.connect(); - logger.info("after close, after connect"); + logger.info('after close, after connect'); const net = fakeNet; - t.test("should attempt to re-open the socket", assert => { + t.test('should attempt to re-open the socket', (assert) => { // skipping the __LOG4JS__ separators - assert.match(net.data[0], "before connect"); - assert.match(net.data[2], "after connect"); - assert.match(net.data[4], "after error, before close"); - assert.match(net.data[6], "after close, before connect"); - assert.match(net.data[8], "after close, after connect"); + assert.match(net.data[0], 'before connect'); + assert.match(net.data[2], 'after connect'); + assert.match(net.data[4], 'after error, before close'); + assert.match(net.data[6], 'after close, before connect'); + assert.match(net.data[8], 'after close, after connect'); assert.equal(net.createConnectionCalled, 2); assert.end(); }); t.end(); }); - batch.test("worker defaults", t => { + batch.test('worker defaults', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); log4js.configure({ - appenders: { worker: { type: "multiprocess", mode: "worker" } }, - categories: { default: { appenders: ["worker"], level: "trace" } } + appenders: { worker: { type: 'multiprocess', mode: 'worker' } }, + categories: { default: { appenders: ['worker'], level: 'trace' } }, }); - t.test("should open a socket to localhost:5000", assert => { + t.test('should open a socket to localhost:5000', (assert) => { assert.equal(fakeNet.port, 5000); - assert.equal(fakeNet.host, "localhost"); + assert.equal(fakeNet.host, 'localhost'); assert.end(); }); t.end(); }); - batch.test("master", t => { + batch.test('master', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { net: fakeNet, - "./appenders/recording": recording - } + './appenders/recording': recording, + }, }); log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, master: { - type: "multiprocess", - mode: "master", + type: 'multiprocess', + mode: 'master', loggerPort: 1234, - loggerHost: "server", - appender: "recorder" - } + loggerHost: 'server', + appender: 'recorder', + }, }, - categories: { default: { appenders: ["master"], level: "trace" } } + categories: { default: { appenders: ['master'], level: 'trace' } }, }); const net = fakeNet; t.test( - "should listen for log messages on loggerPort and loggerHost", - assert => { + 'should listen for log messages on loggerPort and loggerHost', + (assert) => { assert.equal(net.port, 1234); - assert.equal(net.host, "server"); + assert.equal(net.host, 'server'); assert.end(); } ); - t.test("should return the underlying appender", assert => { + t.test('should return the underlying appender', (assert) => { log4js .getLogger() - .info("this should be sent to the actual appender directly"); + .info('this should be sent to the actual appender directly'); assert.equal( recording.replay()[0].data[0], - "this should be sent to the actual appender directly" + 'this should be sent to the actual appender directly' ); assert.end(); }); - t.test('should log the error on "error" event', assert => { - net.cbs.error(new Error("Expected error")); + t.test('should log the error on "error" event', (assert) => { + net.cbs.error(new Error('Expected error')); const logEvents = recording.replay(); assert.plan(2); assert.equal(logEvents.length, 1); assert.equal( - "A worker log process hung up unexpectedly", + 'A worker log process hung up unexpectedly', logEvents[0].data[0] ); }); - t.test("when a client connects", assert => { + t.test('when a client connects', (assert) => { const logString = `${flatted.stringify({ - level: { level: 10000, levelStr: "DEBUG" }, - data: ["some debug"] + level: { level: 10000, levelStr: 'DEBUG' }, + data: ['some debug'], })}__LOG4JS__`; net.cbs.data( `${flatted.stringify({ - level: { level: 40000, levelStr: "ERROR" }, - data: ["an error message"] + level: { level: 40000, levelStr: 'ERROR' }, + data: ['an error message'], })}__LOG4JS__` ); net.cbs.data(logString.slice(0, 10)); @@ -307,103 +310,107 @@ test("Multiprocess Appender", async batch => { net.cbs.data(logString + logString + logString); net.cbs.end( `${flatted.stringify({ - level: { level: 50000, levelStr: "FATAL" }, - data: ["that's all folks"] + level: { level: 50000, levelStr: 'FATAL' }, + data: ["that's all folks"], })}__LOG4JS__` ); - net.cbs.data("bad message__LOG4JS__"); + net.cbs.data('bad message__LOG4JS__'); const logEvents = recording.replay(); // should parse log messages into log events and send to appender - assert.equal(logEvents[0].level.toString(), "ERROR"); - assert.equal(logEvents[0].data[0], "an error message"); - assert.equal(logEvents[0].remoteAddress, "1.2.3.4"); - assert.equal(logEvents[0].remotePort, "1234"); + assert.equal(logEvents[0].level.toString(), 'ERROR'); + assert.equal(logEvents[0].data[0], 'an error message'); + assert.equal(logEvents[0].remoteAddress, '1.2.3.4'); + assert.equal(logEvents[0].remotePort, '1234'); // should parse log messages split into multiple chunks' - assert.equal(logEvents[1].level.toString(), "DEBUG"); - assert.equal(logEvents[1].data[0], "some debug"); - assert.equal(logEvents[1].remoteAddress, "1.2.3.4"); - assert.equal(logEvents[1].remotePort, "1234"); + assert.equal(logEvents[1].level.toString(), 'DEBUG'); + assert.equal(logEvents[1].data[0], 'some debug'); + assert.equal(logEvents[1].remoteAddress, '1.2.3.4'); + assert.equal(logEvents[1].remotePort, '1234'); // should parse multiple log messages in a single chunk' - assert.equal(logEvents[2].data[0], "some debug"); - assert.equal(logEvents[3].data[0], "some debug"); - assert.equal(logEvents[4].data[0], "some debug"); + assert.equal(logEvents[2].data[0], 'some debug'); + assert.equal(logEvents[3].data[0], 'some debug'); + assert.equal(logEvents[4].data[0], 'some debug'); // should handle log messages sent as part of end event' assert.equal(logEvents[5].data[0], "that's all folks"); // should handle unparseable log messages - assert.equal(logEvents[6].level.toString(), "ERROR"); - assert.equal(logEvents[6].categoryName, "log4js"); - assert.equal(logEvents[6].data[0], "Unable to parse log:"); - assert.equal(logEvents[6].data[1], "bad message"); + assert.equal(logEvents[6].level.toString(), 'ERROR'); + assert.equal(logEvents[6].categoryName, 'log4js'); + assert.equal(logEvents[6].data[0], 'Unable to parse log:'); + assert.equal(logEvents[6].data[1], 'bad message'); assert.end(); }); t.end(); }); - batch.test("master without actual appender throws error", t => { + batch.test('master without actual appender throws error', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); t.throws( () => log4js.configure({ - appenders: { master: { type: "multiprocess", mode: "master" } }, - categories: { default: { appenders: ["master"], level: "trace" } } + appenders: { master: { type: 'multiprocess', mode: 'master' } }, + categories: { default: { appenders: ['master'], level: 'trace' } }, }), new Error('multiprocess master must have an "appender" defined') ); t.end(); }); - batch.test("master with unknown appender throws error", t => { + batch.test('master with unknown appender throws error', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); t.throws( () => log4js.configure({ appenders: { - master: { type: "multiprocess", mode: "master", appender: "cheese" } + master: { + type: 'multiprocess', + mode: 'master', + appender: 'cheese', + }, }, - categories: { default: { appenders: ["master"], level: "trace" } } + categories: { default: { appenders: ['master'], level: 'trace' } }, }), new Error('multiprocess master appender "cheese" not defined') ); t.end(); }); - batch.test("master defaults", t => { + batch.test('master defaults', (t) => { const fakeNet = makeFakeNet(); - const log4js = sandbox.require("../../lib/log4js", { + const log4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); log4js.configure({ appenders: { - stdout: { type: "stdout" }, - master: { type: "multiprocess", mode: "master", appender: "stdout" } + stdout: { type: 'stdout' }, + master: { type: 'multiprocess', mode: 'master', appender: 'stdout' }, }, - categories: { default: { appenders: ["master"], level: "trace" } } + categories: { default: { appenders: ['master'], level: 'trace' } }, }); - t.test("should listen for log messages on localhost:5000", assert => { + t.test('should listen for log messages on localhost:5000', (assert) => { assert.equal(fakeNet.port, 5000); - assert.equal(fakeNet.host, "localhost"); + assert.equal(fakeNet.host, 'localhost'); assert.end(); }); t.end(); @@ -418,7 +425,12 @@ test("Multiprocess Appender", async batch => { log4js.configure({ appenders: { recording: { type: 'recording' }, - master: { type: 'multiprocess', mode: 'master', appender: 'recording', loggerPort: 5001 }, + master: { + type: 'multiprocess', + mode: 'master', + appender: 'recording', + loggerPort: 5001, + }, }, categories: { default: { appenders: ['recording'], level: 'trace' } }, }); @@ -439,6 +451,5 @@ test("Multiprocess Appender", async batch => { assert.end(); }); - batch.end(); }); diff --git a/test/tap/newLevel-test.js b/test/tap/newLevel-test.js index ffae2bc0..4f581489 100644 --- a/test/tap/newLevel-test.js +++ b/test/tap/newLevel-test.js @@ -1,300 +1,310 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); -const recording = require("../../lib/appenders/recording"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); +const recording = require('../../lib/appenders/recording'); -test("../../lib/logger", batch => { +test('../../lib/logger', (batch) => { batch.beforeEach(() => { recording.reset(); }); - batch.test("creating a new log level", t => { + batch.test('creating a new log level', (t) => { log4js.configure({ levels: { - DIAG: { value: 6000, colour: "green" } + DIAG: { value: 6000, colour: 'green' }, }, appenders: { - stdout: { type: "stdout" } + stdout: { type: 'stdout' }, }, categories: { - default: { appenders: ["stdout"], level: "trace" } - } + default: { appenders: ['stdout'], level: 'trace' }, + }, }); const logger = log4js.getLogger(); - t.test("should export new log level in levels module", assert => { + t.test('should export new log level in levels module', (assert) => { assert.ok(log4js.levels.DIAG); - assert.equal(log4js.levels.DIAG.levelStr, "DIAG"); + assert.equal(log4js.levels.DIAG.levelStr, 'DIAG'); assert.equal(log4js.levels.DIAG.level, 6000); - assert.equal(log4js.levels.DIAG.colour, "green"); + assert.equal(log4js.levels.DIAG.colour, 'green'); assert.end(); }); t.type( logger.diag, - "function", - "should create named function on logger prototype" + 'function', + 'should create named function on logger prototype' ); t.type( logger.isDiagEnabled, - "function", - "should create isLevelEnabled function on logger prototype" + 'function', + 'should create isLevelEnabled function on logger prototype' ); - t.type(logger.info, "function", "should retain default levels"); + t.type(logger.info, 'function', 'should retain default levels'); t.end(); }); - batch.test("creating a new log level with underscores", t => { + batch.test('creating a new log level with underscores', (t) => { log4js.configure({ levels: { - NEW_LEVEL_OTHER: { value: 6000, colour: "blue" } + NEW_LEVEL_OTHER: { value: 6000, colour: 'blue' }, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); const logger = log4js.getLogger(); - t.test("should export new log level to levels module", assert => { + t.test('should export new log level to levels module', (assert) => { assert.ok(log4js.levels.NEW_LEVEL_OTHER); - assert.equal(log4js.levels.NEW_LEVEL_OTHER.levelStr, "NEW_LEVEL_OTHER"); + assert.equal(log4js.levels.NEW_LEVEL_OTHER.levelStr, 'NEW_LEVEL_OTHER'); assert.equal(log4js.levels.NEW_LEVEL_OTHER.level, 6000); - assert.equal(log4js.levels.NEW_LEVEL_OTHER.colour, "blue"); + assert.equal(log4js.levels.NEW_LEVEL_OTHER.colour, 'blue'); assert.end(); }); t.type( logger.newLevelOther, - "function", - "should create named function on logger prototype in camel case" + 'function', + 'should create named function on logger prototype in camel case' ); t.type( logger.isNewLevelOtherEnabled, - "function", - "should create named isLevelEnabled function on logger prototype in camel case" + 'function', + 'should create named isLevelEnabled function on logger prototype in camel case' ); t.end(); }); - batch.test("creating log events containing newly created log level", t => { + batch.test('creating log events containing newly created log level', (t) => { log4js.configure({ levels: { - LVL1: { value: 6000, colour: "grey" }, - LVL2: { value: 5000, colour: "magenta" } + LVL1: { value: 6000, colour: 'grey' }, + LVL2: { value: 5000, colour: 'magenta' }, }, - appenders: { recorder: { type: "recording" } }, + appenders: { recorder: { type: 'recording' } }, categories: { - default: { appenders: ["recorder"], level: "LVL1" } - } + default: { appenders: ['recorder'], level: 'LVL1' }, + }, }); const logger = log4js.getLogger(); - logger.log(log4js.levels.getLevel("LVL1", log4js.levels.DEBUG), "Event 1"); - logger.log(log4js.levels.getLevel("LVL1"), "Event 2"); - logger.log("LVL1", "Event 3"); - logger.lvl1("Event 4"); + logger.log(log4js.levels.getLevel('LVL1', log4js.levels.DEBUG), 'Event 1'); + logger.log(log4js.levels.getLevel('LVL1'), 'Event 2'); + logger.log('LVL1', 'Event 3'); + logger.lvl1('Event 4'); - logger.lvl2("Event 5"); + logger.lvl2('Event 5'); const events = recording.replay(); - t.test("should show log events with new log level", assert => { - assert.equal(events[0].level.toString(), "LVL1"); - assert.equal(events[0].data[0], "Event 1"); + t.test('should show log events with new log level', (assert) => { + assert.equal(events[0].level.toString(), 'LVL1'); + assert.equal(events[0].data[0], 'Event 1'); - assert.equal(events[1].level.toString(), "LVL1"); - assert.equal(events[1].data[0], "Event 2"); + assert.equal(events[1].level.toString(), 'LVL1'); + assert.equal(events[1].data[0], 'Event 2'); - assert.equal(events[2].level.toString(), "LVL1"); - assert.equal(events[2].data[0], "Event 3"); + assert.equal(events[2].level.toString(), 'LVL1'); + assert.equal(events[2].data[0], 'Event 3'); - assert.equal(events[3].level.toString(), "LVL1"); - assert.equal(events[3].data[0], "Event 4"); + assert.equal(events[3].level.toString(), 'LVL1'); + assert.equal(events[3].data[0], 'Event 4'); assert.end(); }); t.equal( events.length, 4, - "should not be present if min log level is greater than newly created level" + 'should not be present if min log level is greater than newly created level' ); t.end(); }); - batch.test("creating a new log level with incorrect parameters", t => { + batch.test('creating a new log level with incorrect parameters', (t) => { t.throws(() => { log4js.configure({ levels: { - cheese: { value: "biscuits" } + cheese: { value: 'biscuits' }, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level "cheese".value must have an integer value'); t.throws(() => { log4js.configure({ levels: { - cheese: "biscuits" + cheese: 'biscuits', }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level "cheese" must be an object'); t.throws(() => { log4js.configure({ levels: { - cheese: { thing: "biscuits" } + cheese: { thing: 'biscuits' }, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); - }, "level \"cheese\" must have a 'value' property"); + }, 'level "cheese" must have a \'value\' property'); t.throws(() => { log4js.configure({ levels: { - cheese: { value: 3 } + cheese: { value: 3 }, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); - }, "level \"cheese\" must have a 'colour' property"); + }, 'level "cheese" must have a \'colour\' property'); t.throws(() => { log4js.configure({ levels: { - cheese: { value: 3, colour: "pants" } + cheese: { value: 3, colour: 'pants' }, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level "cheese".colour must be one of white, grey, black, blue, cyan, green, magenta, red, yellow'); t.throws(() => { log4js.configure({ levels: { - "#pants": 3 + '#pants': 3, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level name "#pants" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)'); t.throws(() => { log4js.configure({ levels: { - "thing#pants": 3 + 'thing#pants': 3, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level name "thing#pants" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)'); t.throws(() => { log4js.configure({ levels: { - "1pants": 3 + '1pants': 3, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level name "1pants" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)'); t.throws(() => { log4js.configure({ levels: { - 2: 3 + 2: 3, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level name "2" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)'); t.throws(() => { log4js.configure({ levels: { - "cheese!": 3 + 'cheese!': 3, }, - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "trace" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'trace' } }, }); }, 'level name "cheese!" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)'); t.end(); }); - batch.test("calling log with an undefined log level", t => { + batch.test('calling log with an undefined log level', (t) => { log4js.configure({ - appenders: { recorder: { type: "recording" } }, - categories: { default: { appenders: ["recorder"], level: "trace" } } + appenders: { recorder: { type: 'recording' } }, + categories: { default: { appenders: ['recorder'], level: 'trace' } }, }); const logger = log4js.getLogger(); // fallback behavior - logger.log("LEVEL_DOES_NOT_EXIST", "Event 1"); - logger.log(log4js.levels.getLevel("LEVEL_DOES_NOT_EXIST"), "Event 2", "2 Text"); + logger.log('LEVEL_DOES_NOT_EXIST', 'Event 1'); + logger.log( + log4js.levels.getLevel('LEVEL_DOES_NOT_EXIST'), + 'Event 2', + '2 Text' + ); // synonym behavior - logger.log("Event 3"); - logger.log("Event 4", "4 Text"); + logger.log('Event 3'); + logger.log('Event 4', '4 Text'); const events = recording.replay(); - t.equal(events[0].level.toString(), "WARN", "should log warning"); - t.equal(events[0].data[0], "log4js:logger.log: valid log-level not found as first parameter given:"); - t.equal(events[0].data[1], "LEVEL_DOES_NOT_EXIST"); - t.equal(events[1].level.toString(), "INFO", "should fall back to INFO"); - t.equal(events[1].data[0], "[LEVEL_DOES_NOT_EXIST]"); - t.equal(events[1].data[1], "Event 1"); + t.equal(events[0].level.toString(), 'WARN', 'should log warning'); + t.equal( + events[0].data[0], + 'log4js:logger.log: valid log-level not found as first parameter given:' + ); + t.equal(events[0].data[1], 'LEVEL_DOES_NOT_EXIST'); + t.equal(events[1].level.toString(), 'INFO', 'should fall back to INFO'); + t.equal(events[1].data[0], '[LEVEL_DOES_NOT_EXIST]'); + t.equal(events[1].data[1], 'Event 1'); - t.equal(events[2].level.toString(), "WARN", "should log warning"); - t.equal(events[2].data[0], "log4js:logger.log: valid log-level not found as first parameter given:"); + t.equal(events[2].level.toString(), 'WARN', 'should log warning'); + t.equal( + events[2].data[0], + 'log4js:logger.log: valid log-level not found as first parameter given:' + ); t.equal(events[2].data[1], undefined); - t.equal(events[3].level.toString(), "INFO", "should fall back to INFO"); - t.equal(events[3].data[0], "[undefined]"); - t.equal(events[3].data[1], "Event 2"); - t.equal(events[3].data[2], "2 Text"); + t.equal(events[3].level.toString(), 'INFO', 'should fall back to INFO'); + t.equal(events[3].data[0], '[undefined]'); + t.equal(events[3].data[1], 'Event 2'); + t.equal(events[3].data[2], '2 Text'); - t.equal(events[4].level.toString(), "INFO", "LOG is synonym of INFO"); - t.equal(events[4].data[0], "Event 3"); + t.equal(events[4].level.toString(), 'INFO', 'LOG is synonym of INFO'); + t.equal(events[4].data[0], 'Event 3'); - t.equal(events[5].level.toString(), "INFO", "LOG is synonym of INFO"); - t.equal(events[5].data[0], "Event 4"); - t.equal(events[5].data[1], "4 Text"); + t.equal(events[5].level.toString(), 'INFO', 'LOG is synonym of INFO'); + t.equal(events[5].data[0], 'Event 4'); + t.equal(events[5].data[1], '4 Text'); t.end(); }); - batch.test("creating a new level with an existing level name", t => { + batch.test('creating a new level with an existing level name', (t) => { log4js.configure({ levels: { - info: { value: 1234, colour: "blue" } + info: { value: 1234, colour: 'blue' }, }, - appenders: { recorder: { type: "recording" } }, - categories: { default: { appenders: ["recorder"], level: "all" } } + appenders: { recorder: { type: 'recording' } }, + categories: { default: { appenders: ['recorder'], level: 'all' } }, }); t.equal( log4js.levels.INFO.level, 1234, - "should override the existing log level" + 'should override the existing log level' ); t.equal( log4js.levels.INFO.colour, - "blue", - "should override the existing log level" + 'blue', + 'should override the existing log level' ); const logger = log4js.getLogger(); - logger.info("test message"); + logger.info('test message'); const events = recording.replay(); t.equal( events[0].level.level, 1234, - "should override the existing log level" + 'should override the existing log level' ); t.end(); }); diff --git a/test/tap/no-cluster-test.js b/test/tap/no-cluster-test.js index 3a4c4471..65a2ea77 100644 --- a/test/tap/no-cluster-test.js +++ b/test/tap/no-cluster-test.js @@ -1,15 +1,15 @@ -const { test } = require("tap"); -const proxyquire = require("proxyquire"); +const { test } = require('tap'); +const proxyquire = require('proxyquire'); -test("clustering is disabled if cluster is not present", t => { - const log4js = proxyquire("../../lib/log4js", { cluster: null }); - const recorder = require("../../lib/appenders/recording"); +test('clustering is disabled if cluster is not present', (t) => { + const log4js = proxyquire('../../lib/log4js', { cluster: null }); + const recorder = require('../../lib/appenders/recording'); log4js.configure({ - appenders: { vcr: { type: "recording" } }, - categories: { default: { appenders: ["vcr"], level: "debug" } } + appenders: { vcr: { type: 'recording' } }, + categories: { default: { appenders: ['vcr'], level: 'debug' } }, }); - log4js.getLogger().info("it should still work"); + log4js.getLogger().info('it should still work'); const events = recorder.replay(); - t.equal(events[0].data[0], "it should still work"); + t.equal(events[0].data[0], 'it should still work'); t.end(); }); diff --git a/test/tap/noLogFilter-test.js b/test/tap/noLogFilter-test.js index 8f14ab46..d52cf485 100644 --- a/test/tap/noLogFilter-test.js +++ b/test/tap/noLogFilter-test.js @@ -1,42 +1,42 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); -const recording = require("../../lib/appenders/recording"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); +const recording = require('../../lib/appenders/recording'); /** * test a simple regexp */ -test("log4js noLogFilter", batch => { +test('log4js noLogFilter', (batch) => { batch.beforeEach(() => { recording.reset(); }); batch.test( - "appender should exclude events that match the regexp string", - t => { + 'appender should exclude events that match the regexp string', + (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: "This.*not", - appender: "recorder" - } + type: 'noLogFilter', + exclude: 'This.*not', + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("This should not get logged"); - logger.debug("This should get logged"); + logger.debug('This should not get logged'); + logger.debug('This should get logged'); logger.debug( - "Another case that not match the regex, so it should get logged" + 'Another case that not match the regex, so it should get logged' ); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "This should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); t.equal( logEvents[1].data[0], - "Another case that not match the regex, so it should get logged" + 'Another case that not match the regex, so it should get logged' ); t.end(); } @@ -46,36 +46,36 @@ test("log4js noLogFilter", batch => { * test an array of regexp */ batch.test( - "appender should exclude events that match the regexp string contained in the array", - t => { + 'appender should exclude events that match the regexp string contained in the array', + (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: ["This.*not", "instead"], - appender: "recorder" - } + type: 'noLogFilter', + exclude: ['This.*not', 'instead'], + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("This should not get logged"); - logger.debug("This should get logged"); + logger.debug('This should not get logged'); + logger.debug('This should get logged'); logger.debug( - "Another case that not match the regex, so it should get logged" + 'Another case that not match the regex, so it should get logged' ); - logger.debug("This case instead it should get logged"); - logger.debug("The last that should get logged"); + logger.debug('This case instead it should get logged'); + logger.debug('The last that should get logged'); const logEvents = recording.replay(); t.equal(logEvents.length, 3); - t.equal(logEvents[0].data[0], "This should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); t.equal( logEvents[1].data[0], - "Another case that not match the regex, so it should get logged" + 'Another case that not match the regex, so it should get logged' ); - t.equal(logEvents[2].data[0], "The last that should get logged"); + t.equal(logEvents[2].data[0], 'The last that should get logged'); t.end(); } ); @@ -83,30 +83,30 @@ test("log4js noLogFilter", batch => { * test case insentitive regexp */ batch.test( - "appender should evaluate the regexp using incase sentitive option", - t => { + 'appender should evaluate the regexp using incase sentitive option', + (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: ["NOT", "eX.*de"], - appender: "recorder" - } + type: 'noLogFilter', + exclude: ['NOT', 'eX.*de'], + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("This should not get logged"); - logger.debug("This should get logged"); - logger.debug("Exclude this string"); - logger.debug("Include this string"); + logger.debug('This should not get logged'); + logger.debug('This should get logged'); + logger.debug('Exclude this string'); + logger.debug('Include this string'); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "This should get logged"); - t.equal(logEvents[1].data[0], "Include this string"); + t.equal(logEvents[0].data[0], 'This should get logged'); + t.equal(logEvents[1].data[0], 'Include this string'); t.end(); } ); @@ -115,27 +115,27 @@ test("log4js noLogFilter", batch => { * test empty string or null regexp */ batch.test( - "appender should skip the match in case of empty or null regexp", - t => { + 'appender should skip the match in case of empty or null regexp', + (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: ["", null, undefined], - appender: "recorder" - } + type: 'noLogFilter', + exclude: ['', null, undefined], + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("This should get logged"); - logger.debug("Another string that should get logged"); + logger.debug('This should get logged'); + logger.debug('Another string that should get logged'); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "This should get logged"); - t.equal(logEvents[1].data[0], "Another string that should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); + t.equal(logEvents[1].data[0], 'Another string that should get logged'); t.end(); } ); @@ -143,26 +143,26 @@ test("log4js noLogFilter", batch => { /** * test for excluding all the events that contains digits */ - batch.test("appender should exclude the events that contains digits", t => { + batch.test('appender should exclude the events that contains digits', (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: "\\d", - appender: "recorder" - } + type: 'noLogFilter', + exclude: '\\d', + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("This should get logged"); - logger.debug("The 2nd event should not get logged"); - logger.debug("The 3rd event should not get logged, such as the 2nd"); + logger.debug('This should get logged'); + logger.debug('The 2nd event should not get logged'); + logger.debug('The 3rd event should not get logged, such as the 2nd'); const logEvents = recording.replay(); t.equal(logEvents.length, 1); - t.equal(logEvents[0].data[0], "This should get logged"); + t.equal(logEvents[0].data[0], 'This should get logged'); t.end(); }); @@ -171,29 +171,29 @@ test("log4js noLogFilter", batch => { * https://log4js-node.github.io/log4js-node/noLogFilter.html */ batch.test( - "appender should exclude not valid events according to the documentation", - t => { + 'appender should exclude not valid events according to the documentation', + (t) => { log4js.configure({ appenders: { - recorder: { type: "recording" }, + recorder: { type: 'recording' }, filtered: { - type: "noLogFilter", - exclude: ["NOT", "\\d", ""], - appender: "recorder" - } + type: 'noLogFilter', + exclude: ['NOT', '\\d', ''], + appender: 'recorder', + }, }, - categories: { default: { appenders: ["filtered"], level: "DEBUG" } } + categories: { default: { appenders: ['filtered'], level: 'DEBUG' } }, }); const logger = log4js.getLogger(); - logger.debug("I will be logged in all-the-logs.log"); - logger.debug("I will be not logged in all-the-logs.log"); - logger.debug("A 2nd message that will be excluded in all-the-logs.log"); - logger.debug("Hello again"); + logger.debug('I will be logged in all-the-logs.log'); + logger.debug('I will be not logged in all-the-logs.log'); + logger.debug('A 2nd message that will be excluded in all-the-logs.log'); + logger.debug('Hello again'); const logEvents = recording.replay(); t.equal(logEvents.length, 2); - t.equal(logEvents[0].data[0], "I will be logged in all-the-logs.log"); - t.equal(logEvents[1].data[0], "Hello again"); + t.equal(logEvents[0].data[0], 'I will be logged in all-the-logs.log'); + t.equal(logEvents[1].data[0], 'Hello again'); t.end(); } ); diff --git a/test/tap/passenger-test.js b/test/tap/passenger-test.js index 1cd7cce0..2d3a1945 100644 --- a/test/tap/passenger-test.js +++ b/test/tap/passenger-test.js @@ -1,5 +1,5 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); // passenger provides a non-functional cluster module, // but it does not implement the event emitter functions @@ -18,34 +18,34 @@ const passengerCluster = { schedulingPolicy: false, settings: false, worker: false, - workers: false + workers: false, }; -const vcr = require("../../lib/appenders/recording"); +const vcr = require('../../lib/appenders/recording'); -const log4js = sandbox.require("../../lib/log4js", { +const log4js = sandbox.require('../../lib/log4js', { requires: { cluster: passengerCluster, - "./appenders/recording": vcr - } + './appenders/recording': vcr, + }, }); -test("When running in Passenger", batch => { - batch.test("it should still log", t => { +test('When running in Passenger', (batch) => { + batch.test('it should still log', (t) => { log4js.configure({ appenders: { - vcr: { type: "recording" } + vcr: { type: 'recording' }, }, categories: { - default: { appenders: ["vcr"], level: "info" } + default: { appenders: ['vcr'], level: 'info' }, }, - disableClustering: true + disableClustering: true, }); - log4js.getLogger().info("This should still work"); + log4js.getLogger().info('This should still work'); const events = vcr.replay(); t.equal(events.length, 1); - t.equal(events[0].data[0], "This should still work"); + t.equal(events[0].data[0], 'This should still work'); t.end(); }); diff --git a/test/tap/pause-test.js b/test/tap/pause-test.js index c4d00c63..e5ec312c 100644 --- a/test/tap/pause-test.js +++ b/test/tap/pause-test.js @@ -1,95 +1,118 @@ -const tap = require("tap"); -const fs = require("fs"); -const log4js = require("../../lib/log4js"); +const tap = require('tap'); +const fs = require('fs'); +const log4js = require('../../lib/log4js'); -const removeFiles = async filenames => { - if (!Array.isArray(filenames)) - filenames = [filenames]; - const promises = filenames.map(filename => fs.promises.unlink(filename)); +const removeFiles = async (filenames) => { + if (!Array.isArray(filenames)) filenames = [filenames]; + const promises = filenames.map((filename) => fs.promises.unlink(filename)); await Promise.allSettled(promises); }; -tap.test("Drain event test", batch => { +tap.test('Drain event test', (batch) => { + batch.test( + 'Should emit pause event and resume when logging in a file with high frequency', + (t) => { + t.teardown(async () => { + process.off( + 'log4js:pause', + process.listeners('log4js:pause')[ + process.listeners('log4js:pause').length - 1 + ] + ); + await removeFiles('logs/drain.log'); + }); + // Generate logger with 5k of highWaterMark config + log4js.configure({ + appenders: { + file: { + type: 'file', + filename: 'logs/drain.log', + highWaterMark: 5 * 1024, + }, + }, + categories: { + default: { appenders: ['file'], level: 'debug' }, + }, + }); - batch.test("Should emit pause event and resume when logging in a file with high frequency", t => { - t.teardown(async () => { - process.off("log4js:pause", process.listeners("log4js:pause")[process.listeners("log4js:pause").length - 1]); - await removeFiles("logs/drain.log"); - }); - // Generate logger with 5k of highWaterMark config - log4js.configure({ - appenders: { - file: { type: "file", filename: "logs/drain.log", highWaterMark: 5 * 1024 } - }, - categories: { - default: { appenders: ["file"], level: "debug" } - } - }); - - let paused = false; - let resumed = false; + let paused = false; + let resumed = false; - process.on("log4js:pause", value => { - if (value) { - paused = true; - t.ok(value, "log4js:pause, true"); - } else { - resumed = true; - t.ok(!value, "log4js:pause, false"); - t.end(); - } - }); + process.on('log4js:pause', (value) => { + if (value) { + paused = true; + t.ok(value, 'log4js:pause, true'); + } else { + resumed = true; + t.ok(!value, 'log4js:pause, false'); + t.end(); + } + }); - const logger = log4js.getLogger(); - while (!paused && !resumed) { - if (!paused) { - logger.info("This is a test for emitting drain event"); + const logger = log4js.getLogger(); + while (!paused && !resumed) { + if (!paused) { + logger.info('This is a test for emitting drain event'); + } } } - }); + ); + batch.test( + 'Should emit pause event and resume when logging in a date file with high frequency', + (t) => { + t.teardown(async () => { + process.off( + 'log4js:pause', + process.listeners('log4js:pause')[ + process.listeners('log4js:pause').length - 1 + ] + ); + await removeFiles('logs/date-file-drain.log'); + }); + // Generate date file logger with 5kb of highWaterMark config + log4js.configure({ + appenders: { + file: { + type: 'dateFile', + filename: 'logs/date-file-drain.log', + highWaterMark: 5 * 1024, + }, + }, + categories: { + default: { appenders: ['file'], level: 'debug' }, + }, + }); - batch.test("Should emit pause event and resume when logging in a date file with high frequency", (t) => { - t.teardown(async () => { - process.off("log4js:pause", process.listeners("log4js:pause")[process.listeners("log4js:pause").length - 1]); - await removeFiles("logs/date-file-drain.log"); - }); - // Generate date file logger with 5kb of highWaterMark config - log4js.configure({ - appenders: { - file: { type: "dateFile", filename: "logs/date-file-drain.log", highWaterMark: 5 * 1024 } - }, - categories: { - default: { appenders: ["file"], level: "debug" } - } - }); + let paused = false; + let resumed = false; - let paused = false; - let resumed = false; + process.on('log4js:pause', (value) => { + if (value) { + paused = true; + t.ok(value, 'log4js:pause, true'); + } else { + resumed = true; + t.ok(!value, 'log4js:pause, false'); + t.end(); + } + }); - process.on("log4js:pause", value => { - if (value) { - paused = true; - t.ok(value, "log4js:pause, true"); - } else { - resumed = true; - t.ok(!value, "log4js:pause, false"); - t.end(); + const logger = log4js.getLogger(); + while (!paused && !resumed) { + if (!paused) + logger.info( + 'This is a test for emitting drain event in date file logger' + ); } - }); - - const logger = log4js.getLogger(); - while (!paused && !resumed) { - if (!paused) - logger.info("This is a test for emitting drain event in date file logger"); } - }); + ); batch.teardown(async () => { try { - const files = fs.readdirSync("logs"); - await removeFiles(files.map(filename => `logs/${filename}`)); - fs.rmdirSync("logs"); + const files = fs.readdirSync('logs'); + await removeFiles(files.map((filename) => `logs/${filename}`)); + fs.rmdirSync('logs'); } catch (e) { // doesn't matter } diff --git a/test/tap/pm2-support-test.js b/test/tap/pm2-support-test.js index ab7568c3..7d5ee440 100644 --- a/test/tap/pm2-support-test.js +++ b/test/tap/pm2-support-test.js @@ -1,6 +1,6 @@ -const { test } = require("tap"); -const cluster = require("cluster"); -const debug = require("debug")("log4js:pm2-test"); +const { test } = require('tap'); +const cluster = require('cluster'); +const debug = require('debug')('log4js:pm2-test'); // PM2 runs everything as workers // - no master in the cluster (PM2 acts as master itself) @@ -9,7 +9,7 @@ if (cluster.isMaster) { // create two worker forks // PASS IN NODE_APP_INSTANCE HERE const appEvents = {}; - ["0", "1"].forEach(i => { + ['0', '1'].forEach((i) => { cluster.fork({ NODE_APP_INSTANCE: i }); }); @@ -17,7 +17,7 @@ if (cluster.isMaster) { if (worker.type || worker.topic) { msg = worker; } - if (msg.type === "testing") { + if (msg.type === 'testing') { debug( `Received testing message from ${msg.instance} with events ${msg.events}` ); @@ -25,7 +25,7 @@ if (cluster.isMaster) { } // we have to do the re-broadcasting that the pm2-intercom module would do. - if (msg.topic === "log4js:message") { + if (msg.topic === 'log4js:message') { debug(`Received log message ${msg}`); for (const id in cluster.workers) { cluster.workers[id].send(msg); @@ -33,70 +33,70 @@ if (cluster.isMaster) { } }; - cluster.on("message", messageHandler); + cluster.on('message', messageHandler); let count = 0; - cluster.on("exit", () => { + cluster.on('exit', () => { count += 1; if (count === 2) { // wait for any IPC messages still to come, because it seems they are slooooow. setTimeout(() => { - test("PM2 Support", batch => { - batch.test("should not get any events when turned off", t => { + test('PM2 Support', (batch) => { + batch.test('should not get any events when turned off', (t) => { t.notOk( - appEvents["0"].filter( - e => e && e.data[0].indexOf("will not be logged") > -1 + appEvents['0'].filter( + (e) => e && e.data[0].indexOf('will not be logged') > -1 ).length ); t.notOk( - appEvents["1"].filter( - e => e && e.data[0].indexOf("will not be logged") > -1 + appEvents['1'].filter( + (e) => e && e.data[0].indexOf('will not be logged') > -1 ).length ); t.end(); }); - batch.test("should get events on app instance 0", t => { - t.equal(appEvents["0"].length, 2); - t.equal(appEvents["0"][0].data[0], "this should now get logged"); - t.equal(appEvents["0"][1].data[0], "this should now get logged"); + batch.test('should get events on app instance 0', (t) => { + t.equal(appEvents['0'].length, 2); + t.equal(appEvents['0'][0].data[0], 'this should now get logged'); + t.equal(appEvents['0'][1].data[0], 'this should now get logged'); t.end(); }); - batch.test("should not get events on app instance 1", t => { - t.equal(appEvents["1"].length, 0); + batch.test('should not get events on app instance 1', (t) => { + t.equal(appEvents['1'].length, 0); t.end(); }); batch.end(); - cluster.removeListener("message", messageHandler); + cluster.removeListener('message', messageHandler); }); }, 1000); } }); } else { - const recorder = require("../../lib/appenders/recording"); - const log4js = require("../../lib/log4js"); + const recorder = require('../../lib/appenders/recording'); + const log4js = require('../../lib/log4js'); log4js.configure({ - appenders: { out: { type: "recording" } }, - categories: { default: { appenders: ["out"], level: "info" } } + appenders: { out: { type: 'recording' } }, + categories: { default: { appenders: ['out'], level: 'info' } }, }); - const logger = log4js.getLogger("test"); + const logger = log4js.getLogger('test'); logger.info( - "this is a test, but without enabling PM2 support it will not be logged" + 'this is a test, but without enabling PM2 support it will not be logged' ); // IPC messages can take a while to get through to start with. setTimeout(() => { log4js.shutdown(() => { log4js.configure({ - appenders: { out: { type: "recording" } }, - categories: { default: { appenders: ["out"], level: "info" } }, - pm2: true + appenders: { out: { type: 'recording' } }, + categories: { default: { appenders: ['out'], level: 'info' } }, + pm2: true, }); - const anotherLogger = log4js.getLogger("test"); + const anotherLogger = log4js.getLogger('test'); setTimeout(() => { - anotherLogger.info("this should now get logged"); + anotherLogger.info('this should now get logged'); }, 1000); // if we're the pm2-master we should wait for the other process to send its log messages @@ -108,9 +108,9 @@ if (cluster.isMaster) { ); process.send( { - type: "testing", + type: 'testing', instance: process.env.NODE_APP_INSTANCE, - events + events, }, () => { setTimeout(() => { diff --git a/test/tap/recordingAppender-test.js b/test/tap/recordingAppender-test.js index 142f6e18..c8066f85 100644 --- a/test/tap/recordingAppender-test.js +++ b/test/tap/recordingAppender-test.js @@ -1,10 +1,10 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); -test("recording appender", t => { +test('recording appender', (t) => { log4js.configure({ appenders: { rec: { type: 'recording' } }, - categories: { default: { appenders: [ 'rec' ], 'level': 'debug' } } + categories: { default: { appenders: ['rec'], level: 'debug' } }, }); const logger = log4js.getLogger(); @@ -15,14 +15,18 @@ test("recording appender", t => { const recording = log4js.recording(); const loggingEvents = recording.playback(); - t.equal(loggingEvents.length, 2, "There should be 2 recorded events"); - t.equal(loggingEvents[0].data[0], "This will go to the recording!"); - t.equal(loggingEvents[1].data[0], "Another one"); + t.equal(loggingEvents.length, 2, 'There should be 2 recorded events'); + t.equal(loggingEvents[0].data[0], 'This will go to the recording!'); + t.equal(loggingEvents[1].data[0], 'Another one'); recording.reset(); const loggingEventsPostReset = recording.playback(); - t.equal(loggingEventsPostReset.length, 0, "There should be 0 recorded events"); + t.equal( + loggingEventsPostReset.length, + 0, + 'There should be 0 recorded events' + ); t.end(); }); diff --git a/test/tap/server-test.js b/test/tap/server-test.js index 69c70615..2277b838 100644 --- a/test/tap/server-test.js +++ b/test/tap/server-test.js @@ -1,36 +1,36 @@ -const { test } = require("tap"); -const net = require("net"); -const log4js = require("../../lib/log4js"); -const vcr = require("../../lib/appenders/recording"); -const levels = require("../../lib/levels"); -const LoggingEvent = require("../../lib/LoggingEvent"); +const { test } = require('tap'); +const net = require('net'); +const log4js = require('../../lib/log4js'); +const vcr = require('../../lib/appenders/recording'); +const levels = require('../../lib/levels'); +const LoggingEvent = require('../../lib/LoggingEvent'); -test("TCP Server", batch => { +test('TCP Server', (batch) => { batch.test( - "should listen for TCP messages and re-send via process.send", - t => { + 'should listen for TCP messages and re-send via process.send', + (t) => { log4js.configure({ appenders: { - vcr: { type: "recording" }, - tcp: { type: "tcp-server", port: 5678 } + vcr: { type: 'recording' }, + tcp: { type: 'tcp-server', port: 5678 }, }, categories: { - default: { appenders: ["vcr"], level: "debug" } - } + default: { appenders: ['vcr'], level: 'debug' }, + }, }); // give the socket a chance to start up setTimeout(() => { const socket = net.connect(5678, () => { socket.write( `${new LoggingEvent( - "test-category", + 'test-category', levels.INFO, - ["something"], + ['something'], {} ).serialise()}__LOG4JS__${new LoggingEvent( - "test-category", + 'test-category', levels.INFO, - ["something else"], + ['something else'], {} ).serialise()}__LOG4JS__some nonsense__LOG4JS__{"some":"json"}__LOG4JS__`, () => { @@ -40,38 +40,38 @@ test("TCP Server", batch => { const logs = vcr.replay(); t.equal(logs.length, 4); t.match(logs[0], { - data: ["something"], - categoryName: "test-category", - level: { levelStr: "INFO" }, - context: {} + data: ['something'], + categoryName: 'test-category', + level: { levelStr: 'INFO' }, + context: {}, }); t.match(logs[1], { - data: ["something else"], - categoryName: "test-category", - level: { levelStr: "INFO" }, - context: {} + data: ['something else'], + categoryName: 'test-category', + level: { levelStr: 'INFO' }, + context: {}, }); t.match(logs[2], { data: [ - "Unable to parse log:", - "some nonsense", - "because: ", - SyntaxError + 'Unable to parse log:', + 'some nonsense', + 'because: ', + SyntaxError, ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, }); t.match(logs[3], { data: [ - "Unable to parse log:", + 'Unable to parse log:', '{"some":"json"}', - "because: ", - TypeError + 'because: ', + TypeError, ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, }); t.end(); }); @@ -85,109 +85,108 @@ test("TCP Server", batch => { } ); - batch.test( - "sending incomplete messages in chunks", - t => { - log4js.configure({ - appenders: { - vcr: { type: "recording" }, - tcp: { type: "tcp-server" } - }, - categories: { - default: { appenders: ["vcr"], level: "debug" } - } - }); - // give the socket a chance to start up - setTimeout(() => { - const socket = net.connect(5000, () => { - const syncWrite = (dataArray, finalCallback) => { - if (!Array.isArray(dataArray)) { - dataArray = [dataArray]; - } - if (typeof finalCallback !== "function") { - finalCallback = () => {}; + batch.test('sending incomplete messages in chunks', (t) => { + log4js.configure({ + appenders: { + vcr: { type: 'recording' }, + tcp: { type: 'tcp-server' }, + }, + categories: { + default: { appenders: ['vcr'], level: 'debug' }, + }, + }); + // give the socket a chance to start up + setTimeout(() => { + const socket = net.connect(5000, () => { + const syncWrite = (dataArray, finalCallback) => { + if (!Array.isArray(dataArray)) { + dataArray = [dataArray]; + } + if (typeof finalCallback !== 'function') { + finalCallback = () => {}; + } + setTimeout(() => { + if (!dataArray.length) { + finalCallback(); + } else if (dataArray.length === 1) { + socket.write(dataArray.shift(), finalCallback); + } else { + socket.write(dataArray.shift(), () => { + syncWrite(dataArray, finalCallback); + }); } - setTimeout(() => { - if (!dataArray.length) { - finalCallback(); - } else if (dataArray.length === 1) { - socket.write(dataArray.shift(), finalCallback); - } else { - socket.write(dataArray.shift(), () => { syncWrite(dataArray, finalCallback); }); - } - }, 100); - }; + }, 100); + }; - const dataArray = [ - "__LOG4JS__", - "Hello__LOG4JS__World", - "__LOG4JS__", - "testing nonsense", - `__LOG4JS__more nonsense__LOG4JS__` - ]; + const dataArray = [ + '__LOG4JS__', + 'Hello__LOG4JS__World', + '__LOG4JS__', + 'testing nonsense', + `__LOG4JS__more nonsense__LOG4JS__`, + ]; - const finalCallback = () => { - socket.end(); - setTimeout(() => { - log4js.shutdown(() => { - const logs = vcr.replay(); - t.equal(logs.length, 8); - t.match(logs[4], { - data: [ - "Unable to parse log:", - "Hello", - "because: ", - SyntaxError - ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} - }); - t.match(logs[5], { - data: [ - "Unable to parse log:", - "World", - "because: ", - SyntaxError - ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} - }); - t.match(logs[6], { - data: [ - "Unable to parse log:", - "testing nonsense", - "because: ", - SyntaxError - ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} - }); - t.match(logs[7], { - data: [ - "Unable to parse log:", - "more nonsense", - "because: ", - SyntaxError - ], - categoryName: "log4js", - level: { levelStr: "ERROR" }, - context: {} - }); - t.end(); + const finalCallback = () => { + socket.end(); + setTimeout(() => { + log4js.shutdown(() => { + const logs = vcr.replay(); + t.equal(logs.length, 8); + t.match(logs[4], { + data: [ + 'Unable to parse log:', + 'Hello', + 'because: ', + SyntaxError, + ], + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, + }); + t.match(logs[5], { + data: [ + 'Unable to parse log:', + 'World', + 'because: ', + SyntaxError, + ], + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, + }); + t.match(logs[6], { + data: [ + 'Unable to parse log:', + 'testing nonsense', + 'because: ', + SyntaxError, + ], + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, + }); + t.match(logs[7], { + data: [ + 'Unable to parse log:', + 'more nonsense', + 'because: ', + SyntaxError, + ], + categoryName: 'log4js', + level: { levelStr: 'ERROR' }, + context: {}, }); - }, 100); - }; + t.end(); + }); + }, 100); + }; - syncWrite(dataArray, finalCallback); - }); + syncWrite(dataArray, finalCallback); + }); - socket.unref(); - }, 100); - } - ); + socket.unref(); + }, 100); + }); batch.end(); }); diff --git a/test/tap/setLevel-asymmetry-test.js b/test/tap/setLevel-asymmetry-test.js index 9bc6fe41..4a9148ba 100644 --- a/test/tap/setLevel-asymmetry-test.js +++ b/test/tap/setLevel-asymmetry-test.js @@ -5,23 +5,23 @@ // 2) isLevelEnabled("foo") works as does isLevelEnabled(log4js.levels.foo). // -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); -const logger = log4js.getLogger("test-setLevel-asymmetry"); +const logger = log4js.getLogger('test-setLevel-asymmetry'); // Define the array of levels as string to iterate over. -const strLevels = ["Trace", "Debug", "Info", "Warn", "Error", "Fatal"]; +const strLevels = ['Trace', 'Debug', 'Info', 'Warn', 'Error', 'Fatal']; const log4jsLevels = strLevels.map(log4js.levels.getLevel); -test("log4js setLevel", batch => { - strLevels.forEach(strLevel => { - batch.test(`is called with a ${strLevel} as string`, t => { +test('log4js setLevel', (batch) => { + strLevels.forEach((strLevel) => { + batch.test(`is called with a ${strLevel} as string`, (t) => { const log4jsLevel = log4js.levels.getLevel(strLevel); - t.test("should convert string to level correctly", assert => { + t.test('should convert string to level correctly', (assert) => { logger.level = strLevel; - log4jsLevels.forEach(level => { + log4jsLevels.forEach((level) => { assert.equal( logger.isLevelEnabled(level), log4jsLevel.isLessThanOrEqualTo(level) @@ -30,9 +30,9 @@ test("log4js setLevel", batch => { assert.end(); }); - t.test("should also accept a Level", assert => { + t.test('should also accept a Level', (assert) => { logger.level = log4jsLevel; - log4jsLevels.forEach(level => { + log4jsLevels.forEach((level) => { assert.equal( logger.isLevelEnabled(level), log4jsLevel.isLessThanOrEqualTo(level) diff --git a/test/tap/stacktraces-test.js b/test/tap/stacktraces-test.js index df6b101f..d8b018fc 100644 --- a/test/tap/stacktraces-test.js +++ b/test/tap/stacktraces-test.js @@ -1,21 +1,21 @@ -const { test } = require("tap"); +const { test } = require('tap'); -test("Stacktraces from errors in different VM context", t => { - const log4js = require("../../lib/log4js"); - const recorder = require("../../lib/appenders/recording"); - const layout = require("../../lib/layouts").basicLayout; - const vm = require("vm"); +test('Stacktraces from errors in different VM context', (t) => { + const log4js = require('../../lib/log4js'); + const recorder = require('../../lib/appenders/recording'); + const layout = require('../../lib/layouts').basicLayout; + const vm = require('vm'); log4js.configure({ - appenders: { vcr: { type: "recording" } }, - categories: { default: { appenders: ["vcr"], level: "debug" } } + appenders: { vcr: { type: 'recording' } }, + categories: { default: { appenders: ['vcr'], level: 'debug' } }, }); const logger = log4js.getLogger(); try { // Access not defined variable. - vm.runInNewContext("myVar();", {}, "myfile.js"); + vm.runInNewContext('myVar();', {}, 'myfile.js'); } catch (e) { // Expect to have a stack trace printed. logger.error(e); @@ -24,6 +24,6 @@ test("Stacktraces from errors in different VM context", t => { const events = recorder.replay(); // recording appender events do not go through layouts, so let's do it const output = layout(events[0]); - t.match(output, "stacktraces-test.js"); + t.match(output, 'stacktraces-test.js'); t.end(); }); diff --git a/test/tap/stderrAppender-test.js b/test/tap/stderrAppender-test.js index 670885e9..3c107103 100644 --- a/test/tap/stderrAppender-test.js +++ b/test/tap/stderrAppender-test.js @@ -1,59 +1,59 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); -const layouts = require("../../lib/layouts"); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); +const layouts = require('../../lib/layouts'); -test("stderr appender", t => { +test('stderr appender', (t) => { const output = []; const appender = sandbox - .require("../../lib/appenders/stderr", { + .require('../../lib/appenders/stderr', { globals: { process: { stderr: { write(data) { output.push(data); - } - } - } - } + }, + }, + }, + }, }) .configure( - { type: "stderr", layout: { type: "messagePassThrough" } }, + { type: 'stderr', layout: { type: 'messagePassThrough' } }, layouts ); - appender({ data: ["biscuits"] }); + appender({ data: ['biscuits'] }); t.plan(2); - t.equal(output.length, 1, "There should be one message."); - t.equal(output[0], "biscuits\n", "The message should be biscuits."); + t.equal(output.length, 1, 'There should be one message.'); + t.equal(output[0], 'biscuits\n', 'The message should be biscuits.'); t.end(); }); -test("stderr appender with default layout", t => { +test('stderr appender with default layout', (t) => { const output = []; - layouts.colouredLayout = () => "I used the colouredLayout"; + layouts.colouredLayout = () => 'I used the colouredLayout'; const appender = sandbox - .require("../../lib/appenders/stderr", { + .require('../../lib/appenders/stderr', { globals: { process: { stderr: { write(data) { output.push(data); - } - } - } - } + }, + }, + }, + }, }) - .configure({ type: "stderr" }, layouts); + .configure({ type: 'stderr' }, layouts); - appender({ data: ["biscuits"] }); + appender({ data: ['biscuits'] }); t.plan(2); - t.equal(output.length, 1, "There should be one message."); + t.equal(output.length, 1, 'There should be one message.'); t.equal( output[0], - "I used the colouredLayout\n", - "The message should have gone through the default layout." + 'I used the colouredLayout\n', + 'The message should have gone through the default layout.' ); t.end(); }); diff --git a/test/tap/stdoutAppender-test.js b/test/tap/stdoutAppender-test.js index 880118d7..89fc2318 100644 --- a/test/tap/stdoutAppender-test.js +++ b/test/tap/stdoutAppender-test.js @@ -1,30 +1,30 @@ -const { test } = require("tap"); -const sandbox = require("@log4js-node/sandboxed-module"); -const layouts = require("../../lib/layouts"); +const { test } = require('tap'); +const sandbox = require('@log4js-node/sandboxed-module'); +const layouts = require('../../lib/layouts'); -test("stdout appender", t => { +test('stdout appender', (t) => { const output = []; const appender = sandbox - .require("../../lib/appenders/stdout", { + .require('../../lib/appenders/stdout', { globals: { process: { stdout: { write(data) { output.push(data); - } - } - } - } + }, + }, + }, + }, }) .configure( - { type: "stdout", layout: { type: "messagePassThrough" } }, + { type: 'stdout', layout: { type: 'messagePassThrough' } }, layouts ); - appender({ data: ["cheese"] }); + appender({ data: ['cheese'] }); t.plan(2); - t.equal(output.length, 1, "There should be one message."); - t.equal(output[0], "cheese\n", "The message should be cheese."); + t.equal(output.length, 1, 'There should be one message.'); + t.equal(output[0], 'cheese\n', 'The message should be cheese.'); t.end(); }); diff --git a/test/tap/subcategories-test.js b/test/tap/subcategories-test.js index cb873faa..4d71098a 100644 --- a/test/tap/subcategories-test.js +++ b/test/tap/subcategories-test.js @@ -1,32 +1,32 @@ -const { test } = require("tap"); -const log4js = require("../../lib/log4js"); +const { test } = require('tap'); +const log4js = require('../../lib/log4js'); -test("subcategories", batch => { - batch.test("loggers created after levels configuration is loaded", t => { +test('subcategories', (batch) => { + batch.test('loggers created after levels configuration is loaded', (t) => { log4js.configure({ - appenders: { stdout: { type: "stdout" } }, + appenders: { stdout: { type: 'stdout' } }, categories: { - default: { appenders: ["stdout"], level: "TRACE" }, - sub1: { appenders: ["stdout"], level: "WARN" }, - "sub1.sub11": { appenders: ["stdout"], level: "TRACE" }, - "sub1.sub11.sub111": { appenders: ["stdout"], level: "WARN" }, - "sub1.sub12": { appenders: ["stdout"], level: "INFO" } - } + default: { appenders: ['stdout'], level: 'TRACE' }, + sub1: { appenders: ['stdout'], level: 'WARN' }, + 'sub1.sub11': { appenders: ['stdout'], level: 'TRACE' }, + 'sub1.sub11.sub111': { appenders: ['stdout'], level: 'WARN' }, + 'sub1.sub12': { appenders: ['stdout'], level: 'INFO' }, + }, }); const loggers = { - sub1: log4js.getLogger("sub1"), // WARN - sub11: log4js.getLogger("sub1.sub11"), // TRACE - sub111: log4js.getLogger("sub1.sub11.sub111"), // WARN - sub12: log4js.getLogger("sub1.sub12"), // INFO - - sub13: log4js.getLogger("sub1.sub13"), // Inherits sub1: WARN - sub112: log4js.getLogger("sub1.sub11.sub112"), // Inherits sub1.sub11: TRACE - sub121: log4js.getLogger("sub1.sub12.sub121"), // Inherits sub12: INFO - sub0: log4js.getLogger("sub0") // Not defined, not inherited: TRACE + sub1: log4js.getLogger('sub1'), // WARN + sub11: log4js.getLogger('sub1.sub11'), // TRACE + sub111: log4js.getLogger('sub1.sub11.sub111'), // WARN + sub12: log4js.getLogger('sub1.sub12'), // INFO + + sub13: log4js.getLogger('sub1.sub13'), // Inherits sub1: WARN + sub112: log4js.getLogger('sub1.sub11.sub112'), // Inherits sub1.sub11: TRACE + sub121: log4js.getLogger('sub1.sub12.sub121'), // Inherits sub12: INFO + sub0: log4js.getLogger('sub0'), // Not defined, not inherited: TRACE }; - t.test("check logger levels", assert => { + t.test('check logger levels', (assert) => { assert.equal(loggers.sub1.level, log4js.levels.WARN); assert.equal(loggers.sub11.level, log4js.levels.TRACE); assert.equal(loggers.sub111.level, log4js.levels.WARN); @@ -42,38 +42,38 @@ test("subcategories", batch => { t.end(); }); - batch.test("loggers created before levels configuration is loaded", t => { + batch.test('loggers created before levels configuration is loaded', (t) => { // reset to defaults log4js.configure({ - appenders: { stdout: { type: "stdout" } }, - categories: { default: { appenders: ["stdout"], level: "info" } } + appenders: { stdout: { type: 'stdout' } }, + categories: { default: { appenders: ['stdout'], level: 'info' } }, }); // these should all get the default log level of INFO const loggers = { - sub1: log4js.getLogger("sub1"), // WARN - sub11: log4js.getLogger("sub1.sub11"), // TRACE - sub111: log4js.getLogger("sub1.sub11.sub111"), // WARN - sub12: log4js.getLogger("sub1.sub12"), // INFO - - sub13: log4js.getLogger("sub1.sub13"), // Inherits sub1: WARN - sub112: log4js.getLogger("sub1.sub11.sub112"), // Inherits sub1.sub11: TRACE - sub121: log4js.getLogger("sub1.sub12.sub121"), // Inherits sub12: INFO - sub0: log4js.getLogger("sub0") // Not defined, not inherited: TRACE + sub1: log4js.getLogger('sub1'), // WARN + sub11: log4js.getLogger('sub1.sub11'), // TRACE + sub111: log4js.getLogger('sub1.sub11.sub111'), // WARN + sub12: log4js.getLogger('sub1.sub12'), // INFO + + sub13: log4js.getLogger('sub1.sub13'), // Inherits sub1: WARN + sub112: log4js.getLogger('sub1.sub11.sub112'), // Inherits sub1.sub11: TRACE + sub121: log4js.getLogger('sub1.sub12.sub121'), // Inherits sub12: INFO + sub0: log4js.getLogger('sub0'), // Not defined, not inherited: TRACE }; log4js.configure({ - appenders: { stdout: { type: "stdout" } }, + appenders: { stdout: { type: 'stdout' } }, categories: { - default: { appenders: ["stdout"], level: "TRACE" }, - sub1: { appenders: ["stdout"], level: "WARN" }, - "sub1.sub11": { appenders: ["stdout"], level: "TRACE" }, - "sub1.sub11.sub111": { appenders: ["stdout"], level: "WARN" }, - "sub1.sub12": { appenders: ["stdout"], level: "INFO" } - } + default: { appenders: ['stdout'], level: 'TRACE' }, + sub1: { appenders: ['stdout'], level: 'WARN' }, + 'sub1.sub11': { appenders: ['stdout'], level: 'TRACE' }, + 'sub1.sub11.sub111': { appenders: ['stdout'], level: 'WARN' }, + 'sub1.sub12': { appenders: ['stdout'], level: 'INFO' }, + }, }); - t.test("should still get new levels", assert => { + t.test('should still get new levels', (assert) => { // can't use .equal because by calling log4js.configure we create new instances assert.same(loggers.sub1.level, log4js.levels.WARN); assert.same(loggers.sub11.level, log4js.levels.TRACE); @@ -90,30 +90,33 @@ test("subcategories", batch => { }); batch.test( - "setting level on subcategories should not set parent level", - t => { + 'setting level on subcategories should not set parent level', + (t) => { log4js.configure({ - appenders: { stdout: { type: "stdout" } }, + appenders: { stdout: { type: 'stdout' } }, categories: { - default: { appenders: ["stdout"], level: "trace" }, - parent: { appenders: ["stdout"], level: "error" } - } + default: { appenders: ['stdout'], level: 'trace' }, + parent: { appenders: ['stdout'], level: 'error' }, + }, }); - const logger = log4js.getLogger("parent"); - const subLogger = log4js.getLogger("parent.child"); + const logger = log4js.getLogger('parent'); + const subLogger = log4js.getLogger('parent.child'); - t.test("should inherit parent level", assert => { + t.test('should inherit parent level', (assert) => { assert.same(subLogger.level, log4js.levels.ERROR); assert.end(); }); - t.test("changing child level should not change parent level", assert => { - subLogger.level = "info"; - assert.same(subLogger.level, log4js.levels.INFO); - assert.same(logger.level, log4js.levels.ERROR); - assert.end(); - }); + t.test( + 'changing child level should not change parent level', + (assert) => { + subLogger.level = 'info'; + assert.same(subLogger.level, log4js.levels.INFO); + assert.same(logger.level, log4js.levels.ERROR); + assert.end(); + } + ); t.end(); } diff --git a/test/tap/tcp-appender-test.js b/test/tap/tcp-appender-test.js index 3e9fb198..068ff829 100644 --- a/test/tap/tcp-appender-test.js +++ b/test/tap/tcp-appender-test.js @@ -1,23 +1,22 @@ -const { test } = require("tap"); -const net = require("net"); -const flatted = require("flatted"); -const sandbox = require("@log4js-node/sandboxed-module"); -const log4js = require("../../lib/log4js"); -const LoggingEvent = require("../../lib/LoggingEvent"); +const { test } = require('tap'); +const net = require('net'); +const flatted = require('flatted'); +const sandbox = require('@log4js-node/sandboxed-module'); +const log4js = require('../../lib/log4js'); +const LoggingEvent = require('../../lib/LoggingEvent'); let messages = []; let server = null; function makeServer(config) { + server = net.createServer((socket) => { + socket.setEncoding('utf8'); - server = net.createServer(socket => { - socket.setEncoding("utf8"); - - socket.on("data", data => { + socket.on('data', (data) => { data .split(config.endMsg) - .filter(s => s.length) - .forEach(s => { + .filter((s) => s.length) + .forEach((s) => { messages.push(config.deserialise(s)); }); }); @@ -49,72 +48,71 @@ function makeFakeNet() { }, end() { fakeNet.closeCalled = true; - } + }, }; }, createServer(cb) { const fakeNet = this; cb({ - remoteAddress: "1.2.3.4", - remotePort: "1234", + remoteAddress: '1.2.3.4', + remotePort: '1234', setEncoding(encoding) { fakeNet.encoding = encoding; }, on(event, cb2) { fakeNet.cbs[event] = cb2; - } + }, }); return { listen(port, host) { fakeNet.port = port; fakeNet.host = host; - } + }, }; - } + }, }; } -test("TCP Appender", batch => { - - batch.test("Default Configuration", t => { +test('TCP Appender', (batch) => { + batch.test('Default Configuration', (t) => { messages = []; const serverConfig = { - endMsg: "__LOG4JS__", - deserialise: (log) => LoggingEvent.deserialise(log) - } + endMsg: '__LOG4JS__', + deserialise: (log) => LoggingEvent.deserialise(log), + }; server = makeServer(serverConfig); server.listen(() => { const { port } = server.address(); log4js.configure({ appenders: { - default: { type: "tcp", port }, + default: { type: 'tcp', port }, }, categories: { - default: { appenders: ["default"], level: "debug" }, - } + default: { appenders: ['default'], level: 'debug' }, + }, }); const logger = log4js.getLogger(); - logger.info("This should be sent via TCP."); - logger.info("This should also be sent via TCP and not break things."); + logger.info('This should be sent via TCP.'); + logger.info('This should also be sent via TCP and not break things.'); log4js.shutdown(() => { server.close(() => { t.equal(messages.length, 2); t.match(messages[0], { - data: ["This should be sent via TCP."], - categoryName: "default", + data: ['This should be sent via TCP.'], + categoryName: 'default', context: {}, - level: { levelStr: "INFO" } + level: { levelStr: 'INFO' }, }); t.match(messages[1], { - data: ["This should also be sent via TCP and not break things."], - categoryName: "default", + data: ['This should also be sent via TCP and not break things.'], + categoryName: 'default', context: {}, - level: { levelStr: "INFO" } + level: { levelStr: 'INFO' }, }); t.end(); }); @@ -122,44 +120,48 @@ test("TCP Appender", batch => { }); }); - batch.test("Custom EndMessage String", t => { + batch.test('Custom EndMessage String', (t) => { messages = []; const serverConfig = { - endMsg: "\n", - deserialise: (log) => LoggingEvent.deserialise(log) - } + endMsg: '\n', + deserialise: (log) => LoggingEvent.deserialise(log), + }; server = makeServer(serverConfig); server.listen(() => { const { port } = server.address(); log4js.configure({ appenders: { - customEndMsg: { type: "tcp", port, endMsg: "\n" }, + customEndMsg: { type: 'tcp', port, endMsg: '\n' }, }, categories: { - default: { appenders: ["customEndMsg"], level: "debug" }, - } + default: { appenders: ['customEndMsg'], level: 'debug' }, + }, }); const logger = log4js.getLogger(); - logger.info("This should be sent via TCP using a custom EndMsg string."); - logger.info("This should also be sent via TCP using a custom EndMsg string and not break things."); + logger.info('This should be sent via TCP using a custom EndMsg string.'); + logger.info( + 'This should also be sent via TCP using a custom EndMsg string and not break things.' + ); log4js.shutdown(() => { server.close(() => { t.equal(messages.length, 2); t.match(messages[0], { - data: ["This should be sent via TCP using a custom EndMsg string."], - categoryName: "default", + data: ['This should be sent via TCP using a custom EndMsg string.'], + categoryName: 'default', context: {}, - level: { levelStr: "INFO" } + level: { levelStr: 'INFO' }, }); t.match(messages[1], { - data: ["This should also be sent via TCP using a custom EndMsg string and not break things."], - categoryName: "default", + data: [ + 'This should also be sent via TCP using a custom EndMsg string and not break things.', + ], + categoryName: 'default', context: {}, - level: { levelStr: "INFO" } + level: { levelStr: 'INFO' }, }); t.end(); }); @@ -167,51 +169,59 @@ test("TCP Appender", batch => { }); }); - batch.test("Custom Layout", t => { + batch.test('Custom Layout', (t) => { messages = []; const serverConfig = { - endMsg: "__LOG4JS__", - deserialise: (log) => JSON.parse(log) - } + endMsg: '__LOG4JS__', + deserialise: (log) => JSON.parse(log), + }; server = makeServer(serverConfig); - log4js.addLayout('json', () => function (logEvent) { - return JSON.stringify({ - "time": logEvent.startTime, - "message": logEvent.data[0], - "level": logEvent.level.toString() - }); - }); + log4js.addLayout( + 'json', + () => + function (logEvent) { + return JSON.stringify({ + time: logEvent.startTime, + message: logEvent.data[0], + level: logEvent.level.toString(), + }); + } + ); server.listen(() => { const { port } = server.address(); log4js.configure({ appenders: { customLayout: { - type: "tcp", port, - layout: { type: 'json' } + type: 'tcp', + port, + layout: { type: 'json' }, }, }, categories: { - default: { appenders: ["customLayout"], level: "debug" }, - } + default: { appenders: ['customLayout'], level: 'debug' }, + }, }); const logger = log4js.getLogger(); - logger.info("This should be sent as a customized json."); - logger.info("This should also be sent via TCP as a customized json and not break things."); + logger.info('This should be sent as a customized json.'); + logger.info( + 'This should also be sent via TCP as a customized json and not break things.' + ); log4js.shutdown(() => { server.close(() => { t.equal(messages.length, 2); t.match(messages[0], { - message: "This should be sent as a customized json.", - level: "INFO" + message: 'This should be sent as a customized json.', + level: 'INFO', }); t.match(messages[1], { - message: "This should also be sent via TCP as a customized json and not break things.", - level: "INFO" + message: + 'This should also be sent via TCP as a customized json and not break things.', + level: 'INFO', }); t.end(); }); @@ -219,29 +229,29 @@ test("TCP Appender", batch => { }); }); - batch.test("when underlying stream errors", t => { + batch.test('when underlying stream errors', (t) => { const fakeNet = makeFakeNet(); - const sandboxedLog4js = sandbox.require("../../lib/log4js", { + const sandboxedLog4js = sandbox.require('../../lib/log4js', { requires: { - net: fakeNet - } + net: fakeNet, + }, }); sandboxedLog4js.configure({ appenders: { - default: { type: "tcp" }, + default: { type: 'tcp' }, }, categories: { - default: { appenders: ["default"], level: "debug" }, - } + default: { appenders: ['default'], level: 'debug' }, + }, }); const logger = sandboxedLog4js.getLogger(); - logger.info("before connect"); + logger.info('before connect'); t.test( - "should buffer messages written before socket is connected", - assert => { + 'should buffer messages written before socket is connected', + (assert) => { assert.equal(fakeNet.data.length, 0); assert.equal(fakeNet.createConnectionCalled, 1); assert.end(); @@ -249,60 +259,63 @@ test("TCP Appender", batch => { ); fakeNet.cbs.connect(); - t.test( - "should flush buffered messages", - assert => { - assert.equal(fakeNet.data.length, 1); - assert.equal(fakeNet.createConnectionCalled, 1); - assert.match(fakeNet.data[0], "before connect"); - assert.end(); - } - ); + t.test('should flush buffered messages', (assert) => { + assert.equal(fakeNet.data.length, 1); + assert.equal(fakeNet.createConnectionCalled, 1); + assert.match(fakeNet.data[0], 'before connect'); + assert.end(); + }); - logger.info("after connect"); + logger.info('after connect'); t.test( - "should write log messages to socket as flatted strings with a terminator string", - assert => { + 'should write log messages to socket as flatted strings with a terminator string', + (assert) => { assert.equal(fakeNet.data.length, 2); - assert.match(fakeNet.data[0], "before connect"); - assert.ok(fakeNet.data[0].endsWith("__LOG4JS__")); - assert.match(fakeNet.data[1], "after connect"); - assert.ok(fakeNet.data[1].endsWith("__LOG4JS__")); - assert.equal(fakeNet.encoding, "utf8"); + assert.match(fakeNet.data[0], 'before connect'); + assert.ok(fakeNet.data[0].endsWith('__LOG4JS__')); + assert.match(fakeNet.data[1], 'after connect'); + assert.ok(fakeNet.data[1].endsWith('__LOG4JS__')); + assert.equal(fakeNet.encoding, 'utf8'); assert.end(); } ); fakeNet.cbs.error(); - logger.info("after error, before close"); + logger.info('after error, before close'); fakeNet.cbs.close(); - logger.info("after close, before connect"); + logger.info('after close, before connect'); fakeNet.cbs.connect(); - logger.info("after error, after connect"); - t.test("should attempt to re-open the socket on error", assert => { + logger.info('after error, after connect'); + t.test('should attempt to re-open the socket on error', (assert) => { assert.equal(fakeNet.data.length, 5); assert.equal(fakeNet.createConnectionCalled, 2); - assert.match(fakeNet.data[2], "after error, before close"); - assert.match(fakeNet.data[3], "after close, before connect"); - assert.match(fakeNet.data[4], "after error, after connect"); + assert.match(fakeNet.data[2], 'after error, before close'); + assert.match(fakeNet.data[3], 'after close, before connect'); + assert.match(fakeNet.data[4], 'after error, after connect'); assert.end(); }); - t.test("should buffer messages until drain", assert => { + t.test('should buffer messages until drain', (assert) => { const previousLength = fakeNet.data.length; - logger.info("should not be flushed"); + logger.info('should not be flushed'); assert.equal(fakeNet.data.length, previousLength); - assert.notMatch(fakeNet.data[fakeNet.data.length - 1], "should not be flushed"); + assert.notMatch( + fakeNet.data[fakeNet.data.length - 1], + 'should not be flushed' + ); fakeNet.cbs.drain(); assert.equal(fakeNet.data.length, previousLength + 1); - assert.match(fakeNet.data[fakeNet.data.length - 1], "should not be flushed"); + assert.match( + fakeNet.data[fakeNet.data.length - 1], + 'should not be flushed' + ); assert.end(); }); - t.test("should serialize an Error correctly", assert => { + t.test('should serialize an Error correctly', (assert) => { const previousLength = fakeNet.data.length; - logger.error(new Error("Error test")); + logger.error(new Error('Error test')); fakeNet.cbs.drain(); assert.equal(fakeNet.data.length, previousLength + 1); const raw = fakeNet.data[fakeNet.data.length - 1]; @@ -311,7 +324,8 @@ test("TCP Appender", batch => { flatted.parse(raw.slice(0, offset !== -1 ? offset : 0)).data[0].stack, `Expected:\n\n${fakeNet.data[6]}\n\n to have a 'data[0].stack' property` ); - const actual = flatted.parse(raw.slice(0, offset !== -1 ? offset : 0)).data[0].stack; + const actual = flatted.parse(raw.slice(0, offset !== -1 ? offset : 0)) + .data[0].stack; assert.match(actual, /^Error: Error test/); assert.end(); }); diff --git a/test/tap/test-config.json b/test/tap/test-config.json index 2a69651b..bed4e5a0 100644 --- a/test/tap/test-config.json +++ b/test/tap/test-config.json @@ -1,5 +1,3 @@ { - "appenders": [ - { "type": "stdout" } - ] + "appenders": [{ "type": "stdout" }] } diff --git a/v2-changes.md b/v2-changes.md index 97593698..1da1998b 100644 --- a/v2-changes.md +++ b/v2-changes.md @@ -1,5 +1,4 @@ -CHANGES -======= +# CHANGES - no exit listeners defined for appenders by default. users should call log4js.shutdown in their exit listeners. - context added to loggers (only logstash uses it so far)