Compare commits

..

168 Commits

Author SHA1 Message Date
Francisco Dans
3bf2bade32 x-forwarded-for 2015-06-01 15:30:46 +02:00
Gareth Jones
0c74fbbf7d added node 0.12 to travis config 2015-05-13 08:06:16 +10:00
Gareth Jones
8dff114b49 0.6.25 2015-05-13 08:03:35 +10:00
Gareth Jones
c76fe098ae Merge pull request #294 from Skiggz/gelf-fix
Remove GELF flag when capturing custom fields
2015-05-13 07:54:33 +10:00
Skylar Lowery
1454ae5350 Use isUndefined test method vs equals undefined
*doh
2015-04-27 11:01:20 -06:00
Skylar Lowery
3cf1d697e8 Remove GELF flag when capturing custom fields
* Logstash (which supports GELF) drops messages with this key
* There's no particular need to keep this key
2015-04-24 11:14:17 -06:00
Gareth Jones
9fe32d06e3 0.6.24 2015-04-17 11:36:22 +10:00
Gareth Jones
b8e1d03928 Merge pull request #292 from hasegawa-jun/fix-reference-error
make sure to call require()
2015-04-17 11:35:28 +10:00
hasegawa-jun
ebfcf94db3 make sure to call require() 2015-04-17 10:08:00 +09:00
Gareth Jones
adeb714243 made calling logger.log safe if level is not provided as first argument (github issue #279) 2015-04-17 08:31:12 +10:00
Gareth Jones
1cdd37c488 0.6.23 2015-04-17 08:21:00 +10:00
Gareth Jones
eb87ccb78d Merge pull request #277 from hasegawa-jun/shutdown-smtp-appender
Implemented shutdown function for SMTP appender
2015-04-17 08:12:17 +10:00
Gareth Jones
8360bb732c Merge pull request #282 from qbrandon/master
Add appender-level timezone offset config
2015-04-17 08:10:15 +10:00
Gareth Jones
085a88d6fc upgraded semver package version (github issue #291) 2015-04-17 08:05:47 +10:00
Gareth Jones
957d5d369d Merge pull request #288 from alawatthe/nodemailermigration
The smtp appender now works with the current version of nodemailer - fixes #287
2015-04-17 07:54:57 +10:00
alawatthe
57fc9e7aa0 The smtp appender now works with the current version of nodemailer 2015-04-11 12:03:14 +02:00
Quentin Brandon
435f4f320f Bugfixes: get the unit tests passing again 2015-03-20 18:35:53 +09:00
Quentin Brandon
af69eddd1c Add optional timezoneOffset config for appenders
Example:
    log4js.configure({
        appenders: [{type: 'console', timezoneOffset: -540}],
        replaceConsole: true
    });

The expected value is the equivalent of (new Date).getTimezoneOffset()
In this example, -540 is the value for JST.
This allows machines members of world-wide-spread cluster to all report
log time-stamps using the same timezone (or adapt the timezone to a
local different from the system)
2015-03-20 11:51:23 +09:00
hasegawa-jun
4dfe14a0c2 added shutdownTimeout option 2015-03-17 09:25:22 +09:00
Gareth Jones
4a217afc37 Merge pull request #278 from cfogelberg/custom-connect-tokens
Custom connect tokens
2015-03-12 10:02:24 +11:00
Christo Fogelberg
41504a755d test/connect-logger-test.js - tests for custom tokens 2015-03-10 06:37:53 +00:00
Christo Fogelberg
f22621199f test/connect-logger-test.js - trailing whitespace Sublime removed 2015-03-10 06:24:57 +00:00
Christo Fogelberg
25c543f8ae lib/connect-logger.js - allow options.tokens 2015-03-10 06:18:02 +00:00
Christo Fogelberg
24268422cf lib/connect-logger.js - format takes tokens array instead of req, res 2015-03-10 06:13:49 +00:00
Christo Fogelberg
ba80dc1588 Trailing whitespace Sublime removed 2015-03-08 19:36:17 +00:00
hasegawa-jun
adfad9ad20 Implemented shutdown function for SMTP appender 2015-03-04 09:13:30 +09:00
Gareth Jones
35067af550 0.6.22 2015-01-10 15:40:03 +11:00
Gareth Jones
d31521bac0 Merge pull request #240 from vivocha/vivocha-0.6.20
Vivocha 0.6.20
2015-01-10 15:34:31 +11:00
Gareth Jones
6d7cab343d Merge pull request #260 from DerKnerd/patch-1
Update README.md
2015-01-10 15:29:53 +11:00
Gareth Jones
c624aef282 Merge pull request #261 from boljen/clusterpid
added cluster identifier support
2015-01-10 15:29:01 +11:00
Gareth Jones
0ae72ee424 Merge pull request #264 from FleetingClouds/master
Force bundling of appenders/console
2015-01-10 15:26:39 +11:00
Gareth Jones
a4be20f8e1 Merge pull request #266 from sc2bigjoe/patch-1
Update smtp.js
2015-01-10 15:23:28 +11:00
Gareth Jones
d10d40b572 Merge pull request #268 from askhogan/master
Allow for blank tokens due to dynamic data
2015-01-10 15:22:24 +11:00
Gareth Jones
51ab2963d0 Merge pull request #269 from Nekle/master
add options to reload function
2015-01-10 15:21:46 +11:00
Fuxian Ding
1f1442cb7c add options to reload function
if `cwd` is included in option, reload will not work
2014-12-27 12:48:24 +08:00
Patrick Hogan
f987990339 added null tests 2014-12-23 19:42:32 -08:00
Patrick Hogan
6b029e98fc Allow for blank tokens due to dynamic data
Metadata for users such as name, email, etc are not always present for users.  For example, I am running express and I want to log the %x{company}%x{username} so that when I look at my logs I can immediately understand which user this affects.  Or for example, I could log %x{payingOrTial} the type of user.  

This works well when the user is logged in.  However, my logger encompasses everything.  I log when the server boots up.  I log during the login screen where a user is not yet logged in.  In these circumstances there is no way to retrieve this metadata.

So for example

```
"username": function () {
            var session = require('continuation-local-storage').getNamespace('api.callinize');
            if(!session) session = require('continuation-local-storage').getNamespace('dashboard.callinize');
            var username = session && session.get('user') && session.get('user').username;
            if(!username) return "";
            return " " + username + " ";
        }
```

I try to get the metadata.  If I get no metdata I return a blank string.  Unfortunately, in the current implementation, due to the OR operator, even if I have a replacement of "" || matchedString, 

```
  replaceToken(conversionCharacter, loggingEvent, specifier) || 
          matchedString;
```

the blank string equals false and puts the token in the log instead of the blank string.  This makes the log lines get long with information that is not relevant.  The better thing to do is simply allow for blank strings.  This lets the user have control over their logs and also allows for more metadata to go in the logs, without having to pick only metadata that is always present.
2014-12-21 14:49:25 -08:00
sc2bigjoe
1629e01df9 Update smtp.js
added the ability for smtp appender to send message as html instead of plaintext. in your log4js.config file simply include "html": "true", to write out as html, otherwise it will send plaintext
2014-12-17 11:28:50 -05:00
Martin Bramwell
ec72c03f81 Force bundling of appenders/console
Changes to be committed:
	modified:   lib/log4js.js
2014-12-09 02:59:58 -05:00
Christophe Bol
3300dfae60 fixed error when logging from the clustered master 2014-12-01 15:34:09 +01:00
Christophe Bol
b694fd1d8d added cluster identifier support 2014-12-01 12:29:45 +01:00
Imanuel Ulbricht
e07adf2ca4 Update README.md 2014-11-28 17:49:46 +01:00
Gareth Jones
ec5f4485f8 Merge pull request #258 from osher/patch-4
fix bug: headers are changed after log entry emits
2014-11-16 09:19:47 +11:00
osher
2f44dbf53e 0.8 compatibility 2014-11-05 11:58:09 +02:00
osher
9da158f945 fix tests - they have to be async! 2014-11-05 11:49:21 +02:00
osher
cd3971cc03 fix bug: headers are changed after log entry emits
In the original version, the following operation looks synchronic, however it is not:

```
res.end = end;
res.end(data,enc);

//emit the log entry 
```

In fact, it starts a series of async operations, in which the request may yet be changed after the request log has already been emitted
(in our case - a change on request headers was observed, probably by some low level hook or hacky wrap of some http.ServerResponse method that's involved on the process - but called asynchronously)
what leads to situation that the request log does not capture valid data.
(observed by us:
 - request headers
 - calculated end time, when concerning big content
)

The fix just used `setTimeout(function() { /*emit the log entry*/ }, 1)`, but I'm afraid it may not hold true for big contents.
Well. maybe the headers part will, but the response time calculation will lie.

The fix relays on: http://nodejs.org/api/http.html#http_event_finish
2014-11-04 17:28:52 +02:00
Gareth Jones
176d44833e 0.6.21 2014-09-11 09:26:02 +10:00
Gareth Jones
988e9a41f6 added license info 2014-09-11 09:23:55 +10:00
Gareth Jones
39ce97d140 Merge pull request #242 from marcelog/marcelog_logstash_udp_appender
adding logstash UDP appender
2014-09-11 09:20:42 +10:00
Gareth Jones
c753fe37bb Merge pull request #243 from laenger/master
pass options to wrapped appender in logLevelFilter
2014-09-11 09:16:46 +10:00
Marcelo Gornstein
a7a0964803 adding logstash UDP appender 2014-09-10 13:03:21 -03:00
Christian Langer
82950eb965 pass options to wrapped appender in logLevelFilter 2014-09-09 03:28:02 +02:00
Luis Malheiro
1e999f36d7 Fix and test for MARK level. 2014-09-08 12:17:50 +02:00
Luis Malheiro
17c9b29ca5 Removed property 'level' from the file appender, because that functionality is provided by appender logLevelFilter. 2014-09-08 11:33:22 +02:00
Luis Malheiro
492c45d055 Test for appender using subcategories. 2014-09-08 11:14:00 +02:00
Luis Malheiro
ebbbea198d Added test to check loggers using sub-categories. 2014-09-02 14:33:51 +02:00
Gareth Jones
cacade0a37 Merge pull request #239 from lazutkin/gh-238
Closes #238 Updated async library
2014-09-02 19:33:58 +10:00
Luis Malheiro
02ea4831ea Test for the 'compress' option at the file appender. 2014-09-01 18:05:36 +02:00
Luis Malheiro
39a73586ed Fixed bug that failed test 'set level on all categories' 2014-09-01 14:37:25 +02:00
Luis Malheiro
036293db41 Log compression. 2014-08-29 16:33:41 +02:00
Luis Malheiro
6fa998408a Adds subcategories to the appenders and loggers. Adds property "level" at the file appender to limit the levels that a file appender accepts.
Creates a MARK category that always write to the log. That's useful to write things like '---- STARTED ----'.
2014-08-29 16:33:32 +02:00
Dmitry M. Lazutkin
7558a3c367 Closes #238 Updated async library in order to use lib in —use-strict mode 2014-08-28 12:04:02 +04:00
Gareth Jones
fb072dd70d 0.6.20 2014-08-26 09:59:10 +10:00
Gareth Jones
af1ce2933b Merge pull request #236 from jchmura/filter-max-level
Added option for maximum level in logLevelFilter
2014-08-26 09:55:13 +10:00
Jakub Chmura
ade6dd8ea0 Adjusting and adding new tests for logLevelFilter to handle the maxLevel option. 2014-08-25 20:56:37 +02:00
Jakub Chmura
00c62c7fa6 Adding maxLevel to levelFilter.
This optional parameter specifies what maximum level of event is accepted by the filter.
2014-08-25 19:48:15 +02:00
Gareth Jones
ae04cc9a4a 0.6.19 2014-08-21 21:21:16 +10:00
Gareth Jones
70a9444f4d Merge pull request #235 from j2ro/master
Pull request for #233
2014-08-21 21:20:27 +10:00
j2ro
3e78fcb630 #233: Adding ability to put pid in log layout pattern 2014-08-20 10:43:48 +01:00
j2ro
44687e1bd1 #233: Adding ability to put pid in log layout pattern 2014-08-20 10:23:31 +01:00
Gareth Jones
8e5754371a 0.6.18 2014-08-20 10:20:57 +01:00
Grégoire Charvet 黑瓜
feef9975c7 Remove test logging 2014-08-20 10:20:57 +01:00
Grégoire Charvet 黑瓜
93695fbfc4 Change spaces by tabs
Keeping constitency with the rest of the code.
2014-08-20 10:20:57 +01:00
Grégoire Charvet 黑瓜
0571089a8b Correctly send message, level and hostname
Fix issue #230 where the level would hold the message and the log level
information would be lost.
2014-08-20 10:20:57 +01:00
Gareth Jones
ab77895555 0.6.18 2014-08-20 09:12:13 +10:00
Gareth Jones
9637be8a41 Merge pull request #232 from GregoireDigbil/fix_loggly_formatting
Fix loggly formatting
2014-08-20 09:11:12 +10:00
Grégoire Charvet 黑瓜
0ecd729f49 Remove test logging 2014-08-18 07:32:23 +08:00
Grégoire Charvet 黑瓜
f9c2e78055 Change spaces by tabs
Keeping constitency with the rest of the code.
2014-08-18 07:31:33 +08:00
Grégoire Charvet 黑瓜
e7267ecf46 Correctly send message, level and hostname
Fix issue #230 where the level would hold the message and the log level
information would be lost.
2014-08-18 07:25:55 +08:00
Gareth Jones
c03185b563 Merge pull request #231 from eurekaa/buffered-logger
added getBufferedLogger function.
2014-08-17 11:00:10 +10:00
Stefano Graziato
c0aa8c5c86 gitignore 2014-08-16 14:52:00 +02:00
Stefano Graziato
59a6703549 getBufferedLogger tested. 2014-08-16 14:22:58 +02:00
Gareth Jones
ceffdf92e4 Removed hook.io appender, because hook.io does not build on systems without python 2014-08-16 12:23:50 +10:00
Stefano Graziato
c9e72d0f00 added getBufferedLogger function.
This function should be useful when you need to log during async
parallel operations, without having a mess in logs.
For example when you walk asynchronously a directory and you want logs
to be grouped by file.

It returns the same getLogger() object but messages are stored
internally and sent to appenders only when you call the flush() method
on it.
2014-08-15 13:42:08 +02:00
Gareth Jones
a27345461b altering the timings on some tests to make them slightly less flaky (maybe) 2014-08-15 20:06:35 +10:00
Gareth Jones
fb9948145c 0.6.17 2014-08-15 18:32:32 +10:00
Gareth Jones
0242bae78f Merge pull request #214 from GregoireDigbil/master
Format message before adding loggly metadata
2014-08-15 18:29:19 +10:00
Gareth Jones
b71f635267 Merge pull request #224 from idalv/express_fix
Update connect-logger.js to work correctly with express
2014-08-02 03:30:05 +10:00
mishless
66872d136d Update connect-logger.js to work correctly with express
When used with express levels are wrong since send() does not call writeHead, but sets responseCode on response.
2014-07-30 13:06:51 +03:00
Gareth Jones
49849a545a Merge pull request #219 from PSyton/fix_for_no_dir
Make some test windows friendly.
2014-07-18 08:43:27 +10:00
Pavel Sysolyatin
3c4c98bb0b Make some test windows friendly. 2014-07-17 14:29:03 +07:00
Gareth Jones
eaa77b0454 0.6.16 2014-07-12 17:46:03 +10:00
Gareth Jones
78c604b90d Merge branch 'mayconbordin-master' 2014-07-12 17:33:31 +10:00
Gareth Jones
4648e7a5e6 Merge branch 'master' of https://github.com/mayconbordin/log4js-node into mayconbordin-master 2014-07-12 17:18:07 +10:00
Gareth Jones
8f3e040786 Merge branch 'RolfKoenders-set-global-log-level' 2014-07-12 17:09:30 +10:00
Gareth Jones
60d2e093ae Merge branch 'set-global-log-level' of https://github.com/RolfKoenders/log4js-node into RolfKoenders-set-global-log-level 2014-07-12 17:08:39 +10:00
Gareth Jones
a06478632e Merge 2ion-gelf-spec-v1.1-compliance into master 2014-07-12 15:12:40 +10:00
Gareth Jones
a4d55b3339 fixed up test after merge 2014-07-12 15:11:21 +10:00
Gareth Jones
914ed5356b Merge pull request #216 from 2ion/gelf-no-full-message
GELF appender: don't send full_message field
2014-07-12 15:02:17 +10:00
Jens John
52b4aa1874 fix uninitialized field error 2014-07-11 19:19:19 +09:00
Jens John
2b0a58c2f2 reflect the above changes ; forgot a facility field 2014-07-11 13:02:06 +09:00
Jens John
fcafed9a7e fix gelfAppender-test.js to reflect the above changes 2014-07-11 12:52:23 +09:00
Jens John
7ff053f104 fix test/gelfAppender-test.js to reflect full_message being gone 2014-07-11 12:38:29 +09:00
Jens John
0f51ab1bb3 GELF appender: set version to 1.1 2014-07-10 14:26:27 +09:00
Jens John
5b2d840472 GELF appender: move facility key into a custom field if present
At the same time, don't assign a default value as the field is optional
according to the GELF spec v1.1.
2014-07-10 14:07:38 +09:00
Jens John
ca635fc4b9 GELF appender: don't send full_message field
According to the GELF spec v1.1 [1], the full_message field in GELF is
optional. The log4js implemention until now has sent identitical
short_message and full_message fields. Since this does not add any new
information to the log message, I suggest that full_message be dropped
from GELF.

--
[1] http://graylog2.org/gelf#specs
2014-07-10 12:17:35 +09:00
Grégoire Charvet 黑瓜
d65d053bc1 Format message before adding loggly metadata
Also removed a throw err inside an asynchronous callback.
2014-07-04 14:03:08 +08:00
Gareth Jones
f44af56f9e Added link to example app. 2014-07-03 08:44:24 +10:00
Gareth Jones
a703f2dc12 0.6.15 2014-07-03 08:16:07 +10:00
Gareth Jones
b2edbb1146 Merge pull request #175 from devotis/master
Loggly appender should not make use of any layout
2014-06-28 08:22:20 +10:00
Gareth Jones
99e7c0981d Merge pull request #189 from jengler/add-support-for-prerequired-appender-styles
Add support for prerequired appender styles
2014-06-28 08:20:12 +10:00
Gareth Jones
06bab894af Merge pull request #203 from idalv/master
Clusterred appender should consider the categories.
2014-06-28 08:17:16 +10:00
Gareth Jones
101739ebef Merge pull request #209 from Icehunter/patch-1
Update for "write after end" uncaught error.
2014-06-28 08:02:27 +10:00
Ryan Wilson
f8ffccffd5 epic day with a forgotten console 2014-06-20 13:23:57 -07:00
Ryan Wilson
7d50b4aeff removed check for writeable
caused broken unit tests
2014-06-20 13:23:09 -07:00
Ryan Wilson
b12200fabc Update for "write after end" uncaught error. 2014-06-20 13:16:23 -07:00
Vladimir Mitev
f8b6cc7c39 Revert "Update connect-logger.js to work correctly with express"
This reverts commit d18fb466fb.
2014-05-26 15:56:23 +03:00
idalv
6314e4a344 Merge pull request #1 from idalv/automation
Update connect-logger.js to work correctly with express
2014-05-26 15:46:07 +03:00
mishless
d18fb466fb Update connect-logger.js to work correctly with express
When used with express levels are wrong since send() does not call writeHead, but sets responseCode on response.
2014-05-23 13:58:52 +03:00
Vladimir Mitev
e638ff7271 Unit test.
Fixed the old unit tests.
Added validation for new functionality.

Signed-off-by: Vladimir Mitev <idalv@users.noreply.github.com>
2014-05-20 14:42:29 +03:00
Vladimir Mitev
2daf29b400 Clusterred appender should consider the categories.
It turns out that whenever the clusterred appender is used the log event is passed to all actual appenders.
The actual appender's category is ignored.

Signed-off-by: Vladimir Mitev <idalv@users.noreply.github.com>
2014-05-20 13:45:46 +03:00
=
8cf03507dd Add unit test to check if the level is set on all categories 2014-05-04 15:20:22 +02:00
Gareth Jones
ca5272aacc 0.6.14 2014-04-22 10:06:04 +10:00
Gareth Jones
614127bb10 added shutdown to datefile 2014-04-22 10:05:37 +10:00
Gareth Jones
a549df44b4 Merge pull request #199 from lulurun/fix_file_appender
fix shutdown method: make sure to callback when write completed immediat...
2014-04-22 09:58:03 +10:00
Gareth Jones
5e0982f0b1 Merge pull request #200 from lulurun/datefile_appender_fix
file won't get rolled if the process restarted daily
2014-04-22 09:29:15 +10:00
Xiaolu Liu
f5a76d9073 file won't get rolled if the process restarted daily 2014-04-24 00:07:11 +09:00
Xiaolu Liu
29d941f0a6 fix shutdown method: make sure to callback when write completed immediately 2014-04-21 16:27:51 +09:00
Gareth Jones
0c2baa9690 0.6.13 2014-04-09 07:44:23 +10:00
Gareth Jones
9b538ee8ed fixed timezone flakiness 2014-04-09 07:43:40 +10:00
Gareth Jones
e4d5228f2b Merge branch 'flush-on-exit' 2014-04-09 07:37:17 +10:00
Gareth Jones
6aacb0da0b Merge pull request #195 from jengler/flush-on-exit
Flush on exit
2014-04-09 07:35:25 +10:00
John Engler
6e3da6f44b Added error throwing when error loading test file.
This will hopefully give us better visibility into our Travis CI
build failures.
2014-04-08 12:40:27 -07:00
John Engler
3b5eb28115 Update dateFile EOL usage to be consistent with appender.
From the looks of the Travis CI failure, this could be the issue
causing failures. Not sure as I can't reproduce locally. However,
it is still an inconsistency and worth fixing.
2014-04-08 10:47:18 -07:00
John Engler
633ed3cddb Support for disabling log writes on shutdown.
Updated logger.js to support disabling all log writes.
Updated log4js.js shutdown function to disable log writes.
Added tests.
Update gitignore to ignore rolling date stream's test output.
2014-04-07 19:06:29 -07:00
John Engler
8ca092cdb9 Removed callback to write, as it is not needed. 2014-04-05 16:14:56 -07:00
John Engler
3ec9811b5e Update log4js module to expose a shutdown function.
loadAppender will check for a shutdown function exposed by
a loaded appender. If present, it will be cached so that the
shutdown function can execute it.

The intent here is that a Node application would not invoked
process.exit until after the log4js shutdown callback returns.
2014-04-05 15:12:45 -07:00
Gareth Jones
c852fceaf4 Update README.md 2014-04-01 11:09:01 +11:00
John Engler
c569919160 Simplied loadAppender logic. 2014-03-11 02:19:00 -07:00
John Engler
28f7c87a0e Allow adding of appenders as objects
Previously, appenders could only be added by specifying the filepath
to the appender. This required the appender's path to be specified
either relative to the log4js installation, relative to a NODE_PATH
token, or absolute. This creates a coupling between the log4js
configurer and the log4js installation location, or a coupling between
the log4js configurer and the global NODE_PATH. This commit removes
the coupling by allowing the loading of appenders to be done relative
to the log4js configurer.
2014-03-11 02:07:58 -07:00
Gareth Jones
492919b940 0.6.12 2014-03-05 13:17:15 +11:00
Gareth Jones
470baa6c09 Merge pull request #187 from jci-fox/addHasLogger
adding ability to check if a logger exists
2014-03-05 13:16:51 +11:00
Gareth Jones
cd2ee14bde 0.6.11 2014-03-05 09:25:03 +11:00
Gareth Jones
c09c11b147 Merge branch 'master' of https://github.com/nomiddlename/log4js-node 2014-03-05 09:24:09 +11:00
Gareth Jones
b74a514369 Merge pull request #186 from jci-fox/issue184_dynamicloglevels
Adding level checks on dynamic logging
2014-03-05 09:17:16 +11:00
jci-fox
fd05d90c2f adding ability to check if a logger exists
This allows for not accidentally adding a non-configured logger
2014-03-04 09:45:56 -06:00
jci-fox
73344ba79f fixing unit test
logger.log requires 2 params, and with the 1st being level and filtering the level, the log call must provide a level that will result in log messages
2014-03-04 09:27:04 -06:00
jci-fox
22c156582f Adding level checks on dynamic logging
using levels.toLevel and this.isLevelEnabled prior to emiting the event will prevent the appenders from being notified if the log level provided is below the loggers level.
2014-03-04 09:08:27 -06:00
Gareth Jones
72bfb5d980 0.6.10 2014-02-11 08:51:21 +11:00
Gareth Jones
83ad0babf3 changed my email address 2014-02-11 08:50:36 +11:00
Rolf Koenders
6ae01b2b84 Update log4js.js
Overlooked that there was already a var with '[all]'.
2014-01-23 10:34:56 +01:00
Rolf Koenders
e7c0b0da52 Changed to only the ‚levels’ option as discussed in #87 2014-01-22 20:13:36 +01:00
Rolf Koenders
25fa48ee8d Set the global level via the configuration object passed to
log4js.configure or target `all` in the `levels` object.
2014-01-21 23:39:54 +01:00
Christiaan Westerbeek
ae1a55fed9 Stop making use of any layout
Stop making use of any layout by default, because they are intended to
format a line for human reading. Loggly indexes the values (of all
properties of objects) and makes them available for querying.
2014-01-21 12:11:32 +01:00
Gareth Jones
94034e1226 Merge pull request #172 from devotis/master
Fork with Loggly appender here
2014-01-16 14:00:16 -08:00
Christiaan Westerbeek
9b4c7d1574 Fixes the error with test/logglyAppender-test
Refs #172

I will add more relevant tests later
2014-01-16 16:39:45 +01:00
Christiaan Westerbeek
770f2da627 Cleanup 2014-01-10 21:59:39 +01:00
Christiaan Westerbeek
eb51aa99be First working version
tried examples/loggly-appender.js [OK]
2014-01-10 21:51:08 +01:00
Christiaan Westerbeek
5286c50375 Added the basic files for Loggly appender
appender, example, test
not tested yet!
2014-01-10 21:18:16 +01:00
Christiaan Westerbeek
bb644a1632 Update README.md
Will try to add a appender for Loggly in this Fork. I will keep it in to this feature alone as outlined in the rules
2014-01-10 20:47:48 +01:00
Gareth Jones
a6efbf6273 Merge pull request #168 from macedigital/connectlogger-ip-fix
fix 'remote-addr' property in connect-logger
2013-12-30 12:40:40 -08:00
Matthias Adler
2118d8f7b3 fix 'remote-addr' property in connect-logger 2013-12-21 19:42:44 +01:00
Maycon Bordin
7fcdb2e651 fixed a issue with the encoding on node 0.8 2013-12-12 22:26:48 -02:00
Maycon Bordin
60a84f16cf added tests for the fileSync appender and changed the behavior of fileSync to create an empty log when called, just like the file appender does 2013-12-12 18:16:53 -02:00
Maycon Bordin
723dbec964 added a synchronous file appender 2013-12-06 12:48:49 -02:00
Gareth Jones
2a38f460dc tried adding process.nexttick - didn't help 2013-08-05 07:56:02 +10:00
Gareth Jones
9f77734f74 test case for flush on exit 2013-08-05 07:55:07 +10:00
Gareth Jones
ce8b6b06b9 trying out a shutdown function 2013-08-05 07:21:12 +10:00
52 changed files with 2077 additions and 598 deletions

2
.gitignore vendored
View File

@@ -4,3 +4,5 @@ build
node_modules
.bob/
test/streams/test-rolling-file-stream*
test/streams/test-rolling-stream-with-existing-files*
.idea

View File

@@ -1,5 +1,6 @@
language: node_js
node_js:
- "0.12"
- "0.10"
- "0.8"

View File

@@ -1,7 +1,7 @@
# log4js-node [![Build Status](https://secure.travis-ci.org/nomiddlename/log4js-node.png?branch=master)](http://travis-ci.org/nomiddlename/log4js-node)
This is a conversion of the [log4js](http://log4js.berlios.de/index.html)
This is a conversion of the [log4js](https://github.com/stritti/log4js)
framework to work with [node](http://nodejs.org). I've mainly stripped out the browser-specific code and tidied up some of the javascript.
Out of the box it supports the following features:
@@ -12,6 +12,8 @@ Out of the box it supports the following features:
* SMTP appender
* GELF appender
* hook.io appender
* Loggly appender
* Logstash UDP appender
* multiprocess appender (useful when you've got worker processes)
* a logger for connect/express servers
* configurable log message layout/patterns
@@ -106,8 +108,9 @@ For FileAppender you can also pass the path to the log directory as an option wh
log4js.configure('my_log4js_configuration.json', { cwd: '/absolute/path/to/log/dir' });
```
If you have already defined an absolute path for one of the FileAppenders in the configuration file, you could add a "absolute": true to the particular FileAppender to override the cwd option passed. Here is an example configuration file:
```json
#### my_log4js_configuration.json ####
```json
{
"appenders": [
{
@@ -133,6 +136,8 @@ Documentation for most of the core appenders can be found on the [wiki](https://
## Documentation
See the [wiki](https://github.com/nomiddlename/log4js-node/wiki). Improve the [wiki](https://github.com/nomiddlename/log4js-node/wiki), please.
There's also [an example application](https://github.com/nomiddlename/log4js-example).
## Contributing
Contributions welcome, but take a look at the [rules](https://github.com/nomiddlename/log4js-node/wiki/Contributing) first.

View File

@@ -35,11 +35,13 @@ logger.setLevel('ERROR');
//console logging methods have been replaced with log4js ones.
//so this will get coloured output on console, and appear in cheese.log
console.error("AAArgh! Something went wrong", { some: "otherObject", useful_for: "debug purposes" });
console.log("This should appear as info output");
//these will not appear (logging level beneath error)
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.log('Something funny about cheese.');
logger.warn('Cheese is quite smelly.');
//these end up on the console and in cheese.log
logger.error('Cheese %s is too ripe!', "gouda");

27
examples/flush-on-exit.js Normal file
View File

@@ -0,0 +1,27 @@
/**
* run this, then "ab -c 10 -n 100 localhost:4444/" to test (in
* another shell)
*/
var log4js = require('../lib/log4js');
log4js.configure({
appenders: [
{ type: 'file', filename: 'cheese.log', category: 'cheese' },
{ type: 'console'}
]
});
var logger = log4js.getLogger('cheese');
logger.setLevel('INFO');
var http=require('http');
var server = http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/plain'});
var rd = Math.random() * 50;
logger.info("hello " + rd);
response.write('hello ');
if (Math.floor(rd) == 30){
log4js.shutdown(function() { process.exit(1); });
}
response.end();
}).listen(4444);

View File

@@ -0,0 +1,24 @@
//Note that loggly appender needs node-loggly to work.
//If you haven't got node-loggly installed, you'll get cryptic
//"cannot find module" errors when using the loggly appender
var log4js = require('../lib/log4js');
log4js.configure({
"appenders": [
{
type: "console",
category: "test"
},
{
"type" : "loggly",
"token" : "12345678901234567890",
"subdomain": "your-subdomain",
"tags" : ["test"],
"category" : "loggly"
}
]
});
var logger = log4js.getLogger("loggly");
logger.info("Test log message");
//logger.debug("Test log message");

39
examples/logstashUDP.js Normal file
View File

@@ -0,0 +1,39 @@
var log4js = require('../lib/log4js');
/*
Sample logstash config:
udp {
codec => json
port => 10001
queue_size => 2
workers => 2
type => myAppType
}
*/
log4js.configure({
"appenders": [
{
type: "console",
category: "myLogger"
},
{
"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
"field1": "value1",
"field2": "value2"
},
"layout": {
"type": "pattern",
"pattern": "%m"
},
"category": "myLogger"
}
]
});
var logger = log4js.getLogger("myLogger");
logger.info("Test log message %s", "arg1", "arg2");

View File

@@ -71,7 +71,10 @@ function createAppender(config) {
if (config.actualAppenders) {
var size = config.actualAppenders.length;
for(var i = 0; i < size; i++) {
config.actualAppenders[i](loggingEvent);
if (!config.appenders[i].category || config.appenders[i].category === loggingEvent.categoryName) {
// Relying on the index is not a good practice but otherwise the change would have been bigger.
config.actualAppenders[i](loggingEvent);
}
}
}
}
@@ -84,6 +87,15 @@ function createAppender(config) {
// console.log("master : " + cluster.isMaster + " received message: " + JSON.stringify(message.event));
var loggingEvent = deserializeLoggingEvent(message.event);
// Adding PID metadata
loggingEvent.pid = worker.process.pid;
loggingEvent.cluster = {
master: process.pid,
worker: worker.process.pid,
workerId: worker.id
};
masterAppender(loggingEvent);
}
});

View File

@@ -2,10 +2,10 @@
var layouts = require('../layouts')
, consoleLog = console.log.bind(console);
function consoleAppender (layout) {
function consoleAppender (layout, timezoneOffset) {
layout = layout || layouts.colouredLayout;
return function(loggingEvent) {
consoleLog(layout(loggingEvent));
consoleLog(layout(loggingEvent, timezoneOffset));
};
}
@@ -14,7 +14,7 @@ function configure(config) {
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
return consoleAppender(layout);
return consoleAppender(layout, config.timezoneOffset);
}
exports.appender = consoleAppender;

View File

@@ -1,6 +1,7 @@
"use strict";
var streams = require('../streams')
, layouts = require('../layouts')
, async = require('async')
, path = require('path')
, os = require('os')
, eol = os.EOL || '\n'
@@ -19,40 +20,54 @@ process.on('exit', function() {
* @pattern the format that will be added to the end of filename when rolling,
* also used to check when to roll files - defaults to '.yyyy-MM-dd'
* @layout layout function for log messages - defaults to basicLayout
* @timezoneOffset optional timezone offset in minutes - defaults to system local
*/
function appender(filename, pattern, alwaysIncludePattern, layout) {
function appender(filename, pattern, alwaysIncludePattern, layout, timezoneOffset) {
layout = layout || layouts.basicLayout;
var logFile = new streams.DateRollingFileStream(
filename,
pattern,
filename,
pattern,
{ alwaysIncludePattern: alwaysIncludePattern }
);
openFiles.push(logFile);
return function(logEvent) {
logFile.write(layout(logEvent) + eol, "utf8");
logFile.write(layout(logEvent, timezoneOffset) + eol, "utf8");
};
}
function configure(config, options) {
var layout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
if (!config.alwaysIncludePattern) {
config.alwaysIncludePattern = false;
}
if (options && options.cwd && !config.absolute) {
config.filename = path.join(options.cwd, config.filename);
}
return appender(config.filename, config.pattern, config.alwaysIncludePattern, layout);
return appender(config.filename, config.pattern, config.alwaysIncludePattern, layout, config.timezoneOffset);
}
function shutdown(cb) {
async.each(openFiles, function(file, done) {
if (!file.write(eol, "utf-8")) {
file.once('drain', function() {
file.end(done);
});
} else {
file.end(done);
}
}, cb);
}
exports.appender = appender;
exports.configure = configure;
exports.shutdown = shutdown;

View File

@@ -1,11 +1,13 @@
"use strict";
var layouts = require('../layouts')
, async = require('async')
, path = require('path')
, fs = require('fs')
, streams = require('../streams')
, os = require('os')
, eol = os.EOL || '\n'
, openFiles = [];
, openFiles = []
, levels = require('../levels');
//close open files on process exit.
process.on('exit', function() {
@@ -24,8 +26,10 @@ process.on('exit', function() {
* if not provided then logs won't be rotated.
* @param numBackups - the number of log files to keep after logSize
* has been reached (default 5)
* @param compress - flag that controls log file compression
* @param timezoneOffset - optional timezone offset in minutes (default system local)
*/
function fileAppender (file, layout, logSize, numBackups) {
function fileAppender (file, layout, logSize, numBackups, compress, timezoneOffset) {
var bytesWritten = 0;
file = path.normalize(file);
layout = layout || layouts.basicLayout;
@@ -39,7 +43,8 @@ function fileAppender (file, layout, logSize, numBackups) {
stream = new streams.RollingFileStream(
file,
fileSize,
numFiles
numFiles,
{ "compress": compress }
);
} else {
stream = fs.createWriteStream(
@@ -59,10 +64,11 @@ function fileAppender (file, layout, logSize, numBackups) {
// push file to the stack of open handlers
openFiles.push(logFile);
return function(loggingEvent) {
logFile.write(layout(loggingEvent) + eol, "utf8");
logFile.write(layout(loggingEvent, timezoneOffset) + eol, "utf8");
};
}
function configure(config, options) {
@@ -75,8 +81,21 @@ function configure(config, options) {
config.filename = path.join(options.cwd, config.filename);
}
return fileAppender(config.filename, layout, config.maxLogSize, config.backups);
return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config.compress, config.timezoneOffset);
}
function shutdown(cb) {
async.each(openFiles, function(file, done) {
if (!file.write(eol, "utf-8")) {
file.once('drain', function() {
file.end(done);
});
} else {
file.end(done);
}
}, cb);
}
exports.appender = fileAppender;
exports.configure = configure;
exports.shutdown = shutdown;

189
lib/appenders/fileSync.js Executable file
View File

@@ -0,0 +1,189 @@
"use strict";
var debug = require('../debug')('fileSync')
, layouts = require('../layouts')
, path = require('path')
, fs = require('fs')
, streams = require('../streams')
, os = require('os')
, eol = os.EOL || '\n'
;
function RollingFileSync (filename, size, backups, options) {
debug("In RollingFileStream");
function throwErrorIfArgumentsAreNotValid() {
if (!filename || !size || size <= 0) {
throw new Error("You must specify a filename and file size");
}
}
throwErrorIfArgumentsAreNotValid();
this.filename = filename;
this.size = size;
this.backups = backups || 1;
this.options = options || { encoding: 'utf8', mode: parseInt('0644', 8), flags: 'a' };
this.currentSize = 0;
function currentFileSize(file) {
var fileSize = 0;
try {
fileSize = fs.statSync(file).size;
} catch (e) {
// file does not exist
fs.appendFileSync(filename, '');
}
return fileSize;
}
this.currentSize = currentFileSize(this.filename);
}
RollingFileSync.prototype.shouldRoll = function() {
debug("should roll with current size %d, and max size %d", this.currentSize, this.size);
return this.currentSize >= this.size;
};
RollingFileSync.prototype.roll = function(filename) {
var that = this,
nameMatcher = new RegExp('^' + path.basename(filename));
function justTheseFiles (item) {
return nameMatcher.test(item);
}
function index(filename_) {
return parseInt(filename_.substring((path.basename(filename) + '.').length), 10) || 0;
}
function byIndex(a, b) {
if (index(a) > index(b)) {
return 1;
} else if (index(a) < index(b) ) {
return -1;
} else {
return 0;
}
}
function increaseFileIndex (fileToRename) {
var idx = index(fileToRename);
debug('Index of ' + fileToRename + ' is ' + idx);
if (idx < that.backups) {
//on windows, you can get a EEXIST error if you rename a file to an existing file
//so, we'll try to delete the file we're renaming to first
try {
fs.unlinkSync(filename + '.' + (idx+1));
} catch(e) {
//ignore err: if we could not delete, it's most likely that it doesn't exist
}
debug('Renaming ' + fileToRename + ' -> ' + filename + '.' + (idx+1));
fs.renameSync(path.join(path.dirname(filename), fileToRename), filename + '.' + (idx + 1));
}
}
function renameTheFiles() {
//roll the backups (rename file.n to file.n+1, where n <= numBackups)
debug("Renaming the old files");
var files = fs.readdirSync(path.dirname(filename));
files.filter(justTheseFiles).sort(byIndex).reverse().forEach(increaseFileIndex);
}
debug("Rolling, rolling, rolling");
renameTheFiles();
};
RollingFileSync.prototype.write = function(chunk, encoding) {
var that = this;
function writeTheChunk() {
debug("writing the chunk to the file");
that.currentSize += chunk.length;
fs.appendFileSync(that.filename, chunk);
}
debug("in write");
if (this.shouldRoll()) {
this.currentSize = 0;
this.roll(this.filename);
}
writeTheChunk();
};
/**
* File Appender writing the logs to a text file. Supports rolling of logs by size.
*
* @param file file log messages will be written to
* @param layout a function that takes a logevent and returns a string
* (defaults to basicLayout).
* @param logSize - the maximum size (in bytes) for a log file,
* if not provided then logs won't be rotated.
* @param numBackups - the number of log files to keep after logSize
* has been reached (default 5)
* @param timezoneOffset - optional timezone offset in minutes
* (default system local)
*/
function fileAppender (file, layout, logSize, numBackups, timezoneOffset) {
debug("fileSync appender created");
var bytesWritten = 0;
file = path.normalize(file);
layout = layout || layouts.basicLayout;
numBackups = numBackups === undefined ? 5 : numBackups;
//there has to be at least one backup if logSize has been specified
numBackups = numBackups === 0 ? 1 : numBackups;
function openTheStream(file, fileSize, numFiles) {
var stream;
if (fileSize) {
stream = new RollingFileSync(
file,
fileSize,
numFiles
);
} else {
stream = (function(f) {
// create file if it doesn't exist
if (!fs.existsSync(f))
fs.appendFileSync(f, '');
return {
write: function(data) {
fs.appendFileSync(f, data);
}
};
})(file);
}
return stream;
}
var logFile = openTheStream(file, logSize, numBackups);
return function(loggingEvent) {
logFile.write(layout(loggingEvent, timezoneOffset) + eol);
};
}
function configure(config, options) {
var layout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
if (options && options.cwd && !config.absolute) {
config.filename = path.join(options.cwd, config.filename);
}
return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config.timezoneOffset);
}
exports.appender = fileAppender;
exports.configure = configure;

View File

@@ -48,11 +48,14 @@ function gelfAppender (layout, host, port, hostname, facility) {
host = host || 'localhost';
port = port || 12201;
hostname = hostname || require('os').hostname();
facility = facility || 'nodejs-server';
layout = layout || layouts.messagePassThroughLayout;
var defaultCustomFields = customFields || {};
if(facility) {
defaultCustomFields['_facility'] = facility;
}
var client = dgram.createSocket("udp4");
process.on('exit', function() {
@@ -82,6 +85,8 @@ function gelfAppender (layout, host, port, hostname, facility) {
var firstData = data[0];
if (!firstData.GELF) return; // identify with GELF field defined
// Remove the GELF key, some gelf supported logging systems drop the message with it
delete firstData.GELF;
Object.keys(firstData).forEach(function(key) {
// skip _id field for graylog2, skip keys not starts with UNDERSCORE
if (key.match(/^_/) || key !== "_id") {
@@ -96,14 +101,12 @@ function gelfAppender (layout, host, port, hostname, facility) {
function preparePacket(loggingEvent) {
var msg = {};
addCustomFields(loggingEvent, msg);
msg.full_message = layout(loggingEvent);
msg.short_message = msg.full_message;
msg.short_message = layout(loggingEvent);
msg.version="1.0";
msg.version="1.1";
msg.timestamp = msg.timestamp || new Date().getTime() / 1000; // log should use millisecond
msg.host = hostname;
msg.level = levelMapping[loggingEvent.level || levels.DEBUG];
msg.facility = facility;
return msg;
}

View File

@@ -1,76 +0,0 @@
"use strict";
var log4js = require('../log4js')
, layouts = require('../layouts')
, Hook = require('hook.io').Hook
, util = require('util');
var Logger = function createLogger(options) {
var self = this;
var actualAppender = options.actualAppender;
Hook.call(self, options);
self.on('hook::ready', function hookReady() {
self.on('*::' + options.name + '::log', function log(loggingEvent) {
deserializeLoggingEvent(loggingEvent);
actualAppender(loggingEvent);
});
});
};
util.inherits(Logger, Hook);
function deserializeLoggingEvent(loggingEvent) {
loggingEvent.startTime = new Date(loggingEvent.startTime);
loggingEvent.level.toString = function levelToString() {
return loggingEvent.level.levelStr;
};
}
function initHook(hookioOptions) {
var loggerHook;
if (hookioOptions.mode === 'master') {
// Start the master hook, handling the actual logging
loggerHook = new Logger(hookioOptions);
} else {
// Start a worker, just emitting events for a master
loggerHook = new Hook(hookioOptions);
}
loggerHook.start();
return loggerHook;
}
function getBufferedHook(hook, eventName) {
var hookBuffer = [];
var hookReady = false;
hook.on('hook::ready', function emptyBuffer() {
hookBuffer.forEach(function logBufferItem(loggingEvent) {
hook.emit(eventName, loggingEvent);
});
hookReady = true;
});
return function log(loggingEvent) {
if (hookReady) {
hook.emit(eventName, loggingEvent);
} else {
hookBuffer.push(loggingEvent);
}
};
}
function createAppender(hookioOptions) {
var loggerHook = initHook(hookioOptions);
var loggerEvent = hookioOptions.name + '::log';
return getBufferedHook(loggerHook, loggerEvent);
}
function configure(config) {
var actualAppender;
if (config.appender && config.mode === 'master') {
log4js.loadAppender(config.appender.type);
actualAppender = log4js.appenderMakers[config.appender.type](config.appender);
config.actualAppender = actualAppender;
}
return createAppender(config);
}
exports.appender = createAppender;
exports.configure = configure;

View File

@@ -2,19 +2,21 @@
var levels = require('../levels')
, log4js = require('../log4js');
function logLevelFilter (levelString, appender) {
var level = levels.toLevel(levelString);
function logLevelFilter (minLevelString, maxLevelString, appender) {
var minLevel = levels.toLevel(minLevelString);
var maxLevel = levels.toLevel(maxLevelString, levels.FATAL);
return function(logEvent) {
if (logEvent.level.isGreaterThanOrEqualTo(level)) {
var eventLevel = logEvent.level;
if (eventLevel.isGreaterThanOrEqualTo(minLevel) && eventLevel.isLessThanOrEqualTo(maxLevel)) {
appender(logEvent);
}
};
}
function configure(config) {
function configure(config, options) {
log4js.loadAppender(config.appender.type);
var appender = log4js.appenderMakers[config.appender.type](config.appender);
return logLevelFilter(config.level, appender);
var appender = log4js.appenderMakers[config.appender.type](config.appender, options);
return logLevelFilter(config.level, config.maxLevel, appender);
}
exports.appender = logLevelFilter;

44
lib/appenders/loggly.js Normal file
View File

@@ -0,0 +1,44 @@
'use strict';
var layouts = require('../layouts')
, loggly = require('loggly')
, os = require('os')
, passThrough = layouts.messagePassThroughLayout;
/**
* Loggly Appender. Sends logging events to Loggly using node-loggly
*
* @param config object with loggly configuration data
* {
* token: 'your-really-long-input-token',
* subdomain: 'your-subdomain',
* tags: ['loggly-tag1', 'loggly-tag2', .., 'loggly-tagn']
* }
* @param layout a function that takes a logevent and returns a string (defaults to objectLayout).
*/
function logglyAppender(config, layout) {
var client = loggly.createClient(config);
if(!layout) layout = passThrough;
return function(loggingEvent) {
var msg = layout(loggingEvent);
client.log({
msg: msg,
level: loggingEvent.level.levelStr,
category: loggingEvent.categoryName,
hostname: os.hostname().toString(),
});
}
}
function configure(config) {
var layout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
return logglyAppender(config, layout);
}
exports.name = 'loggly';
exports.appender = logglyAppender;
exports.configure = configure;

View File

@@ -0,0 +1,50 @@
"use strict";
var layouts = require('../layouts')
, dgram = require('dgram')
, util = require('util');
function logstashUDP (config, layout) {
var udp = dgram.createSocket('udp4');
var type = config.logType ? config.logType : config.category;
layout = layout || layouts.colouredLayout;
if(!config.fields) {
config.fields = {};
}
return function(loggingEvent) {
var logMessage = layout(loggingEvent);
var fields = {};
for(var i in config.fields) {
fields[i] = config.fields[i];
}
fields['level'] = loggingEvent.level.levelStr;
var logObject = {
'@timestamp': (new Date(loggingEvent.startTime)).toISOString(),
type: type,
message: logMessage,
fields: fields
};
sendLog(udp, config.host, config.port, logObject);
};
}
function sendLog(udp, host, port, logObject) {
var buffer = new Buffer(JSON.stringify(logObject));
udp.send(buffer, 0, buffer.length, port, host, function(err, bytes) {
if(err) {
console.error(
"log4js.logstashUDP - %s:%p Error: %s", host, port, util.inspect(err)
);
}
});
}
function configure(config) {
var layout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
return logstashUDP(config, layout);
}
exports.appender = logstashUDP;
exports.configure = configure;

View File

@@ -1,7 +1,10 @@
"use strict";
var layouts = require("../layouts")
, mailer = require("nodemailer")
, os = require('os');
, os = require('os')
, async = require('async')
, unsentCount = 0
, shutdownTimeout;
/**
* SMTP Appender. Sends logging events using SMTP protocol.
@@ -11,6 +14,7 @@ var layouts = require("../layouts")
* @param config appender configuration data
* config.sendInterval time between log emails (in seconds), if 0
* then every event sends an email
* config.shutdownTimeout time to give up remaining emails (in seconds; defaults to 5).
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
*/
function smtpAppender(config, layout) {
@@ -21,22 +25,31 @@ function smtpAppender(config, layout) {
var logEventBuffer = [];
var sendTimer;
shutdownTimeout = ('shutdownTimeout' in config ? config.shutdownTimeout : 5) * 1000;
function sendBuffer() {
if (logEventBuffer.length > 0) {
var transport = mailer.createTransport(config.transport, config[config.transport]);
var transport = mailer.createTransport(config.SMTP);
var firstEvent = logEventBuffer[0];
var body = "";
var count = logEventBuffer.length;
while (logEventBuffer.length > 0) {
body += layout(logEventBuffer.shift()) + "\n";
body += layout(logEventBuffer.shift(), config.timezoneOffset) + "\n";
}
var msg = {
to: config.recipients,
subject: config.subject || subjectLayout(firstEvent),
text: body,
headers: { "Hostname": os.hostname() }
};
if (!config.html) {
msg.text = body;
} else {
msg.html = body;
}
if (config.sender) {
msg.from = config.sender;
}
@@ -45,6 +58,7 @@ function smtpAppender(config, layout) {
console.error("log4js.smtpAppender - Error happened", error);
}
transport.close();
unsentCount -= count;
});
}
}
@@ -59,6 +73,7 @@ function smtpAppender(config, layout) {
}
return function(loggingEvent) {
unsentCount++;
logEventBuffer.push(loggingEvent);
if (sendInterval > 0) {
scheduleSend();
@@ -76,7 +91,19 @@ function configure(config) {
return smtpAppender(config, layout);
}
function shutdown(cb) {
if (shutdownTimeout > 0) {
setTimeout(function() { unsentCount = 0; }, shutdownTimeout);
}
async.whilst(function() {
return unsentCount > 0;
}, function(done) {
setTimeout(done, 100);
}, cb);
}
exports.name = "smtp";
exports.appender = smtpAppender;
exports.configure = configure;
exports.shutdown = shutdown;

View File

@@ -1,8 +1,9 @@
"use strict";
var levels = require("./levels");
var DEFAULT_FORMAT = ':remote-addr - -' +
' ":method :url HTTP/:http-version"' +
' :status :content-length ":referrer"' +
var _ = require('underscore');
var DEFAULT_FORMAT = ':remote-addr - -' +
' ":method :url HTTP/:http-version"' +
' :status :content-length ":referrer"' +
' ":user-agent"';
/**
* Log requests with the given `options` or a `format` string.
@@ -52,16 +53,15 @@ function getLogger(logger4js, options) {
// nologs
if (nolog && nolog.test(req.originalUrl)) return next();
if (thislogger.isLevelEnabled(level) || options.level === 'auto') {
var start = new Date()
, statusCode
, writeHead = res.writeHead
, end = res.end
, url = req.originalUrl;
// flag as logging
req._logging = true;
// proxy for statusCode.
res.writeHead = function(code, headers){
res.writeHead = writeHead;
@@ -78,28 +78,79 @@ function getLogger(logger4js, options) {
level = levels.toLevel(options.level, levels.INFO);
}
};
// proxy end to output a line to the provided logger.
res.end = function(chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
//hook on end request to emit the log entry of the HTTP request.
res.on('finish', function() {
res.responseTime = new Date() - start;
//status code response level handling
if(res.statusCode && options.level === 'auto'){
level = levels.INFO;
if(res.statusCode >= 300) level = levels.WARN;
if(res.statusCode >= 400) level = levels.ERROR;
}
if (thislogger.isLevelEnabled(level)) {
var combined_tokens = assemble_tokens(req, res, options.tokens || []);
if (typeof fmt === 'function') {
var line = fmt(req, res, function(str){ return format(str, req, res); });
var line = fmt(req, res, function(str){ return format(str, combined_tokens); });
if (line) thislogger.log(level, line);
} else {
thislogger.log(level, format(fmt, req, res));
thislogger.log(level, format(fmt, combined_tokens));
}
}
};
});
}
//ensure next gets always called
next();
};
}
/**
* Adds custom {token, replacement} objects to defaults, overwriting the defaults if any tokens clash
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Array} custom_tokens [{ token: string-or-regexp, replacement: string-or-replace-function }]
* @return {Array}
*/
function assemble_tokens(req, res, custom_tokens) {
var array_unique_tokens = function(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i].token == a[j].token) { // not === because token can be regexp object
a.splice(j--, 1);
}
}
}
return a;
};
var default_tokens = [];
default_tokens.push({ token: ':url', replacement: req.originalUrl });
default_tokens.push({ token: ':method', replacement: req.method });
default_tokens.push({ token: ':status', replacement: res.__statusCode || res.statusCode });
default_tokens.push({ token: ':response-time', replacement: res.responseTime });
default_tokens.push({ token: ':date', replacement: new Date().toUTCString() });
default_tokens.push({ token: ':referrer', replacement: req.headers.referer || req.headers.referrer || '' });
default_tokens.push({ token: ':http-version', replacement: req.httpVersionMajor + '.' + req.httpVersionMinor });
default_tokens.push({ token: ':remote-addr', replacement: req.headers['x-forwarded-for'] || req.ip || req._remoteAddress ||
(req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress))) });
default_tokens.push({ token: ':user-agent', replacement: req.headers['user-agent'] });
default_tokens.push({ token: ':content-length', replacement: (res._headers && res._headers['content-length']) ||
(res.__headers && res.__headers['Content-Length']) || '-' });
default_tokens.push({ token: /:req\[([^\]]+)\]/g, replacement: function(_, field) {
return req.headers[field.toLowerCase()];
} });
default_tokens.push({ token: /:res\[([^\]]+)\]/g, replacement: function(_, field) {
return res._headers ?
(res._headers[field.toLowerCase()] || res.__headers[field])
: (res.__headers && res.__headers[field]);
} });
return array_unique_tokens(custom_tokens.concat(default_tokens));
};
/**
* Return formatted log line.
*
@@ -110,33 +161,10 @@ function getLogger(logger4js, options) {
* @api private
*/
function format(str, req, res) {
return str
.replace(':url', req.originalUrl)
.replace(':method', req.method)
.replace(':status', res.__statusCode || res.statusCode)
.replace(':response-time', res.responseTime)
.replace(':date', new Date().toUTCString())
.replace(':referrer', req.headers.referer || req.headers.referrer || '')
.replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor)
.replace(
':remote-addr',
req.socket &&
(req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress))
)
.replace(':user-agent', req.headers['user-agent'] || '')
.replace(
':content-length',
(res._headers && res._headers['content-length']) ||
(res.__headers && res.__headers['Content-Length']) ||
'-'
)
.replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; })
.replace(/:res\[([^\]]+)\]/g, function(_, field){
return res._headers ?
(res._headers[field.toLowerCase()] || res.__headers[field])
: (res.__headers && res.__headers[field]);
});
function format(str, tokens) {
return _.reduce(tokens, function(current_string, token) {
return current_string.replace(token.token, token.replacement);
}, str);
}
/**
@@ -152,9 +180,9 @@ function format(str, req, res) {
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga
* LOGGING http://example.com/hoge.agif
* 1.2 in "\\.gif|\\.jpg$"
* NOT LOGGING http://example.com/hoge.gif and
* NOT LOGGING http://example.com/hoge.gif and
* http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga
* LOGGING http://example.com/hoge.agif,
* LOGGING http://example.com/hoge.agif,
* http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge
* 1.3 in "\\.(gif|jpe?g|png)$"
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg
@@ -172,15 +200,15 @@ function createNoLogCondition(nolog) {
if (nolog) {
if (nolog instanceof RegExp) {
regexp = nolog;
}
}
if (typeof nolog === 'string') {
regexp = new RegExp(nolog);
}
if (Array.isArray(nolog)) {
var regexpsAsStrings = nolog.map(
function convertToStrings(o) {
function convertToStrings(o) {
return o.source ? o.source : o;
}
);

View File

@@ -21,9 +21,9 @@ function addZero(vNumber) {
* Thanks to http://www.svendtofte.com/code/date_format/
* @private
*/
function offset(date) {
function offset(timezoneOffset) {
// Difference to Greenwich time (GMT) in hours
var os = Math.abs(date.getTimezoneOffset());
var os = Math.abs(timezoneOffset);
var h = String(Math.floor(os/60));
var m = String(os%60);
if (h.length == 1) {
@@ -32,26 +32,32 @@ function offset(date) {
if (m.length == 1) {
m = "0" + m;
}
return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
return timezoneOffset < 0 ? "+"+h+m : "-"+h+m;
}
exports.asString = function(/*format,*/ date) {
exports.asString = function(/*format,*/ date, timezoneOffset) {
var format = exports.ISO8601_FORMAT;
if (typeof(date) === "string") {
format = arguments[0];
date = arguments[1];
timezoneOffset = arguments[2];
}
var vDay = addZero(date.getDate());
var vMonth = addZero(date.getMonth()+1);
var vYearLong = addZero(date.getFullYear());
var vYearShort = addZero(date.getFullYear().toString().substring(2,4));
// make the date independent of the system timezone by working with UTC
if (timezoneOffset === undefined) {
timezoneOffset = date.getTimezoneOffset();
}
date.setUTCMinutes(date.getUTCMinutes() - timezoneOffset);
var vDay = addZero(date.getUTCDate());
var vMonth = addZero(date.getUTCMonth()+1);
var vYearLong = addZero(date.getUTCFullYear());
var vYearShort = addZero(date.getUTCFullYear().toString().substring(2,4));
var vYear = (format.indexOf("yyyy") > -1 ? vYearLong : vYearShort);
var vHour = addZero(date.getHours());
var vMinute = addZero(date.getMinutes());
var vSecond = addZero(date.getSeconds());
var vMillisecond = padWithZeros(date.getMilliseconds(), 3);
var vTimeZone = offset(date);
var vHour = addZero(date.getUTCHours());
var vMinute = addZero(date.getUTCMinutes());
var vSecond = addZero(date.getUTCSeconds());
var vMillisecond = padWithZeros(date.getUTCMilliseconds(), 3);
var vTimeZone = offset(timezoneOffset);
date.setUTCMinutes(date.getUTCMinutes() + timezoneOffset);
var formatted = format
.replace(/dd/g, vDay)
.replace(/MM/g, vMonth)

View File

@@ -71,11 +71,11 @@ function colorize (str, style) {
return colorizeStart(style) + str + colorizeEnd(style);
}
function timestampLevelAndCategory(loggingEvent, colour) {
function timestampLevelAndCategory(loggingEvent, colour, timezoneOffest) {
var output = colorize(
formatLogData(
'[%s] [%s] %s - '
, dateFormat.asString(loggingEvent.startTime)
, dateFormat.asString(loggingEvent.startTime, timezoneOffest)
, loggingEvent.level
, loggingEvent.categoryName
)
@@ -93,18 +93,19 @@ function timestampLevelAndCategory(loggingEvent, colour) {
*
* @author Stephan Strittmatter
*/
function basicLayout (loggingEvent) {
return timestampLevelAndCategory(loggingEvent) + formatLogData(loggingEvent.data);
function basicLayout (loggingEvent, timezoneOffset) {
return timestampLevelAndCategory(loggingEvent, undefined, timezoneOffset) + formatLogData(loggingEvent.data);
}
/**
* colouredLayout - taken from masylum's fork.
* same as basicLayout, but with colours.
*/
function colouredLayout (loggingEvent) {
function colouredLayout (loggingEvent, timezoneOffset) {
return timestampLevelAndCategory(
loggingEvent,
colours[loggingEvent.level.toString()]
colours[loggingEvent.level.toString()],
timezoneOffset
) + formatLogData(loggingEvent.data);
}
@@ -125,6 +126,7 @@ function messagePassThroughLayout (loggingEvent) {
* - %d date in various formats
* - %% %
* - %n newline
* - %z pid
* - %x{<tokenname>} add dynamic tokens to your log. Tokens are specified in the tokens parameter
* You can use %[ and %] to define a colored block.
*
@@ -138,13 +140,14 @@ function messagePassThroughLayout (loggingEvent) {
* Takes a pattern string, array of tokens and returns a layout function.
* @param {String} Log format pattern String
* @param {object} map object of different tokens
* @param {number} timezone offset in minutes
* @return {Function}
* @author Stephan Strittmatter
* @author Jan Schmidle
*/
function patternLayout (pattern, tokens) {
function patternLayout (pattern, tokens, timezoneOffset) {
var TTCC_CONVERSION_PATTERN = "%r %p %c - %m%n";
var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([\[\]cdhmnprx%])(\{([^\}]+)\})?|([^%]+)/;
var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([\[\]cdhmnprzxy%])(\{([^\}]+)\})?|([^%]+)/;
pattern = pattern || TTCC_CONVERSION_PATTERN;
@@ -176,7 +179,7 @@ function patternLayout (pattern, tokens) {
}
}
// Format the date
return dateFormat.asString(format, loggingEvent.startTime);
return dateFormat.asString(format, loggingEvent.startTime, timezoneOffset);
}
function hostname() {
@@ -196,7 +199,7 @@ function patternLayout (pattern, tokens) {
}
function startTime(loggingEvent) {
return "" + loggingEvent.startTime.toLocaleTimeString();
return dateFormat.asString('hh:mm:ss', loggingEvent.startTime, timezoneOffset);
}
function startColour(loggingEvent) {
@@ -211,6 +214,27 @@ function patternLayout (pattern, tokens) {
return '%';
}
function pid(loggingEvent) {
if (loggingEvent && loggingEvent.pid) {
return loggingEvent.pid;
} else {
return process.pid;
}
}
function clusterInfo(loggingEvent, specifier) {
if (loggingEvent.cluster && specifier) {
return specifier
.replace('%m', loggingEvent.cluster.master)
.replace('%w', loggingEvent.cluster.worker)
.replace('%i', loggingEvent.cluster.workerId);
} else if (loggingEvent.cluster) {
return loggingEvent.cluster.worker+'@'+loggingEvent.cluster.master;
} else {
return pid();
}
}
function userDefined(loggingEvent, specifier) {
if (typeof(tokens[specifier]) !== 'undefined') {
if (typeof(tokens[specifier]) === 'function') {
@@ -232,6 +256,8 @@ function patternLayout (pattern, tokens) {
'r': startTime,
'[': startColour,
']': endColour,
'y': clusterInfo,
'z': pid,
'%': percent,
'x': userDefined
};
@@ -289,9 +315,7 @@ function patternLayout (pattern, tokens) {
} else {
// Create a raw replacement string based on the conversion
// character and specifier
var replacement =
replaceToken(conversionCharacter, loggingEvent, specifier) ||
matchedString;
var replacement = replaceToken(conversionCharacter, loggingEvent, specifier);
// Format the replacement according to any padding or
// truncation specified

View File

@@ -63,6 +63,7 @@ module.exports = {
WARN: new Level(30000, "WARN"),
ERROR: new Level(40000, "ERROR"),
FATAL: new Level(50000, "FATAL"),
MARK: new Level(9007199254740992, "MARK"), // 2^53
OFF: new Level(Number.MAX_VALUE, "OFF"),
toLevel: toLevel
};

View File

@@ -44,17 +44,20 @@
* Website: http://log4js.berlios.de
*/
var events = require('events')
, async = require('async')
, fs = require('fs')
, path = require('path')
, util = require('util')
, layouts = require('./layouts')
, levels = require('./levels')
, LoggingEvent = require('./logger').LoggingEvent
, Logger = require('./logger').Logger
, loggerModule = require('./logger')
, LoggingEvent = loggerModule.LoggingEvent
, Logger = loggerModule.Logger
, ALL_CATEGORIES = '[all]'
, appenders = {}
, loggers = {}
, appenderMakers = {}
, appenderShutdowns = {}
, defaultConfig = {
appenders: [
{ type: "console" }
@@ -62,38 +65,103 @@ var events = require('events')
replaceConsole: false
};
require('./appenders/console');
function hasLogger(logger) {
return loggers.hasOwnProperty(logger);
}
function getBufferedLogger(categoryName) {
var base_logger = getLogger(categoryName);
var logger = {};
logger.temp = [];
logger.target = base_logger;
logger.flush = function () {
for (var i = 0; i < logger.temp.length; i++) {
var log = logger.temp[i];
logger.target[log.level](log.message);
delete logger.temp[i];
}
};
logger.trace = function (message) { logger.temp.push({level: 'trace', message: message}); };
logger.debug = function (message) { logger.temp.push({level: 'debug', message: message}); };
logger.info = function (message) { logger.temp.push({level: 'info', message: message}); };
logger.warn = function (message) { logger.temp.push({level: 'warn', message: message}); };
logger.error = function (message) { logger.temp.push({level: 'error', message: message}); };
logger.fatal = function (message) { logger.temp.push({level: 'fatal', message: message}); };
return logger;
}
function normalizeCategory (category) {
return category + '.';
}
function doesLevelEntryContainsLogger (levelCategory, loggerCategory) {
var normalizedLevelCategory = normalizeCategory(levelCategory);
var normalizedLoggerCategory = normalizeCategory(loggerCategory);
return normalizedLoggerCategory.substring(0, normalizedLevelCategory.length) == normalizedLevelCategory;
}
function doesAppenderContainsLogger (appenderCategory, loggerCategory) {
var normalizedAppenderCategory = normalizeCategory(appenderCategory);
var normalizedLoggerCategory = normalizeCategory(loggerCategory);
return normalizedLoggerCategory.substring(0, normalizedAppenderCategory.length) == normalizedAppenderCategory;
}
/**
* Get a logger instance. Instance is cached on categoryName level.
* @param {String} categoryName name of category to log to.
* @return {Logger} instance of logger for the category
* @static
*/
function getLogger (categoryName) {
function getLogger (loggerCategoryName) {
// Use default logger if categoryName is not specified or invalid
if (typeof categoryName !== "string") {
categoryName = Logger.DEFAULT_CATEGORY;
if (typeof loggerCategoryName !== "string") {
loggerCategoryName = Logger.DEFAULT_CATEGORY;
}
var appenderList;
if (!loggers[categoryName]) {
if (!hasLogger(loggerCategoryName)) {
var level = undefined;
// If there's a "levels" entry in the configuration
if (levels.config) {
// Goes through the categories in the levels configuration entry, starting by the "higher" ones.
var keys = Object.keys(levels.config).sort();
for (var idx = 0; idx < keys.length; idx++) {
var levelCategory = keys[idx];
if (doesLevelEntryContainsLogger(levelCategory, loggerCategoryName)) {
// level for the logger
level = levels.config[levelCategory];
}
}
}
// Create the logger for this name if it doesn't already exist
loggers[categoryName] = new Logger(categoryName);
if (appenders[categoryName]) {
appenderList = appenders[categoryName];
appenderList.forEach(function(appender) {
loggers[categoryName].addListener("log", appender);
});
loggers[loggerCategoryName] = new Logger(loggerCategoryName, level);
var appenderList;
for(var appenderCategory in appenders) {
if (doesAppenderContainsLogger(appenderCategory, loggerCategoryName)) {
appenderList = appenders[appenderCategory];
appenderList.forEach(function(appender) {
loggers[loggerCategoryName].addListener("log", appender);
});
}
}
if (appenders[ALL_CATEGORIES]) {
appenderList = appenders[ALL_CATEGORIES];
appenderList.forEach(function(appender) {
loggers[categoryName].addListener("log", appender);
loggers[loggerCategoryName].addListener("log", appender);
});
}
}
return loggers[categoryName];
return loggers[loggerCategoryName];
}
/**
@@ -110,20 +178,26 @@ function addAppender () {
args = args[0];
}
args.forEach(function(category) {
addAppenderToCategory(appender, category);
args.forEach(function(appenderCategory) {
addAppenderToCategory(appender, appenderCategory);
if (category === ALL_CATEGORIES) {
if (appenderCategory === ALL_CATEGORIES) {
addAppenderToAllLoggers(appender);
} else if (loggers[category]) {
loggers[category].addListener("log", appender);
} else {
for(var loggerCategory in loggers) {
if (doesAppenderContainsLogger(appenderCategory,loggerCategory)) {
loggers[loggerCategory].addListener("log", appender);
}
}
}
});
}
function addAppenderToAllLoggers(appender) {
for (var logger in loggers) {
if (loggers.hasOwnProperty(logger)) {
if (hasLogger(logger)) {
loggers[logger].addListener("log", appender);
}
}
@@ -139,7 +213,7 @@ function addAppenderToCategory(appender, category) {
function clearAppenders () {
appenders = {};
for (var logger in loggers) {
if (loggers.hasOwnProperty(logger)) {
if (hasLogger(logger)) {
loggers[logger].removeAllListeners("log");
}
}
@@ -162,11 +236,19 @@ function configureAppenders(appenderList, options) {
}
}
function configureLevels(levels) {
if (levels) {
for (var category in levels) {
if (levels.hasOwnProperty(category)) {
getLogger(category).setLevel(levels[category]);
function configureLevels(_levels) {
levels.config = _levels; // Keep it so we can create loggers later using this cfg
if (_levels) {
var keys = Object.keys(levels.config).sort();
for (var idx in keys) {
var category = keys[idx];
if(category === ALL_CATEGORIES) {
setGlobalLogLevel(_levels[category]);
}
for(var loggerCategory in loggers) {
if (doesLevelEntryContainsLogger(category, loggerCategory)) {
loggers[loggerCategory].setLevel(_levels[category]);
}
}
}
}
@@ -197,8 +279,8 @@ function loadConfigurationFile(filename) {
function configureOnceOff(config, options) {
if (config) {
try {
configureAppenders(config.appenders, options);
configureLevels(config.levels);
configureAppenders(config.appenders, options);
if (config.replaceConsole) {
replaceConsole();
@@ -214,12 +296,12 @@ function configureOnceOff(config, options) {
}
}
function reloadConfiguration() {
function reloadConfiguration(options) {
var mtime = getMTime(configState.filename);
if (!mtime) return;
if (configState.lastMTime && (mtime.getTime() > configState.lastMTime.getTime())) {
configureOnceOff(loadConfigurationFile(configState.filename));
configureOnceOff(loadConfigurationFile(configState.filename), options);
}
configState.lastMTime = mtime;
}
@@ -241,7 +323,7 @@ function initReloadConfiguration(filename, options) {
}
configState.filename = filename;
configState.lastMTime = getMTime(filename);
configState.timerId = setInterval(reloadConfiguration, options.reloadSecs*1000);
configState.timerId = setInterval(reloadConfiguration, options.reloadSecs*1000, options);
}
function configure(configurationFileOrObject, options) {
@@ -290,25 +372,90 @@ function restoreConsole() {
});
}
function loadAppender(appender) {
/**
* Load an appenderModule based on the provided appender filepath. Will first
* check if the appender path is a subpath of the log4js "lib/appenders" directory.
* If not, it will attempt to load the the appender as complete path.
*
* @param {string} appender The filepath for the appender.
* @returns {Object|null} The required appender or null if appender could not be loaded.
* @private
*/
function requireAppender(appender) {
var appenderModule;
try {
appenderModule = require('./appenders/' + appender);
} catch (e) {
appenderModule = require(appender);
}
return appenderModule;
}
/**
* Load an appender. Provided the appender path to be loaded. If appenderModule is defined,
* it will be used in place of requiring the appender module.
*
* @param {string} appender The path to the appender module.
* @param {Object|void} [appenderModule] The pre-required appender module. When provided,
* instead of requiring the appender by its path, this object will be used.
* @returns {void}
* @private
*/
function loadAppender(appender, appenderModule) {
appenderModule = appenderModule || requireAppender(appender);
if (!appenderModule) {
throw new Error("Invalid log4js appender: " + util.inspect(appender));
}
module.exports.appenders[appender] = appenderModule.appender.bind(appenderModule);
if (appenderModule.shutdown) {
appenderShutdowns[appender] = appenderModule.shutdown.bind(appenderModule);
}
appenderMakers[appender] = appenderModule.configure.bind(appenderModule);
}
/**
* Shutdown all log appenders. This will first disable all writing to appenders
* and then call the shutdown function each appender.
*
* @params {Function} cb - The callback to be invoked once all appenders have
* shutdown. If an error occurs, the callback will be given the error object
* as the first argument.
* @returns {void}
*/
function shutdown(cb) {
// First, disable all writing to appenders. This prevents appenders from
// not being able to be drained because of run-away log writes.
loggerModule.disableAllLogWrites();
// Next, get all the shutdown functions for appenders as an array.
var shutdownFunctions = Object.keys(appenderShutdowns).reduce(
function(accum, category) {
return accum.concat(appenderShutdowns[category]);
}, []);
// Call each of the shutdown functions.
async.each(
shutdownFunctions,
function(shutdownFn, done) {
shutdownFn(done);
},
cb
);
}
module.exports = {
getBufferedLogger: getBufferedLogger,
getLogger: getLogger,
getDefaultLogger: getDefaultLogger,
hasLogger: hasLogger,
addAppender: addAppender,
loadAppender: loadAppender,
clearAppenders: clearAppenders,
configure: configure,
shutdown: shutdown,
replaceConsole: replaceConsole,
restoreConsole: restoreConsole,

View File

@@ -4,6 +4,8 @@ var levels = require('./levels')
, events = require('events')
, DEFAULT_CATEGORY = '[default]';
var logWritesEnabled = true;
/**
* Models a logging event.
* @constructor
@@ -49,16 +51,19 @@ Logger.prototype.removeLevel = function() {
Logger.prototype.log = function() {
var args = Array.prototype.slice.call(arguments)
, logLevel = args.shift()
, loggingEvent = new LoggingEvent(this.category, logLevel, args, this);
this.emit("log", loggingEvent);
, logLevel = levels.toLevel(args.shift(), levels.INFO)
, loggingEvent;
if (this.isLevelEnabled(logLevel)) {
loggingEvent = new LoggingEvent(this.category, logLevel, args, this);
this.emit("log", loggingEvent);
}
};
Logger.prototype.isLevelEnabled = function(otherLevel) {
return this.level.isLessThanOrEqualTo(otherLevel);
};
['Trace','Debug','Info','Warn','Error','Fatal'].forEach(
['Trace','Debug','Info','Warn','Error','Fatal', 'Mark'].forEach(
function(levelString) {
var level = levels.toLevel(levelString);
Logger.prototype['is'+levelString+'Enabled'] = function() {
@@ -66,7 +71,7 @@ Logger.prototype.isLevelEnabled = function(otherLevel) {
};
Logger.prototype[levelString.toLowerCase()] = function () {
if (this.isLevelEnabled(level)) {
if (logWritesEnabled && this.isLevelEnabled(level)) {
var args = Array.prototype.slice.call(arguments);
args.unshift(level);
Logger.prototype.log.apply(this, args);
@@ -75,6 +80,23 @@ Logger.prototype.isLevelEnabled = function(otherLevel) {
}
);
/**
* Disable all log writes.
* @returns {void}
*/
function disableAllLogWrites() {
logWritesEnabled = false;
}
/**
* Enable log writes.
* @returns {void}
*/
function enableAllLogWrites() {
logWritesEnabled = true;
}
exports.LoggingEvent = LoggingEvent;
exports.Logger = Logger;
exports.disableAllLogWrites = disableAllLogWrites;
exports.enableAllLogWrites = enableAllLogWrites;

View File

@@ -16,7 +16,11 @@ module.exports = BaseRollingFileStream;
function BaseRollingFileStream(filename, options) {
debug("In BaseRollingFileStream");
this.filename = filename;
this.options = options || { encoding: 'utf8', mode: parseInt('0644', 8), flags: 'a' };
this.options = options || {};
this.options.encoding = this.options.encoding || 'utf8';
this.options.mode = this.options.mode || parseInt('0644', 8);
this.options.flags = this.options.flags || 'a';
this.currentSize = 0;
function currentFileSize(file) {
@@ -48,7 +52,13 @@ BaseRollingFileStream.prototype._write = function(chunk, encoding, callback) {
function writeTheChunk() {
debug("writing the chunk to the underlying stream");
that.currentSize += chunk.length;
that.theStream.write(chunk, encoding, callback);
try {
that.theStream.write(chunk, encoding, callback);
}
catch (err){
debug(err);
callback();
}
}
debug("in _write");

View File

@@ -17,7 +17,14 @@ function DateRollingFileStream(filename, pattern, options, now) {
}
this.pattern = pattern || '.yyyy-MM-dd';
this.now = now || Date.now;
this.lastTimeWeWroteSomething = format.asString(this.pattern, new Date(this.now()));
if (fs.existsSync(filename)) {
var stat = fs.statSync(filename);
this.lastTimeWeWroteSomething = format.asString(this.pattern, stat.mtime);
} else {
this.lastTimeWeWroteSomething = format.asString(this.pattern, new Date(this.now()));
}
this.baseFilename = filename;
this.alwaysIncludePattern = false;

View File

@@ -3,6 +3,8 @@ var BaseRollingFileStream = require('./BaseRollingFileStream')
, debug = require('../debug')('RollingFileStream')
, util = require('util')
, path = require('path')
, child_process = require('child_process')
, zlib = require("zlib")
, fs = require('fs')
, async = require('async');
@@ -25,7 +27,7 @@ function RollingFileStream (filename, size, backups, options) {
util.inherits(RollingFileStream, BaseRollingFileStream);
RollingFileStream.prototype.shouldRoll = function() {
debug("should roll with current size %d, and max size %d", this.currentSize, this.size);
debug("should roll with current size " + this.currentSize + " and max size " + this.size);
return this.currentSize >= this.size;
};
@@ -38,6 +40,7 @@ RollingFileStream.prototype.roll = function(filename, callback) {
}
function index(filename_) {
debug('Calculating index of '+filename_);
return parseInt(filename_.substring((path.basename(filename) + '.').length), 10) || 0;
}
@@ -51,16 +54,42 @@ RollingFileStream.prototype.roll = function(filename, callback) {
}
}
function compress (filename, cb) {
var gzip = zlib.createGzip();
var inp = fs.createReadStream(filename);
var out = fs.createWriteStream(filename+".gz");
inp.pipe(gzip).pipe(out);
fs.unlink(filename, cb);
}
function increaseFileIndex (fileToRename, cb) {
var idx = index(fileToRename);
debug('Index of ' + fileToRename + ' is ' + idx);
if (idx < that.backups) {
var ext = path.extname(fileToRename);
var destination = filename + '.' + (idx+1);
if (that.options.compress && /^gz$/.test(ext.substring(1))) {
destination+=ext;
}
//on windows, you can get a EEXIST error if you rename a file to an existing file
//so, we'll try to delete the file we're renaming to first
fs.unlink(filename + '.' + (idx+1), function (err) {
fs.unlink(destination, function (err) {
//ignore err: if we could not delete, it's most likely that it doesn't exist
debug('Renaming ' + fileToRename + ' -> ' + filename + '.' + (idx+1));
fs.rename(path.join(path.dirname(filename), fileToRename), filename + '.' + (idx + 1), cb);
debug('Renaming ' + fileToRename + ' -> ' + destination);
fs.rename(path.join(path.dirname(filename), fileToRename), destination, function(err) {
if (err) {
cb(err);
} else {
if (that.options.compress && ext!=".gz") {
compress(destination, cb);
} else {
cb();
}
}
});
});
} else {
cb();
@@ -71,7 +100,7 @@ RollingFileStream.prototype.roll = function(filename, callback) {
//roll the backups (rename file.n to file.n+1, where n <= numBackups)
debug("Renaming the old files");
fs.readdir(path.dirname(filename), function (err, files) {
async.forEachSeries(
async.eachSeries(
files.filter(justTheseFiles).sort(byIndex).reverse(),
increaseFileIndex,
cb

View File

@@ -1,6 +1,6 @@
{
"name": "log4js",
"version": "0.6.9",
"version": "0.6.25",
"description": "Port of Log4js to work with node.",
"keywords": [
"logging",
@@ -8,8 +8,9 @@
"log4j",
"node"
],
"license": "Apache-2.0",
"main": "./lib/log4js",
"author": "Gareth Jones <gareth.jones@sensis.com.au>",
"author": "Gareth Jones <gareth.nomiddlename@gmail.com>",
"repository": {
"type": "git",
"url": "https://github.com/nomiddlename/log4js-node.git"
@@ -28,14 +29,14 @@
"lib": "lib"
},
"dependencies": {
"async": "0.1.15",
"semver": "~1.1.4",
"readable-stream": "~1.0.2"
"async": "~0.2.0",
"readable-stream": "~1.0.2",
"semver": "~4.3.3",
"underscore": "1.8.2"
},
"devDependencies": {
"vows": "0.7.0",
"sandboxed-module": "0.1.3",
"hook.io": "0.8.10",
"underscore": "1.2.1"
},
"browser": {

View File

@@ -2,7 +2,8 @@
var vows = require('vows')
, fs = require('fs')
, assert = require('assert');
, assert = require('assert')
, EOL = require('os').EOL || '\n';
function remove(filename) {
try {
@@ -15,24 +16,24 @@ function remove(filename) {
vows.describe('log4js categoryFilter').addBatch({
'appender': {
topic: function() {
var log4js = require('../lib/log4js'), logEvents = [], webLogger, appLogger;
log4js.clearAppenders();
var appender = require('../lib/appenders/categoryFilter')
.appender(
['app'],
['app'],
function(evt) { logEvents.push(evt); }
);
log4js.addAppender(appender, ["app","web"]);
webLogger = log4js.getLogger("web");
appLogger = log4js.getLogger("app");
webLogger.debug('This should get logged');
appLogger.debug('This should not');
webLogger.debug('Hello again');
log4js.getLogger('db').debug('This shouldn\'t be included by the appender anyway');
return logEvents;
},
'should only pass matching category' : function(logEvents) {
@@ -41,32 +42,32 @@ vows.describe('log4js categoryFilter').addBatch({
assert.equal(logEvents[1].data[0], 'Hello again');
}
},
'configure': {
topic: function() {
var log4js = require('../lib/log4js')
, logger, weblogger;
remove(__dirname + '/categoryFilter-web.log');
remove(__dirname + '/categoryFilter-noweb.log');
log4js.configure('test/with-categoryFilter.json');
logger = log4js.getLogger("app");
weblogger = log4js.getLogger("web");
logger.info('Loading app');
logger.debug('Initialising indexes');
weblogger.info('00:00:00 GET / 200');
weblogger.warn('00:00:00 GET / 500');
//wait for the file system to catch up
setTimeout(this.callback, 100);
setTimeout(this.callback, 500);
},
'tmp-tests.log': {
topic: function() {
fs.readFile(__dirname + '/categoryFilter-noweb.log', 'utf8', this.callback);
},
'should contain all log messages': function(contents) {
var messages = contents.trim().split('\n');
var messages = contents.trim().split(EOL);
assert.deepEqual(messages, ['Loading app','Initialising indexes']);
}
},
@@ -75,7 +76,7 @@ vows.describe('log4js categoryFilter').addBatch({
fs.readFile(__dirname + '/categoryFilter-web.log','utf8',this.callback);
},
'should contain only error and warning log messages': function(contents) {
var messages = contents.trim().split('\n');
var messages = contents.trim().split(EOL);
assert.deepEqual(messages, ['00:00:00 GET / 200','00:00:00 GET / 500']);
}
}

View File

@@ -37,7 +37,8 @@ vows.describe('log4js cluster appender').addBatch({
});
var masterAppender = appenderModule.appender({
actualAppenders: [ fakeActualAppender ]
actualAppenders: [fakeActualAppender, fakeActualAppender, fakeActualAppender],
appenders: [{}, {category: "test"}, {category: "wovs"}]
});
// Actual test - log message using masterAppender
@@ -56,7 +57,9 @@ vows.describe('log4js cluster appender').addBatch({
},
"should log using actual appender": function(topic) {
assert.equal(topic.loggingEvents.length, 2)
assert.equal(topic.loggingEvents[0].data[0], 'masterAppender test');
assert.equal(topic.loggingEvents[1].data[0], 'masterAppender test');
},
},

View File

@@ -86,6 +86,21 @@ vows.describe('log4js configure').addBatch({
assert.isFunction(log4js.appenderMakers['some/other/external']);
}
},
'when appender object loaded via loadAppender': {
topic: function() {
var testAppender = makeTestAppender(),
log4js = sandbox.require('../lib/log4js');
log4js.loadAppender('some/other/external', testAppender);
return log4js;
},
'should load appender with provided object': function(log4js) {
assert.ok(log4js.appenders['some/other/external']);
},
'should add appender configure function to appenderMakers': function(log4js) {
assert.isFunction(log4js.appenderMakers['some/other/external']);
}
},
'when configuration file loaded via LOG4JS_CONFIG environment variable': {
topic: function() {
process.env.LOG4JS_CONFIG = 'some/path/to/mylog4js.json';

View File

@@ -2,13 +2,15 @@
"use strict";
var vows = require('vows')
, assert = require('assert')
, util = require('util')
, EE = require('events').EventEmitter
, levels = require('../lib/levels');
function MockLogger() {
var that = this;
this.messages = [];
this.log = function(level, message, exception) {
that.messages.push({ level: level, message: message });
};
@@ -16,7 +18,7 @@ function MockLogger() {
this.isLevelEnabled = function(level) {
return level.isGreaterThanOrEqualTo(that.level);
};
this.level = levels.TRACE;
}
@@ -37,15 +39,19 @@ function MockRequest(remoteAddr, method, originalUrl, headers) {
}
function MockResponse() {
this.end = function(chunk, encoding) {
var r = this;
this.end = function(chunk, encoding) {
r.emit('finish');
};
this.writeHead = function(code, headers) {
this.statusCode = code;
this._headers = headers;
};
}
util.inherits(MockResponse, EE);
function request(cl, method, url, code, reqHeaders, resHeaders) {
var req = new MockRequest('my.remote.addr', method, url, reqHeaders);
var res = new MockResponse();
@@ -60,7 +66,7 @@ vows.describe('log4js connect logger').addBatch({
var clm = require('../lib/connect-logger');
return clm;
},
'should return a "connect logger" factory' : function(clm) {
assert.isObject(clm);
},
@@ -71,18 +77,21 @@ vows.describe('log4js connect logger').addBatch({
var cl = clm.connectLogger(ml);
return cl;
},
'should return a "connect logger"': function(cl) {
assert.isFunction(cl);
}
},
'log events' : {
topic: function(clm) {
var ml = new MockLogger();
var cl = clm.connectLogger(ml);
var cb = this.callback;
request(cl, 'GET', 'http://url', 200);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'check message': function(messages) {
@@ -104,7 +113,7 @@ vows.describe('log4js connect logger').addBatch({
request(cl, 'GET', 'http://url', 200);
return ml.messages;
},
'check message': function(messages) {
assert.isArray(messages);
assert.isEmpty(messages);
@@ -114,12 +123,14 @@ vows.describe('log4js connect logger').addBatch({
'log events with non-default level and custom format' : {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: levels.INFO, format: ':method :url' } );
request(cl, 'GET', 'http://url', 200);
return ml.messages;
},
setTimeout(function() {
cb(null, ml.messages);
},10); },
'check message': function(messages) {
assert.isArray(messages);
assert.equal(messages.length, 1);
@@ -131,10 +142,13 @@ vows.describe('log4js connect logger').addBatch({
'logger with options as string': {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, ':method :url');
request(cl, 'POST', 'http://meh', 200);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'should use the passed in format': function(messages) {
assert.equal(messages[0].message, 'POST http://meh');
@@ -144,6 +158,7 @@ vows.describe('log4js connect logger').addBatch({
'auto log levels': {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: 'auto', format: ':method :url' });
request(cl, 'GET', 'http://meh', 200);
@@ -151,7 +166,9 @@ vows.describe('log4js connect logger').addBatch({
request(cl, 'GET', 'http://meh', 302);
request(cl, 'GET', 'http://meh', 404);
request(cl, 'GET', 'http://meh', 500);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'should use INFO for 2xx': function(messages) {
@@ -175,10 +192,13 @@ vows.describe('log4js connect logger').addBatch({
'format using a function': {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, function(req, res, formatFn) { return "I was called"; });
request(cl, 'GET', 'http://blah', 200);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'should call the format function': function(messages) {
@@ -189,14 +209,17 @@ vows.describe('log4js connect logger').addBatch({
'format that includes request headers': {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, ':req[Content-Type]');
request(
cl,
'GET', 'http://blah', 200,
cl,
'GET', 'http://blah', 200,
{ 'Content-Type': 'application/json' }
);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'should output the request header': function(messages) {
assert.equal(messages[0].message, 'application/json');
@@ -206,6 +229,7 @@ vows.describe('log4js connect logger').addBatch({
'format that includes response headers': {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, ':res[Content-Type]');
request(
@@ -214,13 +238,58 @@ vows.describe('log4js connect logger').addBatch({
null,
{ 'Content-Type': 'application/cheese' }
);
return ml.messages;
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'should output the response header': function(messages) {
assert.equal(messages[0].message, 'application/cheese');
}
}
},
'log events with custom token' : {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: levels.INFO, format: ':method :url :custom_string', tokens: [{
token: ':custom_string', replacement: 'fooBAR'
}] } );
request(cl, 'GET', 'http://url', 200);
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'check message': function(messages) {
assert.isArray(messages);
assert.equal(messages.length, 1);
assert.ok(levels.INFO.isEqualTo(messages[0].level));
assert.equal(messages[0].message, 'GET http://url fooBAR');
}
},
'log events with custom override token' : {
topic: function(clm) {
var ml = new MockLogger();
var cb = this.callback;
ml.level = levels.INFO;
var cl = clm.connectLogger(ml, { level: levels.INFO, format: ':method :url :date', tokens: [{
token: ':date', replacement: "20150310"
}] } );
request(cl, 'GET', 'http://url', 200);
setTimeout(function() {
cb(null, ml.messages);
},10);
},
'check message': function(messages) {
assert.isArray(messages);
assert.equal(messages.length, 1);
assert.ok(levels.INFO.isEqualTo(messages[0].level));
assert.equal(messages[0].message, 'GET http://url 20150310');
}
}
}
}).export(module);

View File

@@ -4,7 +4,8 @@ var vows = require('vows')
, path = require('path')
, fs = require('fs')
, sandbox = require('sandboxed-module')
, log4js = require('../lib/log4js');
, log4js = require('../lib/log4js')
, EOL = require('os').EOL || '\n';
function removeFile(filename) {
return function() {
@@ -134,7 +135,10 @@ vows.describe('../lib/appenders/dateFile').addBatch({
teardown: removeFile('date-file-test.log'),
'should load appender configuration from a json file': function(err, contents) {
assert.include(contents, 'this should be written to the file' + require('os').EOL);
if (err) {
throw err;
}
assert.include(contents, 'this should be written to the file' + EOL);
assert.equal(contents.indexOf('this should not be written to the file'), -1);
}
},
@@ -161,7 +165,7 @@ vows.describe('../lib/appenders/dateFile').addBatch({
, thisTime = format.asString(options.appenders[0].pattern, new Date());
fs.writeFileSync(
path.join(__dirname, 'date-file-test' + thisTime),
"this is existing data" + require('os').EOL,
"this is existing data" + EOL,
'utf8'
);
log4js.clearAppenders();
@@ -182,7 +186,7 @@ vows.describe('../lib/appenders/dateFile').addBatch({
}
},
'with cwd option': {
topic: function() {
topic: function () {
var fileOpened,
appender = sandbox.require(
'../lib/appenders/dateFile',
@@ -209,8 +213,9 @@ vows.describe('../lib/appenders/dateFile').addBatch({
);
return fileOpened;
},
'should prepend options.cwd to config.filename': function(fileOpened) {
assert.equal(fileOpened, "/absolute/path/to/whatever.log");
'should prepend options.cwd to config.filename': function (fileOpened) {
var expected = path.sep + path.join("absolute", "path", "to", "whatever.log");
assert.equal(fileOpened, expected);
}
}

View File

@@ -3,11 +3,13 @@ var vows = require('vows')
, assert = require('assert')
, dateFormat = require('../lib/date_format');
function createFixedDate() {
return new Date(2010, 0, 11, 14, 31, 30, 5);
}
vows.describe('date_format').addBatch({
'Date extensions': {
topic: function() {
return new Date(2010, 0, 11, 14, 31, 30, 5);
},
topic: createFixedDate,
'should format a date as string using a pattern': function(date) {
assert.equal(
dateFormat.asString(dateFormat.DATETIME_FORMAT, date),
@@ -20,13 +22,16 @@ vows.describe('date_format').addBatch({
'2010-01-11 14:31:30.005'
);
},
'should provide a ISO8601 with timezone offset format': function(date) {
'should provide a ISO8601 with timezone offset format': function() {
var date = createFixedDate();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset() - 660);
date.getTimezoneOffset = function() { return -660; };
assert.equal(
dateFormat.asString(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, date),
"2010-01-11T14:31:30+1100"
);
date = createFixedDate();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset() + 120);
date.getTimezoneOffset = function() { return 120; };
assert.equal(
dateFormat.asString(dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT, date),
@@ -40,7 +45,9 @@ vows.describe('date_format').addBatch({
'14:31:30.005'
);
},
'should provide a custom format': function(date) {
'should provide a custom format': function() {
var date = createFixedDate();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset() + 120);
date.getTimezoneOffset = function() { return 120; };
assert.equal(
dateFormat.asString("O.SSS.ss.mm.hh.dd.MM.yy", date),

View File

@@ -4,7 +4,9 @@ var vows = require('vows')
, path = require('path')
, sandbox = require('sandboxed-module')
, log4js = require('../lib/log4js')
, assert = require('assert');
, assert = require('assert')
, zlib = require('zlib')
, EOL = require('os').EOL || '\n';
log4js.clearAppenders();
@@ -93,8 +95,8 @@ vows.describe('log4js fileAppender').addBatch({
fs.readFile(testFile, "utf8", that.callback);
}, 100);
},
'should write log messages to the file': function(err, fileContents) {
assert.include(fileContents, "This should be in the file.\n");
'should write log messages to the file': function (err, fileContents) {
assert.include(fileContents, "This should be in the file." + EOL);
},
'log messages should be in the basic layout format': function(err, fileContents) {
assert.match(
@@ -103,6 +105,70 @@ vows.describe('log4js fileAppender').addBatch({
);
}
},
'fileAppender subcategories': {
topic: function() {
var that = this;
log4js.clearAppenders();
function addAppender(cat) {
var testFile = path.join(__dirname, '/fa-subcategories-test-'+cat.join('-').replace(/\./g, "_")+'.log');
remove(testFile);
log4js.addAppender(require('../lib/appenders/file').appender(testFile), cat);
return testFile;
}
var file_sub1 = addAppender([ 'sub1']);
var file_sub1_sub12$sub1_sub13 = addAppender([ 'sub1.sub12', 'sub1.sub13' ]);
var file_sub1_sub12 = addAppender([ 'sub1.sub12' ]);
var logger_sub1_sub12_sub123 = log4js.getLogger('sub1.sub12.sub123');
var logger_sub1_sub13_sub133 = log4js.getLogger('sub1.sub13.sub133');
var logger_sub1_sub14 = log4js.getLogger('sub1.sub14');
var logger_sub2 = log4js.getLogger('sub2');
logger_sub1_sub12_sub123.info('sub1_sub12_sub123');
logger_sub1_sub13_sub133.info('sub1_sub13_sub133');
logger_sub1_sub14.info('sub1_sub14');
logger_sub2.info('sub2');
setTimeout(function() {
that.callback(null, {
file_sub1: fs.readFileSync(file_sub1).toString(),
file_sub1_sub12$sub1_sub13: fs.readFileSync(file_sub1_sub12$sub1_sub13).toString(),
file_sub1_sub12: fs.readFileSync(file_sub1_sub12).toString()
});
}, 3000);
},
'check file contents': function (err, fileContents) {
// everything but category 'sub2'
assert.match(fileContents.file_sub1, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123|sub1.sub13.sub133 - sub1_sub13_sub133|sub1.sub14 - sub1_sub14)[\s\S]){3}$/);
assert.ok(fileContents.file_sub1.match(/sub123/) && fileContents.file_sub1.match(/sub133/) && fileContents.file_sub1.match(/sub14/));
assert.ok(!fileContents.file_sub1.match(/sub2/));
// only catgories starting with 'sub1.sub12' and 'sub1.sub13'
assert.match(fileContents.file_sub1_sub12$sub1_sub13, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123|sub1.sub13.sub133 - sub1_sub13_sub133)[\s\S]){2}$/);
assert.ok(fileContents.file_sub1_sub12$sub1_sub13.match(/sub123/) && fileContents.file_sub1_sub12$sub1_sub13.match(/sub133/));
assert.ok(!fileContents.file_sub1_sub12$sub1_sub13.match(/sub14|sub2/));
// only catgories starting with 'sub1.sub12'
assert.match(fileContents.file_sub1_sub12, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123)[\s\S]){1}$/);
assert.ok(!fileContents.file_sub1_sub12.match(/sub14|sub2|sub13/));
}
},
'with a max file size and no backups': {
topic: function() {
var testFile = path.join(__dirname, '/fa-maxFileSize-test.log')
@@ -125,7 +191,7 @@ vows.describe('log4js fileAppender').addBatch({
}, 100);
},
'log file should only contain the second message': function(err, fileContents) {
assert.include(fileContents, "This is the second log message.\n");
assert.include(fileContents, "This is the second log message.");
assert.equal(fileContents.indexOf("This is the first log message."), -1);
},
'the number of files': {
@@ -213,6 +279,79 @@ vows.describe('log4js fileAppender').addBatch({
}
}
}
},
'with a max file size and 2 compressed backups': {
topic: function() {
var testFile = path.join(__dirname, '/fa-maxFileSize-with-backups-compressed-test.log')
, logger = log4js.getLogger('max-file-size-backups');
remove(testFile);
remove(testFile+'.1.gz');
remove(testFile+'.2.gz');
//log file of 50 bytes maximum, 2 backups
log4js.clearAppenders();
log4js.addAppender(
require('../lib/appenders/file').appender(testFile, log4js.layouts.basicLayout, 50, 2, true),
'max-file-size-backups'
);
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.");
var that = this;
//give the system a chance to open the stream
setTimeout(function() {
fs.readdir(__dirname, function(err, files) {
if (files) {
that.callback(null, files.sort());
} else {
that.callback(err, files);
}
});
}, 1000);
},
'the log files': {
topic: function(files) {
var logFiles = files.filter(
function(file) { return file.indexOf('fa-maxFileSize-with-backups-compressed-test.log') > -1; }
);
return logFiles;
},
'should be 3': function (files) {
assert.equal(files.length, 3);
},
'should be named in sequence': function (files) {
assert.deepEqual(files, [
'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'
]);
},
'and the contents of the first file': {
topic: function(logFiles) {
fs.readFile(path.join(__dirname, logFiles[0]), "utf8", this.callback);
},
'should be the last log message': function(contents) {
assert.include(contents, 'This is the fourth log message.');
}
},
'and the contents of the second file': {
topic: function(logFiles) {
zlib.gunzip(fs.readFileSync(path.join(__dirname, logFiles[1])), this.callback);
},
'should be the third log message': function(contents) {
assert.include(contents.toString('utf8'), 'This is the third log message.');
}
},
'and the contents of the third file': {
topic: function(logFiles) {
zlib.gunzip(fs.readFileSync(path.join(__dirname, logFiles[2])), this.callback);
},
'should be the second log message': function(contents) {
assert.include(contents.toString('utf8'), 'This is the second log message.');
}
}
}
}
}).addBatch({
'configure' : {
@@ -229,8 +368,8 @@ vows.describe('log4js fileAppender').addBatch({
fs.readFile('tmp-tests.log', 'utf8', this.callback);
},
'should load appender configuration from a json file': function(err, contents) {
assert.include(contents, 'this should be written to the file\n');
'should load appender configuration from a json file': function (err, contents) {
assert.include(contents, 'this should be written to the file' + EOL);
assert.equal(contents.indexOf('this should not be written to the file'), -1);
}
}

182
test/fileSyncAppender-test.js Executable file
View File

@@ -0,0 +1,182 @@
"use strict";
var vows = require('vows')
, fs = require('fs')
, path = require('path')
, sandbox = require('sandboxed-module')
, log4js = require('../lib/log4js')
, assert = require('assert')
, EOL = require('os').EOL || '\n';
log4js.clearAppenders();
function remove(filename) {
try {
fs.unlinkSync(filename);
} catch (e) {
//doesn't really matter if it failed
}
}
vows.describe('log4js fileSyncAppender').addBatch({
'with default fileSyncAppender settings': {
topic: function() {
var that = this
, testFile = path.join(__dirname, '/fa-default-sync-test.log')
, logger = log4js.getLogger('default-settings');
remove(testFile);
log4js.clearAppenders();
log4js.addAppender(require('../lib/appenders/fileSync').appender(testFile), 'default-settings');
logger.info("This should be in the file.");
fs.readFile(testFile, "utf8", that.callback);
},
'should write log messages to the file': function (err, fileContents) {
assert.include(fileContents, "This should be in the file." + EOL);
},
'log messages should be in the basic layout format': function(err, fileContents) {
assert.match(
fileContents,
/\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] default-settings - /
);
}
},
'with a max file size and no backups': {
topic: function() {
var testFile = path.join(__dirname, '/fa-maxFileSize-sync-test.log')
, logger = log4js.getLogger('max-file-size')
, that = this;
remove(testFile);
remove(testFile + '.1');
//log file of 100 bytes maximum, no backups
log4js.clearAppenders();
log4js.addAppender(
require('../lib/appenders/fileSync').appender(testFile, log4js.layouts.basicLayout, 100, 0),
'max-file-size'
);
logger.info("This is the first log message.");
logger.info("This is an intermediate log message.");
logger.info("This is the second log message.");
fs.readFile(testFile, "utf8", that.callback);
},
'log file should only contain the second message': function (err, fileContents) {
assert.include(fileContents, "This is the second log message." + EOL);
assert.equal(fileContents.indexOf("This is the first log message."), -1);
},
'the number of files': {
topic: function() {
fs.readdir(__dirname, this.callback);
},
'starting with the test file name should be two': function(err, files) {
//there will always be one backup if you've specified a max log size
var logFiles = files.filter(
function(file) { return file.indexOf('fa-maxFileSize-sync-test.log') > -1; }
);
assert.equal(logFiles.length, 2);
}
}
},
'with a max file size and 2 backups': {
topic: function() {
var testFile = path.join(__dirname, '/fa-maxFileSize-with-backups-sync-test.log')
, logger = log4js.getLogger('max-file-size-backups');
remove(testFile);
remove(testFile+'.1');
remove(testFile+'.2');
//log file of 50 bytes maximum, 2 backups
log4js.clearAppenders();
log4js.addAppender(
require('../lib/appenders/fileSync').appender(testFile, log4js.layouts.basicLayout, 50, 2),
'max-file-size-backups'
);
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.");
var that = this;
fs.readdir(__dirname, function(err, files) {
if (files) {
that.callback(null, files.sort());
} else {
that.callback(err, files);
}
});
},
'the log files': {
topic: function(files) {
var logFiles = files.filter(
function(file) { return file.indexOf('fa-maxFileSize-with-backups-sync-test.log') > -1; }
);
return logFiles;
},
'should be 3': function (files) {
assert.equal(files.length, 3);
},
'should be named in sequence': function (files) {
assert.deepEqual(files, [
'fa-maxFileSize-with-backups-sync-test.log',
'fa-maxFileSize-with-backups-sync-test.log.1',
'fa-maxFileSize-with-backups-sync-test.log.2'
]);
},
'and the contents of the first file': {
topic: function(logFiles) {
fs.readFile(path.join(__dirname, logFiles[0]), "utf8", this.callback);
},
'should be the last log message': function(contents) {
assert.include(contents, 'This is the fourth log message.');
}
},
'and the contents of the second file': {
topic: function(logFiles) {
fs.readFile(path.join(__dirname, logFiles[1]), "utf8", this.callback);
},
'should be the third log message': function(contents) {
assert.include(contents, 'This is the third log message.');
}
},
'and the contents of the third file': {
topic: function(logFiles) {
fs.readFile(path.join(__dirname, logFiles[2]), "utf8", this.callback);
},
'should be the second log message': function(contents) {
assert.include(contents, 'This is the second log message.');
}
}
}
}
}).addBatch({
'configure' : {
'with fileSyncAppender': {
topic: function() {
var log4js = require('../lib/log4js')
, logger;
//this config defines one file appender (to ./tmp-sync-tests.log)
//and sets the log level for "tests" to WARN
log4js.configure({
appenders: [{
category: "tests",
type: "file",
filename: "tmp-sync-tests.log",
layout: { type: "messagePassThrough" }
}],
levels: { tests: "WARN" }
});
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('tmp-sync-tests.log', 'utf8', this.callback);
},
'should load appender configuration from a json file': function(err, contents) {
assert.include(contents, 'this should be written to the file' + EOL);
assert.equal(contents.indexOf('this should not be written to the file'), -1);
}
}
}
}).export(module);

View File

@@ -73,7 +73,7 @@ var vows = require('vows')
console: fakeConsole
}
});
log4js.clearAppenders();
log4js.addAppender(appender.configure(options || {}), category || "gelf-test");
return {
@@ -87,7 +87,7 @@ var vows = require('vows')
};
vows.describe('log4js gelfAppender').addBatch({
'with default gelfAppender settings': {
topic: function() {
var setup = setupLogging();
@@ -115,12 +115,10 @@ vows.describe('log4js gelfAppender').addBatch({
return message;
},
'should be in the gelf format': function(message) {
assert.equal(message.version, '1.0');
assert.equal(message.version, '1.1');
assert.equal(message.host, require('os').hostname());
assert.equal(message.level, 6); //INFO
assert.equal(message.facility, 'nodejs-server');
assert.equal(message.full_message, message.short_message);
assert.equal(message.full_message, 'This is a test');
assert.equal(message.short_message, 'This is a test');
}
}
},
@@ -166,7 +164,7 @@ vows.describe('log4js gelfAppender').addBatch({
},
'should pick up the options': function(message) {
assert.equal(message.host, 'cheese');
assert.equal(message.facility, 'nonsense');
assert.equal(message._facility, 'nonsense');
}
}
},
@@ -246,12 +244,12 @@ vows.describe('log4js gelfAppender').addBatch({
},
'should pick up the options': function(message) {
assert.equal(message.host, 'cheese');
assert.equal(message.facility, 'nonsense');
assert.isUndefined(message.GELF); // make sure flag was removed
assert.equal(message._facility, 'nonsense');
assert.equal(message._every1, 'Hello every one'); // the default value
assert.equal(message._every2, 'Overwritten!'); // the overwritten value
assert.equal(message._myField, 'This is my field!'); // the value for this message only
assert.equal(message.short_message, 'Just testing.'); // skip the field object
assert.equal(message.full_message, 'Just testing.'); // should be as same as short_message
assert.equal(message.short_message, 'Just testing.'); // skip the field object
}
}
}

View File

@@ -8,7 +8,7 @@ vows.describe('log4js global loglevel').addBatch({
var log4js = require('../lib/log4js');
return log4js;
},
'set global loglevel on creation': function(log4js) {
var log1 = log4js.getLogger('log1');
var level = 'OFF';
@@ -16,14 +16,14 @@ vows.describe('log4js global loglevel').addBatch({
level = 'TRACE';
}
assert.notEqual(log1.level.toString(), level);
log4js.setGlobalLogLevel(level);
assert.equal(log1.level.toString(), level);
var log2 = log4js.getLogger('log2');
assert.equal(log2.level.toString(), level);
},
'global change loglevel': function(log4js) {
var log1 = log4js.getLogger('log1');
var log2 = log4js.getLogger('log2');
@@ -32,7 +32,7 @@ vows.describe('log4js global loglevel').addBatch({
level = 'TRACE';
}
assert.notEqual(log1.level.toString(), level);
log4js.setGlobalLogLevel(level);
assert.equal(log1.level.toString(), level);
assert.equal(log2.level.toString(), level);
@@ -46,20 +46,20 @@ vows.describe('log4js global loglevel').addBatch({
level = 'TRACE';
}
assert.notEqual(log1.level.toString(), level);
var oldLevel = log1.level.toString();
assert.equal(log2.level.toString(), oldLevel);
log2.setLevel(level);
assert.equal(log1.level.toString(), oldLevel);
assert.equal(log2.level.toString(), level);
assert.notEqual(oldLevel, level);
log2.removeLevel();
assert.equal(log1.level.toString(), oldLevel);
assert.equal(log2.level.toString(), oldLevel);
},
'preload loglevel': function(log4js) {
var log1 = log4js.getLogger('log1');
var level = 'OFF';
@@ -67,20 +67,55 @@ vows.describe('log4js global loglevel').addBatch({
level = 'TRACE';
}
assert.notEqual(log1.level.toString(), level);
var oldLevel = log1.level.toString();
log4js.getLogger('log2').setLevel(level);
assert.equal(log1.level.toString(), oldLevel);
// get again same logger but as different variable
var log2 = log4js.getLogger('log2');
assert.equal(log2.level.toString(), level);
assert.notEqual(oldLevel, level);
log2.removeLevel();
assert.equal(log1.level.toString(), oldLevel);
assert.equal(log2.level.toString(), oldLevel);
},
'set level on all categories': function(log4js) {
// Get 2 loggers
var log1 = log4js.getLogger('log1');
var log2 = log4js.getLogger('log2');
// First a test with 2 categories with different levels
var config = {
'levels': {
'log1': 'ERROR',
'log2': 'WARN'
}
};
log4js.configure(config);
// Check if the levels are set correctly
assert.equal('ERROR', log1.level.toString());
assert.equal('WARN', log2.level.toString());
log1.removeLevel();
log2.removeLevel();
// Almost identical test, but now we set
// level on all categories
var config2 = {
'levels': {
'[all]': 'DEBUG'
}
};
log4js.configure(config2);
// Check if the loggers got the DEBUG level
assert.equal('DEBUG', log1.level.toString());
assert.equal('DEBUG', log2.level.toString());
}
}
}).export(module);

View File

@@ -1,176 +0,0 @@
"use strict";
var vows = require('vows')
, assert = require('assert')
, sandbox = require('sandboxed-module');
function fancyResultingHookioAppender(hookNotReady) {
var emitHook = !hookNotReady
, result = { ons: {}, emissions: {}, logged: [], configs: [] };
var fakeLog4Js = {
appenderMakers: {}
};
fakeLog4Js.loadAppender = function (appender) {
fakeLog4Js.appenderMakers[appender] = function (config) {
result.actualLoggerConfig = config;
return function log(logEvent) {
result.logged.push(logEvent);
};
};
};
var fakeHookIo = { Hook: function(config) { result.configs.push(config); } };
fakeHookIo.Hook.prototype.start = function () {
result.startCalled = true;
};
fakeHookIo.Hook.prototype.on = function (eventName, functionToExec) {
result.ons[eventName] = { functionToExec: functionToExec };
if (emitHook && eventName === 'hook::ready') {
functionToExec();
}
};
fakeHookIo.Hook.prototype.emit = function (eventName, data) {
result.emissions[eventName] = result.emissions[eventName] || [];
result.emissions[eventName].push({data: data});
var on = '*::' + eventName;
if (eventName !== 'hook::ready' && result.ons[on]) {
result.ons[on].callingCount =
result.ons[on].callingCount ? result.ons[on].callingCount += 1 : 1;
result.ons[on].functionToExec(data);
}
};
return { theResult: result,
theModule: sandbox.require('../lib/appenders/hookio', {
requires: {
'../log4js': fakeLog4Js,
'hook.io': fakeHookIo
}
})
};
}
vows.describe('log4js hookioAppender').addBatch({
'master': {
topic: function() {
var fancy = fancyResultingHookioAppender();
var logger = fancy.theModule.configure(
{
name: 'ohno',
mode: 'master',
'hook-port': 5001,
appender: { type: 'file' }
}
);
logger(
{
level: { levelStr: 'INFO' },
data: "ALRIGHTY THEN",
startTime: '2011-10-27T03:53:16.031Z'
}
);
logger(
{
level: { levelStr: 'DEBUG' },
data: "OH WOW",
startTime: '2011-10-27T04:53:16.031Z'
}
);
return fancy.theResult;
},
'should write to the actual appender': function (result) {
assert.isTrue(result.startCalled);
assert.equal(result.configs.length, 1);
assert.equal(result.configs[0]['hook-port'], 5001);
assert.equal(result.logged.length, 2);
assert.equal(result.emissions['ohno::log'].length, 2);
assert.equal(result.ons['*::ohno::log'].callingCount, 2);
},
'data written should be formatted correctly': function (result) {
assert.equal(result.logged[0].level.toString(), 'INFO');
assert.equal(result.logged[0].data, 'ALRIGHTY THEN');
assert.isTrue(typeof(result.logged[0].startTime) === 'object');
assert.equal(result.logged[1].level.toString(), 'DEBUG');
assert.equal(result.logged[1].data, 'OH WOW');
assert.isTrue(typeof(result.logged[1].startTime) === 'object');
},
'the actual logger should get the right config': function (result) {
assert.equal(result.actualLoggerConfig.type, 'file');
}
},
'worker': {
'should emit logging events to the master': {
topic: function() {
var fancy = fancyResultingHookioAppender();
var logger = fancy.theModule.configure({
name: 'ohno',
mode: 'worker',
appender: { type: 'file' }
});
logger({
level: { levelStr: 'INFO' },
data: "ALRIGHTY THEN",
startTime: '2011-10-27T03:53:16.031Z'
});
logger({
level: { levelStr: 'DEBUG' },
data: "OH WOW",
startTime: '2011-10-27T04:53:16.031Z'
});
return fancy.theResult;
},
'should not write to the actual appender': function (result) {
assert.isTrue(result.startCalled);
assert.equal(result.logged.length, 0);
assert.equal(result.emissions['ohno::log'].length, 2);
assert.isUndefined(result.ons['*::ohno::log']);
}
}
},
'when hook not ready': {
topic: function() {
var fancy = fancyResultingHookioAppender(true)
, logger = fancy.theModule.configure({
name: 'ohno',
mode: 'worker'
});
logger({
level: { levelStr: 'INFO' },
data: "something",
startTime: '2011-10-27T03:45:12.031Z'
});
return fancy;
},
'should buffer the log events': function(fancy) {
assert.isUndefined(fancy.theResult.emissions['ohno::log']);
},
},
'when hook ready': {
topic: function() {
var fancy = fancyResultingHookioAppender(true)
, logger = fancy.theModule.configure({
name: 'ohno',
mode: 'worker'
});
logger({
level: { levelStr: 'INFO' },
data: "something",
startTime: '2011-10-27T03:45:12.031Z'
});
fancy.theResult.ons['hook::ready'].functionToExec();
return fancy;
},
'should emit the buffered events': function(fancy) {
assert.equal(fancy.theResult.emissions['ohno::log'].length, 1);
}
}
}).exportTo(module);

View File

@@ -1,13 +1,15 @@
"use strict";
var vows = require('vows')
, assert = require('assert');
, assert = require('assert')
, os = require('os')
, EOL = os.EOL || '\n';
//used for patternLayout tests.
function test(args, pattern, value) {
var layout = args[0]
, event = args[1]
, tokens = args[2];
assert.equal(layout(pattern, tokens)(event), value);
}
@@ -16,7 +18,7 @@ vows.describe('log4js layouts').addBatch({
topic: function() {
return require('../lib/layouts').colouredLayout;
},
'should apply level colour codes to output': function(layout) {
var output = layout({
data: ["nonsense"],
@@ -40,7 +42,7 @@ vows.describe('log4js layouts').addBatch({
assert.equal(output, '\x1B[31m[2010-12-05 14:18:30.045] [ERROR] cheese - \x1B[39mthing 2');
}
},
'messagePassThroughLayout': {
topic: function() {
return require('../lib/layouts').messagePassThroughLayout;
@@ -58,49 +60,49 @@ vows.describe('log4js layouts').addBatch({
},
'should support the console.log format for the message' : function(layout) {
assert.equal(layout({
data: ["thing %d", 1, "cheese"],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
data: ["thing %d", 1, "cheese"],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level : {
colour: "green",
colour: "green",
toString: function() { return "ERROR"; }
}
}), "thing 1 cheese");
},
'should output the first item even if it is not a string': function(layout) {
assert.equal(layout({
data: [ { thing: 1} ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
data: [ { thing: 1} ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level: {
colour: "green",
colour: "green",
toString: function() { return "ERROR"; }
}
}), "{ thing: 1 }");
},
'should print the stacks of a passed error objects': function(layout) {
assert.isArray(layout({
data: [ new Error() ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
data: [ new Error() ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level: {
colour: "green",
colour: "green",
toString: function() { return "ERROR"; }
}
}).match(/Error\s+at Object\..*\s+\((.*)test[\\\/]layouts-test\.js\:\d+\:\d+\)\s+at runTest/)
, 'regexp did not return a match');
},
'with passed augmented errors': {
'with passed augmented errors': {
topic: function(layout){
var e = new Error("My Unique Error Message");
e.augmented = "My Unique attribute value";
e.augObj = { at1: "at2" };
return layout({
data: [ e ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
data: [ e ],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level: {
colour: "green",
colour: "green",
toString: function() { return "ERROR"; }
}
});
@@ -118,10 +120,10 @@ vows.describe('log4js layouts').addBatch({
assert.isArray(m);
}
}
},
'basicLayout': {
topic: function() {
var layout = require('../lib/layouts').basicLayout,
@@ -143,17 +145,17 @@ vows.describe('log4js layouts').addBatch({
var layout = args[0], event = args[1], output, lines,
error = new Error("Some made-up error"),
stack = error.stack.split(/\n/);
event.data = ['this is a test', error];
output = layout(event);
lines = output.split(/\n/);
assert.equal(lines.length - 1, stack.length);
assert.equal(
lines[0],
lines[0],
"[2010-12-05 14:18:30.045] [DEBUG] tests - this is a test [Error: Some made-up error]"
);
for (var i = 1; i < stack.length; i++) {
assert.equal(lines[i+2], stack[i+1]);
}
@@ -166,18 +168,18 @@ vows.describe('log4js layouts').addBatch({
}];
output = layout(event);
assert.equal(
output,
"[2010-12-05 14:18:30.045] [DEBUG] tests - this is a test " +
output,
"[2010-12-05 14:18:30.045] [DEBUG] tests - this is a test " +
"{ name: 'Cheese', message: 'Gorgonzola smells.' }"
);
}
},
'patternLayout': {
topic: function() {
var event = {
data: ['this is a test'],
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
startTime: new Date('2010-12-05T14:18:30.045Z'), //new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "multiple.levels.of.tests",
level: {
toString: function() { return "DEBUG"; }
@@ -188,11 +190,14 @@ vows.describe('log4js layouts').addBatch({
testFunction: function() { return 'testFunctionToken'; },
fnThatUsesLogEvent: function(logEvent) { return logEvent.level.toString(); }
};
//override getTimezoneOffset
event.startTime.getTimezoneOffset = function() { return 0; };
return [layout, event, tokens];
},
'should default to "time logLevel loggerName - message"': function(args) {
test(args, null, "14:18:30 DEBUG multiple.levels.of.tests - this is a test\n");
test(args, null, "14:18:30 DEBUG multiple.levels.of.tests - this is a test" + EOL);
},
'%r should output time only': function(args) {
test(args, '%r', '14:18:30');
@@ -207,10 +212,13 @@ vows.describe('log4js layouts').addBatch({
test(args, '%m', 'this is a test');
},
'%n should output a new line': function(args) {
test(args, '%n', '\n');
test(args, '%n', EOL);
},
'%h should output hostname' : function(args) {
test(args, '%h', require('os').hostname().toString());
test(args, '%h', os.hostname().toString());
},
'%z should output pid' : function(args) {
test(args, '%z', process.pid);
},
'%c should handle category names like java-style package names': function(args) {
test(args, '%c{1}', 'tests');
@@ -244,7 +252,7 @@ vows.describe('log4js layouts').addBatch({
'should handle complicated patterns': function(args) {
test(args,
'%m%n %c{2} at %d{ABSOLUTE} cheese %p%n',
'this is a test\n of.tests at 14:18:30.045 cheese DEBUG\n'
'this is a test'+ EOL +' of.tests at 14:18:30.045 cheese DEBUG' + EOL
);
},
'should truncate fields if specified': function(args) {
@@ -274,14 +282,14 @@ vows.describe('log4js layouts').addBatch({
test(args, '%x{testFunction}', 'testFunctionToken');
},
'%x{doesNotExist} should output the string stored in tokens': function(args) {
test(args, '%x{doesNotExist}', '%x{doesNotExist}');
test(args, '%x{doesNotExist}', 'null');
},
'%x{fnThatUsesLogEvent} should be able to use the logEvent': function(args) {
test(args, '%x{fnThatUsesLogEvent}', 'DEBUG');
},
'%x should output the string stored in tokens': function(args) {
test(args, '%x', '%x');
},
test(args, '%x', 'null');
}
},
'layout makers': {
topic: require('../lib/layouts'),

View File

@@ -43,6 +43,7 @@ vows.describe('levels').addBatch({
assert.isNotNull(levels.WARN);
assert.isNotNull(levels.ERROR);
assert.isNotNull(levels.FATAL);
assert.isNotNull(levels.MARK);
assert.isNotNull(levels.OFF);
},
'ALL': {
@@ -56,7 +57,8 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -70,6 +72,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -84,6 +87,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -99,6 +103,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -113,6 +118,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -127,6 +133,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -141,6 +148,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -154,6 +162,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -168,6 +177,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]
);
@@ -180,6 +190,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]);
assertThat(info).isNotLessThanOrEqualTo([levels.ALL, levels.TRACE, levels.DEBUG]);
@@ -190,6 +201,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]);
},
@@ -202,6 +214,7 @@ vows.describe('levels').addBatch({
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.MARK,
levels.OFF
]);
}
@@ -209,7 +222,7 @@ vows.describe('levels').addBatch({
'WARN': {
topic: levels.WARN,
'should be less than ERROR': function(warn) {
assertThat(warn).isLessThanOrEqualTo([levels.ERROR, levels.FATAL, levels.OFF]);
assertThat(warn).isLessThanOrEqualTo([levels.ERROR, levels.FATAL, levels.MARK, levels.OFF]);
assertThat(warn).isNotLessThanOrEqualTo([
levels.ALL,
levels.TRACE,
@@ -224,7 +237,7 @@ vows.describe('levels').addBatch({
levels.DEBUG,
levels.INFO
]);
assertThat(warn).isNotGreaterThanOrEqualTo([levels.ERROR, levels.FATAL, levels.OFF]);
assertThat(warn).isNotGreaterThanOrEqualTo([levels.ERROR, levels.FATAL, levels.MARK, levels.OFF]);
},
'should only be equal to WARN': function(trace) {
assertThat(trace).isEqualTo([levels.toLevel("WARN")]);
@@ -242,7 +255,7 @@ vows.describe('levels').addBatch({
'ERROR': {
topic: levels.ERROR,
'should be less than FATAL': function(error) {
assertThat(error).isLessThanOrEqualTo([levels.FATAL, levels.OFF]);
assertThat(error).isLessThanOrEqualTo([levels.FATAL, levels.MARK, levels.OFF]);
assertThat(error).isNotLessThanOrEqualTo([
levels.ALL,
levels.TRACE,
@@ -259,7 +272,7 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN
]);
assertThat(error).isNotGreaterThanOrEqualTo([levels.FATAL, levels.OFF]);
assertThat(error).isNotGreaterThanOrEqualTo([levels.FATAL, levels.MARK, levels.OFF]);
},
'should only be equal to ERROR': function(trace) {
assertThat(trace).isEqualTo([levels.toLevel("ERROR")]);
@@ -270,6 +283,7 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.FATAL,
levels.MARK,
levels.OFF
]);
}
@@ -277,7 +291,7 @@ vows.describe('levels').addBatch({
'FATAL': {
topic: levels.FATAL,
'should be less than OFF': function(fatal) {
assertThat(fatal).isLessThanOrEqualTo([levels.OFF]);
assertThat(fatal).isLessThanOrEqualTo([levels.MARK, levels.OFF]);
assertThat(fatal).isNotLessThanOrEqualTo([
levels.ALL,
levels.TRACE,
@@ -295,8 +309,8 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.ERROR
]);
assertThat(fatal).isNotGreaterThanOrEqualTo([levels.OFF]);
]);
assertThat(fatal).isNotGreaterThanOrEqualTo([levels.MARK, levels.OFF]);
},
'should only be equal to FATAL': function(fatal) {
assertThat(fatal).isEqualTo([levels.toLevel("FATAL")]);
@@ -306,7 +320,48 @@ vows.describe('levels').addBatch({
levels.DEBUG,
levels.INFO,
levels.WARN,
levels.ERROR,
levels.ERROR,
levels.MARK,
levels.OFF
]);
}
},
'MARK': {
topic: levels.MARK,
'should be less than OFF': function(mark) {
assertThat(mark).isLessThanOrEqualTo([levels.OFF]);
assertThat(mark).isNotLessThanOrEqualTo([
levels.ALL,
levels.TRACE,
levels.DEBUG,
levels.INFO,
levels.WARN,
levels.FATAL,
levels.ERROR
]);
},
'should be greater than FATAL': function(mark) {
assertThat(mark).isGreaterThanOrEqualTo([
levels.ALL,
levels.TRACE,
levels.DEBUG,
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL
]);
assertThat(mark).isNotGreaterThanOrEqualTo([levels.OFF]);
},
'should only be equal to MARK': function(mark) {
assertThat(mark).isEqualTo([levels.toLevel("MARK")]);
assertThat(mark).isNotEqualTo([
levels.ALL,
levels.TRACE,
levels.DEBUG,
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL,
levels.OFF
]);
}
@@ -321,7 +376,8 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL
levels.FATAL,
levels.MARK
]);
},
'should be greater than everything': function(off) {
@@ -332,7 +388,8 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL
levels.FATAL,
levels.MARK
]);
},
'should only be equal to OFF': function(off) {
@@ -344,7 +401,8 @@ vows.describe('levels').addBatch({
levels.INFO,
levels.WARN,
levels.ERROR,
levels.FATAL
levels.FATAL,
levels.MARK
]);
}
}
@@ -353,14 +411,14 @@ vows.describe('levels').addBatch({
topic: levels.INFO,
'should handle string arguments': function(info) {
assertThat(info).isGreaterThanOrEqualTo(["all", "trace", "debug"]);
assertThat(info).isNotGreaterThanOrEqualTo(['warn', 'ERROR', 'Fatal', 'off']);
assertThat(info).isNotGreaterThanOrEqualTo(['warn', 'ERROR', 'Fatal', 'MARK', 'off']);
}
},
'isLessThanOrEqualTo': {
topic: levels.INFO,
'should handle string arguments': function(info) {
assertThat(info).isNotLessThanOrEqualTo(["all", "trace", "debug"]);
assertThat(info).isLessThanOrEqualTo(['warn', 'ERROR', 'Fatal', 'off']);
assertThat(info).isLessThanOrEqualTo(['warn', 'ERROR', 'Fatal', 'MARK', 'off']);
}
},
'isEqualTo': {

View File

@@ -1,6 +1,7 @@
"use strict";
var vows = require('vows')
, assert = require('assert')
, path = require('path')
, sandbox = require('sandboxed-module');
vows.describe('log4js-abspath').addBatch({
@@ -69,7 +70,8 @@ vows.describe('log4js-abspath').addBatch({
return fileOpened;
},
'should prepend options.cwd to config.filename': function(fileOpened) {
assert.equal(fileOpened, "/absolute/path/to/whatever.log");
var expected = path.sep + path.join("absolute", "path", "to", "whatever.log");
assert.equal(fileOpened, expected);
}
},
}).export(module);

View File

@@ -1,7 +1,9 @@
"use strict";
var vows = require('vows')
, fs = require('fs')
, assert = require('assert');
, assert = require('assert')
, os = require('os')
, EOL = require('os').EOL || '\n';
function remove(filename) {
try {
@@ -19,12 +21,13 @@ vows.describe('log4js logLevelFilter').addBatch({
log4js.addAppender(
require('../lib/appenders/logLevelFilter')
.appender(
'ERROR',
'ERROR',
undefined,
function(evt) { logEvents.push(evt); }
),
),
"logLevelTest"
);
logger = log4js.getLogger("logLevelTest");
logger.debug('this should not trigger an event');
logger.warn('neither should this');
@@ -43,26 +46,29 @@ vows.describe('log4js logLevelFilter').addBatch({
topic: function() {
var log4js = require('../lib/log4js')
, logger;
remove(__dirname + '/logLevelFilter.log');
remove(__dirname + '/logLevelFilter-warnings.log');
remove(__dirname + '/logLevelFilter-debugs.log');
log4js.configure('test/with-logLevelFilter.json');
logger = log4js.getLogger("tests");
logger.info('main');
logger.error('both');
logger.warn('both');
logger.debug('main');
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(this.callback, 100);
setTimeout(this.callback, 500);
},
'tmp-tests.log': {
topic: function() {
fs.readFile(__dirname + '/logLevelFilter.log', 'utf8', this.callback);
},
'should contain all log messages': function(contents) {
var messages = contents.trim().split('\n');
assert.deepEqual(messages, ['main','both','both','main']);
'should contain all log messages': function (contents) {
var messages = contents.trim().split(EOL);
assert.deepEqual(messages, ['debug','info','error','warn','debug','trace']);
}
},
'tmp-tests-warnings.log': {
@@ -70,8 +76,17 @@ vows.describe('log4js logLevelFilter').addBatch({
fs.readFile(__dirname + '/logLevelFilter-warnings.log','utf8',this.callback);
},
'should contain only error and warning log messages': function(contents) {
var messages = contents.trim().split('\n');
assert.deepEqual(messages, ['both','both']);
var messages = contents.trim().split(EOL);
assert.deepEqual(messages, ['error','warn']);
}
},
'tmp-tests-debugs.log': {
topic: function() {
fs.readFile(__dirname + '/logLevelFilter-debugs.log','utf8',this.callback);
},
'should contain only trace and debug log messages': function(contents) {
var messages = contents.trim().split(EOL);
assert.deepEqual(messages, ['debug','debug','trace']);
}
}
}

View File

@@ -2,7 +2,8 @@
var vows = require('vows')
, assert = require('assert')
, levels = require('../lib/levels')
, Logger = require('../lib/logger').Logger;
, loggerModule = require('../lib/logger')
, Logger = loggerModule.Logger;
vows.describe('../lib/logger').addBatch({
'constructor with no parameters': {
@@ -53,5 +54,28 @@ vows.describe('../lib/logger').addBatch({
assert.isTrue(logger.isErrorEnabled());
assert.isTrue(logger.isFatalEnabled());
}
},
'should emit log events': {
topic: function() {
var events = [],
logger = new Logger();
logger.addListener('log', function (logEvent) { events.push(logEvent); });
logger.debug('Event 1');
loggerModule.disableAllLogWrites();
logger.debug('Event 2');
loggerModule.enableAllLogWrites();
logger.debug('Event 3');
return events;
},
'when log writes are enabled': function(events) {
assert.equal(events[0].data[0], 'Event 1');
},
'but not when log writes are disabled': function(events) {
assert.equal(events.length, 2);
assert.equal(events[1].data[0], 'Event 3');
}
}
}).exportTo(module);

View File

@@ -32,6 +32,72 @@ function setupConsoleTest() {
}
vows.describe('log4js').addBatch({
'getBufferedLogger': {
topic: function () {
var log4js = require('../lib/log4js');
log4js.clearAppenders();
var logger = log4js.getBufferedLogger('tests');
return logger;
},
'should take a category and return a logger': function (logger) {
assert.equal(logger.target.category, 'tests');
assert.isFunction(logger.flush);
assert.isFunction(logger.trace);
assert.isFunction(logger.debug);
assert.isFunction(logger.info);
assert.isFunction(logger.warn);
assert.isFunction(logger.error);
assert.isFunction(logger.fatal);
},
'cache events': {
topic: function () {
var log4js = require('../lib/log4js');
log4js.clearAppenders();
var logger = log4js.getBufferedLogger('tests1');
var events = [];
logger.target.addListener("log", function (logEvent) { events.push(logEvent); });
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" });
return events;
},
'should not emit log events if .flush() is not called.': function (events) {
assert.equal(events.length, 0);
}
},
'log events after flush() is called': {
topic: function () {
var log4js = require('../lib/log4js');
log4js.clearAppenders();
var logger = log4js.getBufferedLogger('tests2');
logger.target.setLevel("TRACE");
var events = [];
logger.target.addListener("log", function (logEvent) { events.push(logEvent); });
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" });
logger.flush();
return events;
},
'should emit log events when .flush() is called.': function (events) {
assert.equal(events.length, 6);
}
}
},
'getLogger': {
topic: function() {
var log4js = require('../lib/log4js');
@@ -75,13 +141,65 @@ vows.describe('log4js').addBatch({
assert.equal(events[1].level.toString(), 'WARN');
},
'should include the error if passed in': function (events) {
'should include the error if passed in': function(events) {
assert.instanceOf(events[2].data[1], Error);
assert.equal(events[2].data[1].message, 'Pants are on fire!');
}
}
},
'when shutdown is called': {
topic: function() {
var events = {
appenderShutdownCalled: false,
shutdownCallbackCalled: false
},
log4js = sandbox.require(
'../lib/log4js',
{
requires: {
'./appenders/file':
{
name: "file",
appender: function() {},
configure: function(configuration) {
return function() {};
},
shutdown: function(cb) {
events.appenderShutdownCalled = true;
cb();
}
}
}
}
),
shutdownCallback = function() {
events.shutdownCallbackCalled = true;
},
config = { appenders:
[ { "type" : "file",
"filename" : "cheesy-wotsits.log",
"maxLogSize" : 1024,
"backups" : 3
}
]
};
log4js.configure(config);
log4js.shutdown(shutdownCallback);
// Re-enable log writing so other tests that use logger are not
// affected.
require('../lib/logger').enableAllLogWrites();
return events;
},
'should invoke appender shutdowns': function(events) {
assert.ok(events.appenderShutdownCalled);
},
'should call callback': function(events) {
assert.ok(events.shutdownCallbackCalled);
}
},
'invalid configuration': {

View File

@@ -0,0 +1,82 @@
"use strict";
var vows = require('vows')
, assert = require('assert')
, log4js = require('../lib/log4js')
, sandbox = require('sandboxed-module')
;
function setupLogging(category, options) {
var msgs = [];
var fakeLoggly = {
createClient: function (options) {
return {
config: options,
log: function (msg, tags) {
msgs.push({
msg: msg,
tags: tags
});
}
};
}
};
var fakeLayouts = {
layout: function(type, config) {
this.type = type;
this.config = config;
return log4js.layouts.messagePassThroughLayout;
},
basicLayout: log4js.layouts.basicLayout,
messagePassThroughLayout: log4js.layouts.messagePassThroughLayout
};
var fakeConsole = {
errors: [],
error: function(msg, value) {
this.errors.push({ msg: msg, value: value });
}
};
var logglyModule = sandbox.require('../lib/appenders/loggly', {
requires: {
'loggly': fakeLoggly,
'../layouts': fakeLayouts
},
globals: {
console: fakeConsole
}
});
log4js.addAppender(logglyModule.configure(options), category);
return {
logger: log4js.getLogger(category),
loggly: fakeLoggly,
layouts: fakeLayouts,
console: fakeConsole,
results: msgs
};
}
log4js.clearAppenders();
vows.describe('log4js logglyAppender').addBatch({
'minimal config': {
topic: function() {
var setup = setupLogging('loggly', {
token: 'your-really-long-input-token',
subdomain: 'your-subdomain',
tags: ['loggly-tag1', 'loggly-tag2', 'loggly-tagn']
});
setup.logger.log('trace', 'Log event #1');
return setup;
},
'there should be one message only': function (topic) {
//console.log('topic', topic);
assert.equal(topic.results.length, 1);
}
}
}).export(module);

106
test/logstashUDP-test.js Normal file
View File

@@ -0,0 +1,106 @@
"use strict";
var sys = require("sys");
var vows = require('vows')
, assert = require('assert')
, log4js = require('../lib/log4js')
, sandbox = require('sandboxed-module')
;
function setupLogging(category, options) {
var udpSent = {};
var fakeDgram = {
createSocket: function (type) {
return {
send: function(buffer, offset, length, port, host, callback) {
udpSent.date = new Date();
udpSent.host = host;
udpSent.port = port;
udpSent.length = length;
udpSent.offset = 0;
udpSent.buffer = buffer;
callback(undefined, length);
}
};
}
};
var logstashModule = sandbox.require('../lib/appenders/logstashUDP', {
requires: {
'dgram': fakeDgram
}
});
log4js.clearAppenders();
log4js.addAppender(logstashModule.configure(options), category);
return {
logger: log4js.getLogger(category),
results: udpSent
};
}
vows.describe('logstashUDP appender').addBatch({
'when logging with logstash via UDP': {
topic: function() {
var setup = setupLogging('logstashUDP', {
"host": "127.0.0.1",
"port": 10001,
"type": "logstashUDP",
"logType": "myAppType",
"category": "myLogger",
"fields": {
"field1": "value1",
"field2": "value2"
},
"layout": {
"type": "pattern",
"pattern": "%m"
}
});
setup.logger.log('trace', 'Log event #1');
return setup;
},
'an UDP packet should be sent': function (topic) {
assert.equal(topic.results.host, "127.0.0.1");
assert.equal(topic.results.port, 10001);
assert.equal(topic.results.offset, 0);
var json = JSON.parse(topic.results.buffer.toString());
assert.equal(json.type, 'myAppType');
var fields = {
field1: 'value1',
field2: 'value2',
level: 'TRACE'
};
assert.equal(JSON.stringify(json.fields), JSON.stringify(fields));
assert.equal(json.message, 'Log event #1');
// Assert timestamp, up to hours resolution.
var date = new Date(json['@timestamp']);
assert.equal(
date.toISOString().substring(0, 14),
topic.results.date.toISOString().substring(0, 14)
);
}
},
'when missing some options': {
topic: function() {
var setup = setupLogging('myLogger', {
"host": "127.0.0.1",
"port": 10001,
"type": "logstashUDP",
"category": "myLogger",
"layout": {
"type": "pattern",
"pattern": "%m"
}
});
setup.logger.log('trace', 'Log event #1');
return setup;
},
'it sets some defaults': function (topic) {
var json = JSON.parse(topic.results.buffer.toString());
assert.equal(json.type, 'myLogger');
assert.equal(JSON.stringify(json.fields), JSON.stringify({'level': 'TRACE'}));
}
}
}).export(module);

View File

@@ -1,6 +1,8 @@
"use strict";
var vows = require('vows')
, assert = require('assert')
, util = require('util')
, EE = require('events').EventEmitter
, levels = require('../lib/levels');
function MockLogger() {
@@ -31,13 +33,14 @@ function MockRequest(remoteAddr, method, originalUrl) {
}
function MockResponse(statusCode) {
var r = this;
this.statusCode = statusCode;
this.end = function(chunk, encoding) {
r.emit('finish');
};
}
util.inherits(MockResponse, EE);
vows.describe('log4js connect logger').addBatch({
'getConnectLoggerModule': {
@@ -61,9 +64,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d){
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.png'); // not gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages);
},10);
},
'check message': function(messages){
assert.isArray(messages);
@@ -81,9 +87,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.gif'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages);
},10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -103,9 +112,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d){
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.png'); // not gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages){
assert.isArray(messages);
@@ -123,9 +135,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.gif'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -136,9 +151,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.jpeg'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -157,9 +175,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d){
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.png'); // not gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages){
assert.isArray(messages);
@@ -177,9 +198,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.gif'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -191,9 +215,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.jpeg'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -212,9 +239,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d){
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.png'); // not gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages){
assert.isArray(messages);
@@ -232,9 +262,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.gif'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);
@@ -246,9 +279,12 @@ vows.describe('log4js connect logger').addBatch({
topic: function(d) {
var req = new MockRequest('my.remote.addr', 'GET', 'http://url/hoge.jpeg'); // gif
var res = new MockResponse(200);
var cb = this.callback;
d.cl(req, res, function() { });
res.end('chunk', 'encoding');
return d.ml.messages;
setTimeout(function() {
cb(null, d.ml.messages)
}, 10);
},
'check message': function(messages) {
assert.isArray(messages);

View File

@@ -7,7 +7,7 @@ var vows = require('vows')
function setupLogging(category, options) {
var msgs = [];
var fakeMailer = {
createTransport: function (name, options) {
return {
@@ -49,7 +49,7 @@ function setupLogging(category, options) {
});
log4js.addAppender(smtpModule.configure(options), category);
return {
logger: log4js.getLogger(category),
mailer: fakeMailer,
@@ -74,7 +74,6 @@ vows.describe('log4js smtpAppender').addBatch({
topic: function() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
@@ -98,7 +97,6 @@ vows.describe('log4js smtpAppender').addBatch({
recipients: 'recipient@domain.com',
sender: 'sender@domain.com',
subject: 'This is subject',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
@@ -134,7 +132,6 @@ vows.describe('log4js smtpAppender').addBatch({
var self = this;
var setup = setupLogging('separate email for each event', {
recipients: 'recipient@domain.com',
transport: "SMTP",
SMTP: {
port: 25,
auth: {
@@ -150,10 +147,10 @@ vows.describe('log4js smtpAppender').addBatch({
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
}, 1100);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
}, 3000);
},
'there should be three messages': function (result) {
assert.equal(result.results.length, 3);
@@ -168,7 +165,6 @@ vows.describe('log4js smtpAppender').addBatch({
var setup = setupLogging('multiple events in one email', {
recipients: 'recipient@domain.com',
sendInterval: 1,
transport: "SMTP",
SMTP: {
port: 25,
auth: {
@@ -181,13 +177,13 @@ vows.describe('log4js smtpAppender').addBatch({
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
}, 100);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1050);
}, 1500);
setTimeout(function () {
self.callback(null, setup);
}, 2100);
}, 3000);
},
'there should be two messages': function (result) {
assert.equal(result.results.length, 2);
@@ -206,7 +202,6 @@ vows.describe('log4js smtpAppender').addBatch({
var setup = setupLogging('error when sending email', {
recipients: 'recipient@domain.com',
sendInterval: 0,
transport: 'SMTP',
SMTP: { port: 25, auth: { user: 'user@domain.com' } }
});
@@ -218,7 +213,7 @@ vows.describe('log4js smtpAppender').addBatch({
close: function() { }
};
};
setup.logger.info("This will break");
return setup.console;
},
@@ -228,6 +223,4 @@ vows.describe('log4js smtpAppender').addBatch({
assert.equal(cons.errors[0].value.message, 'oh noes');
}
}
}).export(module);

View File

@@ -122,7 +122,7 @@ vows.describe('RollingFileStream').addBatch({
__dirname + "/test-rolling-file-stream-write-more",
45
);
async.forEach(
async.each(
[0, 1, 2, 3, 4, 5, 6],
function(i, cb) {
stream.write(i +".cheese\n", "utf8", cb);
@@ -183,7 +183,7 @@ vows.describe('RollingFileStream').addBatch({
45,
5
);
async.forEach(
async.each(
[0, 1, 2, 3, 4, 5, 6],
function(i, cb) {
stream.write(i +".cheese\n", "utf8", cb);

View File

@@ -0,0 +1,86 @@
"use strict";
var assert = require('assert')
, vows = require('vows')
, sandbox = require('sandboxed-module')
, log4js = require('../lib/log4js')
, levels = require('../lib/levels');
vows.describe('subcategories').addBatch({
'loggers created after levels configuration is loaded': {
topic: function() {
log4js.configure({
"levels": {
"sub1": "WARN",
"sub1.sub11": "TRACE",
"sub1.sub11.sub111": "WARN",
"sub1.sub12": "INFO"
}
}, { reloadSecs: 30 })
return {
"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
};
},
'check logger levels': function(loggers) {
assert.equal(loggers.sub1.level, levels.WARN);
assert.equal(loggers.sub11.level, levels.TRACE);
assert.equal(loggers.sub111.level, levels.WARN);
assert.equal(loggers.sub12.level, levels.INFO);
assert.equal(loggers.sub13.level, levels.WARN);
assert.equal(loggers.sub112.level, levels.TRACE);
assert.equal(loggers.sub121.level, levels.INFO);
assert.equal(loggers.sub0.level, levels.TRACE);
}
},
'loggers created before levels configuration is loaded': {
topic: function() {
var 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
};
log4js.configure({
"levels": {
"sub1": "WARN",
"sub1.sub11": "TRACE",
"sub1.sub11.sub111": "WARN",
"sub1.sub12": "INFO"
}
}, { reloadSecs: 30 })
return loggers;
},
'check logger levels': function(loggers) {
assert.equal(loggers.sub1.level, levels.WARN);
assert.equal(loggers.sub11.level, levels.TRACE);
assert.equal(loggers.sub111.level, levels.WARN);
assert.equal(loggers.sub12.level, levels.INFO);
assert.equal(loggers.sub13.level, levels.WARN);
assert.equal(loggers.sub112.level, levels.TRACE);
assert.equal(loggers.sub121.level, levels.INFO);
assert.equal(loggers.sub0.level, levels.TRACE);
}
}
}).exportTo(module);

View File

@@ -12,6 +12,19 @@
}
}
},
{
"category": "tests",
"type": "logLevelFilter",
"level": "TRACE",
"maxLevel": "DEBUG",
"appender": {
"type": "file",
"filename": "test/logLevelFilter-debugs.log",
"layout": {
"type": "messagePassThrough"
}
}
},
{
"category": "tests",
"type": "file",
@@ -23,6 +36,6 @@
],
"levels": {
"tests": "DEBUG"
"tests": "TRACE"
}
}