Bunyan Rotating File Stream is a stream component for the logging system "node bunyan" that provides rich and flexible control over your log files. [](https://gitter.im/Rcomian/bunyan-rotating-file-stream?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ```js var log = bunyan.createLogger({ name: 'foo', streams: [{ stream: new RotatingFileStream({ path: '/var/log/foo.log', period: '1d', // daily rotation totalFiles: 10, // keep up to 10 back copies rotateExisting: true, // Give ourselves a clean file when we start up, based on period threshold: '10m', // Rotate log files larger than 10 megabytes totalSize: '20m', // Don't keep more than 20mb of archived log files gzip: true // Compress the archive log files to save space }) }] }); ``` # Recent changes ## 1.6.3 Type definition file for Typescript Generously provided by: scippio ## 1.6.2 Fixed support for the "rotateExisting" flag Tests have been added to ensure that this feature keeps working in the future. Note that this feature may not work as expected with linux on EXT4. ## 1.6 Support for non-JSON logs Minor release but now that logs which are written in a non-json format are supported. ## 1.5 Templates Release We now have the ability to specify templates in the log's filename. For full details see the templating section, but briefly: we can template where you put the number when rotating files (this allows you to preserve the extension so that the files open in the correct viewer), or give your log filename a timestamp in your preferred format. All previous features are maintained and you should be able to use your existing configuration without change. Integration testing is still rudimentary in terms of technology, but the coverage has been massively improved, checking that no logs have been re-ordered or lost. # Compatibility Implemented tests and strategies to support specific node versions: * 0.12.*latest* * 4.*latest* * 6.*latest* * 7.*latest* *0.10 and earlier* Not supported as it is missing a lot of useful path processing features. Whilst we could patch this with inline code and npm packages, I think it's a shame to have these hanging around when the functionality will be built into all future versions of node. *0.12* Is supported, but it's performance cannot keep up with the latest versions of node. I've had to reduce the stress involved when running tests to allow old `0.12` to keep up. *5* Is supported, but won't be stress tested as those resources are being used for the LTS releases 0.12, 4 & 6. # Current Status The basics of the features are there, you should be able to use the rotating file logging to limit disk space usage while maximising the amount of logs kept. There are a few extra features to add to the system, but in general it needs stabilisation, code cleanup and bug fixing. We can now regularly run feature tests against all supported versions of node. # Planned Future Features * Prevent multiple processes logging to the same file * Allow multiple processes to safely log to the same file * Allow you to say where to put the number in date formatted file names # Installation ```sh npm install bunyan-rotating-file-stream ``` # Main Features - Name log files with templates - Rotate to a new log file periodically (can also rotate on startup to clean old log files) - Rotate to a new log file once the main log file goes over a certain size - Keep a maximum number of archival log files - Delete older log files once the archive reaches a certain size - GZip archived log files - Supports being a raw stream or a normal stream ## How to use **WARNING on node 0.8 usage:** Users should use at least node 0.10 (node 0.8 does not support the `unref()` method on `setTimeout(...)`). The symptom is that process termination will hang for up to a full rotation period if period rotation is used. You can manually keep hold of the logger and call "shutdown" to prevent this. **WARNING on [cluster](http://nodejs.org/docs/latest/api/all.html#all_cluster) usage:** Using `bunyan-rotating-file-stream` with node.js's "cluster" module can result in unexpected file rotation. You must not have multiple processes in the cluster logging to the same file path. In other words, you must have a separate log file path for the master and each worker in the cluster. Alternatively, consider using a system file rotation facility such as `logrotate` on Linux or `logadm` on SmartOS/Illumos. See [this comment on issue #117](https://github.com/trentm/node-bunyan/issues/117#issuecomment-44804938) for details. Add this stream directly to the bunyan logger. The stream supports being both a raw and normal stream modes. Raw streams can be faster under some high-load scenarios but may serialize the json differently to bunyan. ```js var bunyan = require('bunyan'); var RotatingFileStream = require('bunyan-rotating-file-stream'); var log = bunyan.createLogger({ name: 'foo', streams: [{ type: 'raw', stream: new RotatingFileStream({ path: '/var/log/foo.log', period: '1d', // daily rotation totalFiles: 10, // keep 10 back copies rotateExisting: true, // Give ourselves a clean file when we start up, based on period threshold: '10m', // Rotate log files larger than 10 megabytes totalSize: '20m', // Don't keep more than 20mb of archived log files gzip: true // Compress the archive log files to save space }) }] }); ``` This will rotate '/var/log/foo.log' every day (at midnight) to: ```sh /var/log/foo.log.1 # yesterday /var/log/foo.log.2 # 1 day ago /var/log/foo.log.3 # 2 days ago ```
Field | Required? | Default | Description |
---|---|---|---|
path | Yes | - | A file path to which to log. Rotated files will be "$path.0", "$path.1", ... |
period | No | 1d | The period at which to rotate. This is a string of the format "$number$scope" where "$scope" is one of "ms" (milliseconds -- only useful for testing), "h" (hours), "d" (days), "w" (weeks), "m" (months), "y" (years). Or one of the following names can be used "hourly" (means 1h), "daily" (1d), "weekly" (1w), "monthly" (1m), "yearly" (1y). Rotation is done at the start of the scope: top of the hour (h), midnight (d), start of Sunday (w), start of the 1st of the month (m), start of Jan 1st (y). |
rotateExisting | No | false | If period is also set, will rotate an existing log file when the process starts up if that file needs rotating due to its age. This means that if you want a new file every day, and the process isn't running over midnight, this option will give you that new file when you next startup. See note on EXT4. |
threshold | No | 0 | The maximum size for a log file to reach before it's rotated. Can be specified as a number of bytes, or a more friendly units: eg, '100k', '1m', '2g' etc. |
totalFiles | No | 0 | The maximum number of rotated files to keep. 0 to keep files regardless of how many there are. |
totalSize | No | 0 | The maximum storage to allow for the rotated files. Older files are deleted to keep within this size. 0 here keeps files regardless of how large they get. Can be specified as a number of bytes, or a more friendly unit: eg, '100k', '1m', '2g' etc. |
gzip | No | false | Compress rotated files using gzip. Adds a '.gz' extension. |
fieldOrder | No | An array of string that specify the order the log parameters are written to the file. This option allows certain keys in the log fields to be written first for each log entry in the file. For example, if you use the value ['time'], the timestamp will appear on the left of each row. This doesn't affect how programs read each log record if they just JSON.parse each line at a time, it's purely for visual browsing when you scan through the text file. For this to work, the stream must be set to "raw" mode. You can't use this option without that setting. This option has a measurable performance impact as it's copying each log entry object, so be aware if you're using this in heavily loaded systems. *note* This feature currently works using an undocumented and un-guaranteed side effect of how serialisation works. It may break for a time on new versions of node if the internals of serialisation change how things work. In that case, the replacement code will likely be even slower. |
|
startNewFile | No | false |
By default the file stream will open the most recent log file it can find and append to it. This flag will force the stream to create a new file instead. |