├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTORS ├── Gemfile ├── LICENSE ├── NOTICE.TXT ├── README.md ├── Rakefile ├── docs └── index.asciidoc ├── lib └── logstash │ └── outputs │ └── file.rb ├── logstash-output-file.gemspec └── spec └── outputs └── file_spec.rb /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Logstash 2 | 3 | All contributions are welcome: ideas, patches, documentation, bug reports, 4 | complaints, etc! 5 | 6 | Programming is not a required skill, and there are many ways to help out! 7 | It is more important to us that you are able to contribute. 8 | 9 | That said, some basic guidelines, which you are free to ignore :) 10 | 11 | ## Want to learn? 12 | 13 | Want to lurk about and see what others are doing with Logstash? 14 | 15 | * The irc channel (#logstash on irc.freenode.org) is a good place for this 16 | * The [forum](https://discuss.elastic.co/c/logstash) is also 17 | great for learning from others. 18 | 19 | ## Got Questions? 20 | 21 | Have a problem you want Logstash to solve for you? 22 | 23 | * You can ask a question in the [forum](https://discuss.elastic.co/c/logstash) 24 | * Alternately, you are welcome to join the IRC channel #logstash on 25 | irc.freenode.org and ask for help there! 26 | 27 | ## Have an Idea or Feature Request? 28 | 29 | * File a ticket on [GitHub](https://github.com/elastic/logstash/issues). Please remember that GitHub is used only for issues and feature requests. If you have a general question, the [forum](https://discuss.elastic.co/c/logstash) or IRC would be the best place to ask. 30 | 31 | ## Something Not Working? Found a Bug? 32 | 33 | If you think you found a bug, it probably is a bug. 34 | 35 | * If it is a general Logstash or a pipeline issue, file it in [Logstash GitHub](https://github.com/elasticsearch/logstash/issues) 36 | * If it is specific to a plugin, please file it in the respective repository under [logstash-plugins](https://github.com/logstash-plugins) 37 | * or ask the [forum](https://discuss.elastic.co/c/logstash). 38 | 39 | # Contributing Documentation and Code Changes 40 | 41 | If you have a bugfix or new feature that you would like to contribute to 42 | logstash, and you think it will take more than a few minutes to produce the fix 43 | (ie; write code), it is worth discussing the change with the Logstash users and developers first! You can reach us via [GitHub](https://github.com/elastic/logstash/issues), the [forum](https://discuss.elastic.co/c/logstash), or via IRC (#logstash on freenode irc) 44 | Please note that Pull Requests without tests will not be merged. If you would like to contribute but do not have experience with writing tests, please ping us on IRC/forum or create a PR and ask our help. 45 | 46 | ## Contributing to plugins 47 | 48 | Check our [documentation](https://www.elastic.co/guide/en/logstash/current/contributing-to-logstash.html) on how to contribute to plugins or write your own! It is super easy! 49 | 50 | ## Contribution Steps 51 | 52 | 1. Test your changes! [Run](https://github.com/elastic/logstash#testing) the test suite 53 | 2. Please make sure you have signed our [Contributor License 54 | Agreement](https://www.elastic.co/contributor-agreement/). We are not 55 | asking you to assign copyright to us, but to give us the right to distribute 56 | your code without restriction. We ask this of all contributors in order to 57 | assure our users of the origin and continuing existence of the code. You 58 | only need to sign the CLA once. 59 | 3. Send a pull request! Push your changes to your fork of the repository and 60 | [submit a pull 61 | request](https://help.github.com/articles/using-pull-requests). In the pull 62 | request, describe what your changes do and mention any bugs/issues related 63 | to the pull request. 64 | 65 | 66 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please post all product and debugging questions on our [forum](https://discuss.elastic.co/c/logstash). Your questions will reach our wider community members there, and if we confirm that there is a bug, then we can open a new issue here. 2 | 3 | For all general issues, please provide the following details for fast resolution: 4 | 5 | - Version: 6 | - Operating System: 7 | - Config File (if you have sensitive info, please remove it): 8 | - Sample Data: 9 | - Steps to Reproduce: 10 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for contributing to Logstash! If you haven't already signed our CLA, here's a handy link: https://www.elastic.co/contributor-agreement/ 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | Gemfile.lock 3 | .bundle 4 | vendor 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | import: 2 | - logstash-plugins/.ci:travis/travis.yml@1.x -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## unreleased 2 | - Fixed unit tests to account for ECS by default [#94](https://github.com/logstash-plugins/logstash-output-file/pull/94) 3 | - Fixed .ci integration [#94](https://github.com/logstash-plugins/logstash-output-file/pull/94) 4 | 5 | ## 4.3.0 6 | - Made `stale_cleanup_interval` configurable [#84](https://github.com/logstash-plugins/logstash-output-file/pull/84) 7 | - CI: upgrade testing [#83](https://github.com/logstash-plugins/logstash-output-file/pull/83) 8 | 9 | ## 4.2.6 10 | - Removed JRuby check when using FIFOs [#75](https://github.com/logstash-plugins/logstash-output-file/pull/75) 11 | 12 | ## 4.2.5 13 | - Fix a bug introduced in v4.2.4 where events on low-volume pipelines could remain unflushed for long periods when `flush_interval` was non-zero [#70](https://github.com/logstash-plugins/logstash-output-file/pull/70) 14 | 15 | ## 4.2.4 16 | - Fix a bug where flush interval was being called for each event when enabled [#67](https://github.com/logstash-plugins/logstash-output-file/pull/67) 17 | 18 | ## 4.2.3 19 | - Docs: Set the default_codec doc attribute. 20 | 21 | ## 4.2.2 22 | - Add feature `write_behavior` to the documentation #58 23 | 24 | ## 4.2.1 25 | - Bugfix: Move require of flores into the spec file instead of main file.rb 26 | 27 | ## 4.2.0 28 | - New `write_behavior` feature. Value can be "append" (default) or 29 | "overwrite". If "append", events will be appended to the end of the file. 30 | If "overwrite", the file will only contain the last event written. 31 | 32 | ## 4.1.2 33 | - Update gemspec summary 34 | 35 | ## 4.1.1 36 | - Fix some documentation issues 37 | 38 | ## 4.1.0 39 | - Remove obsolete option `message_format` 40 | 41 | ## 4.0.1 42 | - Move one log message from info to debug to avoid noise 43 | 44 | ## 4.0.0 45 | - Make 'message_format' option obsolete 46 | - Use new Logsash 2.4/5.0 APIs for working batchwise and with shared concurrency 47 | 48 | ## 3.0.2 49 | - Relax constraint on logstash-core-plugin-api to >= 1.60 <= 2.99 50 | 51 | ## 3.0.1 52 | - Republish all the gems under jruby. 53 | ## 3.0.0 54 | - Update the plugin to the version 2.0 of the plugin api, this change is required for Logstash 5.0 compatibility. See https://github.com/elastic/logstash/issues/5141 55 | # 2.2.5 56 | - Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash 57 | # 2.2.4 58 | - New dependency requirements for logstash-core for the 5.0 release 59 | ## 2.2.3 60 | - Rename Dir.exists? to Dir.exist? to fix deprecation warning 61 | - Allow setting dir and file permissions 62 | 63 | ## 2.2.1 64 | - Fixed specs to not depend on pipeline ordering 65 | 66 | ## 2.2.1 67 | - Fixed Time specs 68 | 69 | ## 2.2.0 70 | - Add support for codec, using **json_lines** as default codec to keep default behavior. 71 | Ref: https://github.com/logstash-plugins/logstash-output-file/pull/9 72 | 73 | ## 2.1.0 74 | - Add create_if_deleted option to create a destination file in case it 75 | was deleted by another agent in the machine. In case of being false 76 | the system will add the incomming messages to the failure file. 77 | 78 | ## 2.0.0 79 | - Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully, 80 | instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895 81 | - Dependency on logstash-core update to 2.0 82 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | The following is a list of people who have contributed ideas, code, bug 2 | reports, or in general have helped logstash along its way. 3 | 4 | Contributors: 5 | * Colin Surprenant (colinsurprenant) 6 | * Ivan Babrou (bobrik) 7 | * John E. Vincent (lusis) 8 | * Jordan Sissel (jordansissel) 9 | * Kayla Green (MixMuffins) 10 | * Kurt Hurtado (kurtado) 11 | * Matt Gray (mattgray) 12 | * Pete Fritchman (fetep) 13 | * Philippe Weber (wiibaa) 14 | * Pier-Hugues Pellerin (ph) 15 | * Richard Pijnenburg (electrical) 16 | 17 | Note: If you've sent us patches, bug reports, or otherwise contributed to 18 | Logstash, and you aren't on the list above and want to be, please let us know 19 | and we'll make sure you're here. Contributions from folks like you are what make 20 | open source awesome. 21 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gemspec 4 | 5 | logstash_path = ENV["LOGSTASH_PATH"] || "../../logstash" 6 | use_logstash_source = ENV["LOGSTASH_SOURCE"] && ENV["LOGSTASH_SOURCE"].to_s == "1" 7 | 8 | if Dir.exist?(logstash_path) && use_logstash_source 9 | gem 'logstash-core', :path => "#{logstash_path}/logstash-core" 10 | gem 'logstash-core-plugin-api', :path => "#{logstash_path}/logstash-core-plugin-api" 11 | end 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2020 Elastic and contributors 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE.TXT: -------------------------------------------------------------------------------- 1 | Elasticsearch 2 | Copyright 2012-2015 Elasticsearch 3 | 4 | This product includes software developed by The Apache Software 5 | Foundation (http://www.apache.org/). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Logstash Plugin 2 | 3 | [![Travis Build Status](https://travis-ci.com/logstash-plugins/logstash-output-file.svg)](https://travis-ci.com/logstash-plugins/logstash-output-file) 4 | 5 | This is a plugin for [Logstash](https://github.com/elastic/logstash). 6 | 7 | It is fully free and fully open source. The license is Apache 2.0, meaning you are pretty much free to use it however you want in whatever way. 8 | 9 | ## Documentation 10 | 11 | Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elastic.co/guide/en/logstash/current/). 12 | 13 | - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive 14 | - For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide 15 | 16 | ## Need Help? 17 | 18 | Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum. 19 | 20 | ## Developing 21 | 22 | ### 1. Plugin Developement and Testing 23 | 24 | #### Code 25 | - To get started, you'll need JRuby with the Bundler gem installed. 26 | 27 | - Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization. We also provide [example plugins](https://github.com/logstash-plugins?query=example). 28 | 29 | - Install dependencies 30 | ```sh 31 | bundle install 32 | ``` 33 | 34 | #### Test 35 | 36 | - Update your dependencies 37 | 38 | ```sh 39 | bundle install 40 | ``` 41 | 42 | - Run tests 43 | 44 | ```sh 45 | bundle exec rspec 46 | ``` 47 | 48 | ### 2. Running your unpublished Plugin in Logstash 49 | 50 | #### 2.1 Run in a local Logstash clone 51 | 52 | - Edit Logstash `Gemfile` and add the local plugin path, for example: 53 | ```ruby 54 | gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome" 55 | ``` 56 | - Install plugin 57 | ```sh 58 | # Logstash 2.3 and higher 59 | bin/logstash-plugin install --no-verify 60 | 61 | # Prior to Logstash 2.3 62 | bin/plugin install --no-verify 63 | 64 | ``` 65 | - Run Logstash with your plugin 66 | ```sh 67 | bin/logstash -e 'filter {awesome {}}' 68 | ``` 69 | At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash. 70 | 71 | #### 2.2 Run in an installed Logstash 72 | 73 | You can use the same **2.1** method to run your plugin in an installed Logstash by editing its `Gemfile` and pointing the `:path` to your local plugin development directory or you can build the gem and install it using: 74 | 75 | - Build your plugin gem 76 | ```sh 77 | gem build logstash-filter-awesome.gemspec 78 | ``` 79 | - Install the plugin from the Logstash home 80 | ```sh 81 | # Logstash 2.3 and higher 82 | bin/logstash-plugin install --no-verify 83 | 84 | # Prior to Logstash 2.3 85 | bin/plugin install --no-verify 86 | 87 | ``` 88 | - Start Logstash and proceed to test the plugin 89 | 90 | ## Contributing 91 | 92 | All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin. 93 | 94 | Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here. 95 | 96 | It is more important to the community that you are able to contribute. 97 | 98 | For more information about contributing, see the [CONTRIBUTING](https://github.com/elastic/logstash/blob/master/CONTRIBUTING.md) file. -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | @files=[] 2 | 3 | task :default do 4 | system("rake -T") 5 | end 6 | 7 | require "logstash/devutils/rake" 8 | -------------------------------------------------------------------------------- /docs/index.asciidoc: -------------------------------------------------------------------------------- 1 | :plugin: file 2 | :type: output 3 | :default_codec: json_lines 4 | 5 | /////////////////////////////////////////// 6 | START - GENERATED VARIABLES, DO NOT EDIT! 7 | /////////////////////////////////////////// 8 | :version: %VERSION% 9 | :release_date: %RELEASE_DATE% 10 | :changelog_url: %CHANGELOG_URL% 11 | :include_path: ../../../../logstash/docs/include 12 | /////////////////////////////////////////// 13 | END - GENERATED VARIABLES, DO NOT EDIT! 14 | /////////////////////////////////////////// 15 | 16 | [id="plugins-{type}s-{plugin}"] 17 | 18 | === File output plugin 19 | 20 | include::{include_path}/plugin_header.asciidoc[] 21 | 22 | ==== Description 23 | 24 | This output writes events to files on disk. You can use fields 25 | from the event as parts of the filename and/or path. 26 | 27 | By default, this output writes one event per line in **json** format. 28 | You can customise the line format using the `line` codec like 29 | [source,ruby] 30 | output { 31 | file { 32 | path => ... 33 | codec => line { format => "custom format: %{message}"} 34 | } 35 | } 36 | 37 | [id="plugins-{type}s-{plugin}-options"] 38 | ==== File Output Configuration Options 39 | 40 | This plugin supports the following configuration options plus the <> described later. 41 | 42 | [cols="<,<,<",options="header",] 43 | |======================================================================= 44 | |Setting |Input type|Required 45 | | <> |<>|No 46 | | <> |<>|No 47 | | <> |<>|No 48 | | <> |<>|No 49 | | <> |<>|No 50 | | <> |<>|No 51 | | <> |<>|Yes 52 | | <> |<>|No 53 | | <> |<>|No 54 | |======================================================================= 55 | 56 | Also see <> for a list of options supported by all 57 | output plugins. 58 | 59 |   60 | 61 | [id="plugins-{type}s-{plugin}-create_if_deleted"] 62 | ===== `create_if_deleted` 63 | 64 | * Value type is <> 65 | * Default value is `true` 66 | 67 | If the configured file is deleted, but an event is handled by the plugin, 68 | the plugin will recreate the file. Default => true 69 | 70 | [id="plugins-{type}s-{plugin}-dir_mode"] 71 | ===== `dir_mode` 72 | 73 | * Value type is <> 74 | * Default value is `-1` 75 | 76 | Dir access mode to use. Note that due to the bug in jruby system umask 77 | is ignored on linux: https://github.com/jruby/jruby/issues/3426 78 | Setting it to -1 uses default OS value. 79 | Example: `"dir_mode" => 0750` 80 | 81 | [id="plugins-{type}s-{plugin}-file_mode"] 82 | ===== `file_mode` 83 | 84 | * Value type is <> 85 | * Default value is `-1` 86 | 87 | File access mode to use. Note that due to the bug in jruby system umask 88 | is ignored on linux: https://github.com/jruby/jruby/issues/3426 89 | Setting it to -1 uses default OS value. 90 | Example: `"file_mode" => 0640` 91 | 92 | [id="plugins-{type}s-{plugin}-filename_failure"] 93 | ===== `filename_failure` 94 | 95 | * Value type is <> 96 | * Default value is `"_filepath_failures"` 97 | 98 | If the generated path is invalid, the events will be saved 99 | into this file and inside the defined path. 100 | 101 | [id="plugins-{type}s-{plugin}-flush_interval"] 102 | ===== `flush_interval` 103 | 104 | * Value type is <> 105 | * Default value is `2` 106 | 107 | Flush interval (in seconds) for flushing writes to log files. 108 | 0 will flush on every message. 109 | 110 | [id="plugins-{type}s-{plugin}-gzip"] 111 | ===== `gzip` 112 | 113 | * Value type is <> 114 | * Default value is `false` 115 | 116 | Gzip the output stream before writing to disk. 117 | 118 | [id="plugins-{type}s-{plugin}-path"] 119 | ===== `path` 120 | 121 | * This is a required setting. 122 | * Value type is <> 123 | * There is no default value for this setting. 124 | 125 | The path to the file to write. Event fields can be used here, 126 | like `/var/log/logstash/%{host}/%{application}` 127 | One may also utilize the path option for date-based log 128 | rotation via the joda time format. This will use the event 129 | timestamp. 130 | E.g.: `path => "./test-%{+YYYY-MM-dd}.txt"` to create 131 | `./test-2013-05-29.txt` 132 | 133 | If you use an absolute path you cannot start with a dynamic string. 134 | E.g: `/%{myfield}/`, `/test-%{myfield}/` are not valid paths 135 | 136 | [id="plugins-{type}s-{plugin}-stale_cleanup_interval"] 137 | ===== `stale_cleanup_interval` 138 | 139 | * Value type is <> 140 | * Default value is `10` 141 | 142 | Defines the interval, in seconds, between the stale files cleanup runs. 143 | The stale files cleanup cycle closes inactive files (i.e files not written to since the last cycle). 144 | 145 | [id="plugins-{type}s-{plugin}-write_behavior"] 146 | ===== `write_behavior` 147 | 148 | * Value type is <> 149 | * Default value is `append` 150 | 151 | If `append`, the file will be opened for appending and each new event will be written at the end of the file. 152 | If `overwrite`, the file will be truncated before writing and only the most recent event will appear in the file. 153 | [id="plugins-{type}s-{plugin}-common-options"] 154 | 155 | include::{include_path}/{type}.asciidoc[] 156 | 157 | :default_codec!: 158 | -------------------------------------------------------------------------------- /lib/logstash/outputs/file.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "logstash/namespace" 3 | require "logstash/outputs/base" 4 | require "logstash/errors" 5 | require "zlib" 6 | 7 | # This output writes events to files on disk. You can use fields 8 | # from the event as parts of the filename and/or path. 9 | # 10 | # By default, this output writes one event per line in **json** format. 11 | # You can customise the line format using the `line` codec like 12 | # [source,ruby] 13 | # output { 14 | # file { 15 | # path => ... 16 | # codec => line { format => "custom format: %{message}"} 17 | # } 18 | # } 19 | class LogStash::Outputs::File < LogStash::Outputs::Base 20 | concurrency :shared 21 | 22 | FIELD_REF = /%\{[^}]+\}/ 23 | 24 | config_name "file" 25 | 26 | attr_reader :failure_path 27 | 28 | # The path to the file to write. Event fields can be used here, 29 | # like `/var/log/logstash/%{host}/%{application}` 30 | # One may also utilize the path option for date-based log 31 | # rotation via the joda time format. This will use the event 32 | # timestamp. 33 | # E.g.: `path => "./test-%{+YYYY-MM-dd}.txt"` to create 34 | # `./test-2013-05-29.txt` 35 | # 36 | # If you use an absolute path you cannot start with a dynamic string. 37 | # E.g: `/%{myfield}/`, `/test-%{myfield}/` are not valid paths 38 | config :path, :validate => :string, :required => true 39 | 40 | # Flush interval (in seconds) for flushing writes to log files. 41 | # 0 will flush on every message. 42 | config :flush_interval, :validate => :number, :default => 2 43 | 44 | # Gzip the output stream before writing to disk. 45 | config :gzip, :validate => :boolean, :default => false 46 | 47 | # If the generated path is invalid, the events will be saved 48 | # into this file and inside the defined path. 49 | config :filename_failure, :validate => :string, :default => '_filepath_failures' 50 | 51 | # If the configured file is deleted, but an event is handled by the plugin, 52 | # the plugin will recreate the file. Default => true 53 | config :create_if_deleted, :validate => :boolean, :default => true 54 | 55 | # Dir access mode to use. Note that due to the bug in jruby system umask 56 | # is ignored on linux: https://github.com/jruby/jruby/issues/3426 57 | # Setting it to -1 uses default OS value. 58 | # Example: `"dir_mode" => 0750` 59 | config :dir_mode, :validate => :number, :default => -1 60 | 61 | # File access mode to use. Note that due to the bug in jruby system umask 62 | # is ignored on linux: https://github.com/jruby/jruby/issues/3426 63 | # Setting it to -1 uses default OS value. 64 | # Example: `"file_mode" => 0640` 65 | config :file_mode, :validate => :number, :default => -1 66 | 67 | 68 | # How should the file be written? 69 | # 70 | # If `append`, the file will be opened for appending and each new event will 71 | # be written at the end of the file. 72 | # 73 | # If `overwrite`, the file will be truncated before writing and only the most 74 | # recent event will appear in the file. 75 | config :write_behavior, :validate => [ "overwrite", "append" ], :default => "append" 76 | 77 | # How often should the stale files cleanup cycle run (in seconds). 78 | # The stale files cleanup cycle closes inactive files (i.e files not written to since the last cycle). 79 | config :stale_cleanup_interval, :validate => :number, :default => 10 80 | 81 | 82 | default :codec, "json_lines" 83 | 84 | def register 85 | require "fileutils" # For mkdir_p 86 | 87 | @files = {} 88 | @io_mutex = Mutex.new 89 | 90 | @path = File.expand_path(path) 91 | 92 | validate_path 93 | 94 | if path_with_field_ref? 95 | @file_root = extract_file_root 96 | else 97 | @file_root = File.dirname(path) 98 | end 99 | @failure_path = File.join(@file_root, @filename_failure) 100 | 101 | @flush_interval = @flush_interval.to_i 102 | if @flush_interval > 0 103 | @flusher = Interval.start(@flush_interval, -> { flush_pending_files }) 104 | end 105 | 106 | @last_stale_cleanup_cycle = Time.now 107 | end 108 | 109 | def multi_receive_encoded(events_and_encoded) 110 | encoded_by_path = Hash.new {|h,k| h[k] = []} 111 | 112 | events_and_encoded.each do |event,encoded| 113 | file_output_path = event_path(event) 114 | encoded_by_path[file_output_path] << encoded 115 | end 116 | 117 | @io_mutex.synchronize do 118 | encoded_by_path.each do |path,chunks| 119 | fd = open(path) 120 | if @write_behavior == "overwrite" 121 | fd.truncate(0) 122 | fd.seek(0, IO::SEEK_SET) 123 | fd.write(chunks.last) 124 | else 125 | # append to the file 126 | chunks.each {|chunk| fd.write(chunk) } 127 | end 128 | fd.flush unless @flusher && @flusher.alive? 129 | end 130 | 131 | close_stale_files 132 | end 133 | end 134 | 135 | def close 136 | @flusher.stop unless @flusher.nil? 137 | @io_mutex.synchronize do 138 | @logger.debug("Close: closing files") 139 | 140 | @files.each do |path, fd| 141 | begin 142 | fd.close 143 | @logger.debug("Closed file #{path}", :fd => fd) 144 | rescue Exception => e 145 | @logger.error("Exception while flushing and closing files.", :exception => e) 146 | end 147 | end 148 | end 149 | end 150 | 151 | private 152 | 153 | def validate_path 154 | if (root_directory =~ FIELD_REF) != nil 155 | @logger.error("File: The starting part of the path should not be dynamic.", :path => @path) 156 | raise LogStash::ConfigurationError.new("The starting part of the path should not be dynamic.") 157 | end 158 | end 159 | 160 | def root_directory 161 | parts = @path.split(File::SEPARATOR).select { |item| !item.empty? } 162 | if Gem.win_platform? 163 | # First part is the drive letter 164 | parts[1] 165 | else 166 | parts.first 167 | end 168 | end 169 | 170 | def inside_file_root?(log_path) 171 | target_file = File.expand_path(log_path) 172 | return target_file.start_with?("#{@file_root.to_s}/") 173 | end 174 | 175 | def event_path(event) 176 | file_output_path = generate_filepath(event) 177 | if path_with_field_ref? && !inside_file_root?(file_output_path) 178 | @logger.warn("File: the event tried to write outside the files root, writing the event to the failure file", :event => event, :filename => @failure_path) 179 | file_output_path = @failure_path 180 | elsif !@create_if_deleted && deleted?(file_output_path) 181 | file_output_path = @failure_path 182 | end 183 | @logger.debug("File, writing event to file.", :filename => file_output_path) 184 | 185 | file_output_path 186 | end 187 | 188 | def generate_filepath(event) 189 | event.sprintf(@path) 190 | end 191 | 192 | def path_with_field_ref? 193 | path =~ FIELD_REF 194 | end 195 | 196 | def extract_file_root 197 | parts = File.expand_path(path).split(File::SEPARATOR) 198 | parts.take_while { |part| part !~ FIELD_REF }.join(File::SEPARATOR) 199 | end 200 | 201 | # the back-bone of @flusher, our periodic-flushing interval. 202 | def flush_pending_files 203 | @io_mutex.synchronize do 204 | @logger.debug("Starting flush cycle") 205 | 206 | @files.each do |path, fd| 207 | @logger.debug("Flushing file", :path => path, :fd => fd) 208 | fd.flush 209 | end 210 | end 211 | rescue => e 212 | # squash exceptions caught while flushing after logging them 213 | @logger.error("Exception flushing files", :exception => e.message, :backtrace => e.backtrace) 214 | end 215 | 216 | # every 10 seconds or so (triggered by events, but if there are no events there's no point closing files anyway) 217 | def close_stale_files 218 | now = Time.now 219 | return unless now - @last_stale_cleanup_cycle >= @stale_cleanup_interval 220 | 221 | @logger.debug("Starting stale files cleanup cycle", :files => @files) 222 | inactive_files = @files.select { |path, fd| not fd.active } 223 | @logger.debug("%d stale files found" % inactive_files.count, :inactive_files => inactive_files) 224 | inactive_files.each do |path, fd| 225 | @logger.info("Closing file %s" % path) 226 | fd.close 227 | @files.delete(path) 228 | end 229 | # mark all files as inactive, a call to write will mark them as active again 230 | @files.each { |path, fd| fd.active = false } 231 | @last_stale_cleanup_cycle = now 232 | end 233 | 234 | def cached?(path) 235 | @files.include?(path) && !@files[path].nil? 236 | end 237 | 238 | def deleted?(path) 239 | !File.exist?(path) 240 | end 241 | 242 | def open(path) 243 | if !deleted?(path) && cached?(path) 244 | return @files[path] 245 | end 246 | 247 | if deleted?(path) 248 | if @create_if_deleted 249 | @logger.debug("Required path was deleted, creating the file again", :path => path) 250 | @files.delete(path) 251 | else 252 | return @files[path] if cached?(path) 253 | end 254 | end 255 | 256 | @logger.info("Opening file", :path => path) 257 | 258 | dir = File.dirname(path) 259 | if !Dir.exist?(dir) 260 | @logger.info("Creating directory", :directory => dir) 261 | if @dir_mode != -1 262 | FileUtils.mkdir_p(dir, :mode => @dir_mode) 263 | else 264 | FileUtils.mkdir_p(dir) 265 | end 266 | end 267 | 268 | # work around a bug opening fifos (bug JRUBY-6280) 269 | stat = File.stat(path) rescue nil 270 | if stat && stat.ftype == "fifo" 271 | fd = java.io.FileWriter.new(java.io.File.new(path)) 272 | else 273 | if @file_mode != -1 274 | fd = File.new(path, "a+", @file_mode) 275 | else 276 | fd = File.new(path, "a+") 277 | end 278 | end 279 | if gzip 280 | fd = Zlib::GzipWriter.new(fd) 281 | end 282 | @files[path] = IOWriter.new(fd) 283 | end 284 | 285 | ## 286 | # Bare-bones utility for running a block of code at an interval. 287 | # 288 | class Interval 289 | ## 290 | # Initializes a new Interval with the given arguments and starts it before returning it. 291 | # 292 | # @param interval [Integer] (see: Interval#initialize) 293 | # @param procsy [#call] (see: Interval#initialize) 294 | # 295 | # @return [Interval] 296 | # 297 | def self.start(interval, procsy) 298 | self.new(interval, procsy).tap(&:start) 299 | end 300 | 301 | ## 302 | # @param interval [Integer]: time in seconds to wait between calling the given proc 303 | # @param procsy [#call]: proc or lambda to call periodically; must not raise exceptions. 304 | def initialize(interval, procsy) 305 | @interval = interval 306 | @procsy = procsy 307 | 308 | require 'thread' # Mutex, ConditionVariable, etc. 309 | @mutex = Mutex.new 310 | @sleeper = ConditionVariable.new 311 | end 312 | 313 | ## 314 | # Starts the interval, or returns if it has already been started. 315 | # 316 | # @return [void] 317 | def start 318 | @mutex.synchronize do 319 | return if @thread && @thread.alive? 320 | 321 | @thread = Thread.new { run } 322 | end 323 | end 324 | 325 | ## 326 | # Stop the interval. 327 | # Does not interrupt if execution is in-progress. 328 | def stop 329 | @mutex.synchronize do 330 | @stopped = true 331 | end 332 | 333 | @thread && @thread.join 334 | end 335 | 336 | ## 337 | # @return [Boolean] 338 | def alive? 339 | @thread && @thread.alive? 340 | end 341 | 342 | private 343 | 344 | def run 345 | @mutex.synchronize do 346 | loop do 347 | @sleeper.wait(@mutex, @interval) 348 | break if @stopped 349 | 350 | @procsy.call 351 | end 352 | end 353 | ensure 354 | @sleeper.broadcast 355 | end 356 | end 357 | end 358 | 359 | # wrapper class 360 | class IOWriter 361 | attr_accessor :active 362 | 363 | def initialize(io) 364 | @io = io 365 | end 366 | 367 | def write(*args) 368 | @io.write(*args) 369 | @active = true 370 | end 371 | 372 | def flush 373 | @io.flush 374 | if @io.class == Zlib::GzipWriter 375 | @io.to_io.flush 376 | end 377 | end 378 | 379 | def method_missing(method_name, *args, &block) 380 | if @io.respond_to?(method_name) 381 | 382 | @io.send(method_name, *args, &block) 383 | else 384 | super 385 | end 386 | end 387 | end 388 | -------------------------------------------------------------------------------- /logstash-output-file.gemspec: -------------------------------------------------------------------------------- 1 | Gem::Specification.new do |s| 2 | 3 | s.name = 'logstash-output-file' 4 | s.version = '4.3.0' 5 | s.licenses = ['Apache License (2.0)'] 6 | s.summary = "Writes events to files on disk" 7 | s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" 8 | s.authors = ["Elastic"] 9 | s.email = 'info@elastic.co' 10 | s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" 11 | s.require_paths = ["lib"] 12 | 13 | # Files 14 | s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"] 15 | 16 | # Tests 17 | s.test_files = s.files.grep(%r{^(test|spec|features)/}) 18 | 19 | # Special flag to let us know this is actually a logstash plugin 20 | s.metadata = { "logstash_plugin" => "true", "logstash_group" => "output" } 21 | 22 | # Gem dependencies 23 | s.add_runtime_dependency "logstash-core-plugin-api", ">= 2.0.0", "< 2.99" 24 | s.add_runtime_dependency 'logstash-codec-json_lines' 25 | s.add_runtime_dependency 'logstash-codec-line' 26 | 27 | s.add_development_dependency 'logstash-devutils' 28 | s.add_development_dependency 'insist' 29 | s.add_development_dependency 'flores' 30 | s.add_development_dependency 'logstash-input-generator' 31 | end 32 | -------------------------------------------------------------------------------- /spec/outputs/file_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | require "logstash/devutils/rspec/spec_helper" 3 | require "insist" 4 | require "logstash/outputs/file" 5 | require "logstash/codecs/line" 6 | require "logstash/codecs/json_lines" 7 | require "logstash/event" 8 | require "logstash/json" 9 | require "stud/temporary" 10 | require "tempfile" 11 | require "uri" 12 | require "fileutils" 13 | require "flores/random" 14 | 15 | def get_sequence_number(event) 16 | event.get('sequence') || event.get('event')['sequence'] 17 | end 18 | 19 | describe LogStash::Outputs::File do 20 | describe "ship lots of events to a file" do 21 | tmp_file = Tempfile.new('logstash-spec-output-file') 22 | event_count = 10000 + rand(500) 23 | 24 | config <<-CONFIG 25 | input { 26 | generator { 27 | message => "hello world" 28 | count => #{event_count} 29 | type => "generator" 30 | } 31 | } 32 | output { 33 | file { 34 | path => "#{tmp_file.path}" 35 | } 36 | } 37 | CONFIG 38 | 39 | agent do 40 | line_num = 0 41 | 42 | # Now check all events for order and correctness. 43 | events = tmp_file.map {|line| LogStash::Event.new(LogStash::Json.load(line))} 44 | sorted = events.sort_by {|e| get_sequence_number(e)} 45 | sorted.each do |event| 46 | insist {event.get("message")} == "hello world" 47 | insist {get_sequence_number(event)} == line_num 48 | line_num += 1 49 | end 50 | 51 | insist {line_num} == event_count 52 | end # agent 53 | end 54 | 55 | describe "ship lots of events to a file gzipped" do 56 | Stud::Temporary.file('logstash-spec-output-file') do |tmp_file| 57 | event_count = 100000 + rand(500) 58 | 59 | config <<-CONFIG 60 | input { 61 | generator { 62 | message => "hello world" 63 | count => #{event_count} 64 | type => "generator" 65 | } 66 | } 67 | output { 68 | file { 69 | path => "#{tmp_file.path}" 70 | gzip => true 71 | } 72 | } 73 | CONFIG 74 | 75 | agent do 76 | line_num = 0 77 | # Now check all events for order and correctness. 78 | events = Zlib::GzipReader.open(tmp_file.path).map {|line| LogStash::Event.new(LogStash::Json.load(line)) } 79 | sorted = events.sort_by {|e| get_sequence_number(e)} 80 | sorted.each do |event| 81 | insist {event.get("message")} == "hello world" 82 | insist {get_sequence_number(event)} == line_num 83 | line_num += 1 84 | end 85 | insist {line_num} == event_count 86 | end # agent 87 | end 88 | end 89 | 90 | describe "#register" do 91 | let(:path) { '/%{name}' } 92 | let(:output) { LogStash::Outputs::File.new({ "path" => path }) } 93 | 94 | it 'doesnt allow the path to start with a dynamic string' do 95 | expect { output.register }.to raise_error(LogStash::ConfigurationError) 96 | output.close 97 | end 98 | 99 | context 'doesnt allow the root directory to have some dynamic part' do 100 | ['/a%{name}/', 101 | '/a %{name}/', 102 | '/a- %{name}/', 103 | '/a- %{name}'].each do |test_path| 104 | it "with path: #{test_path}" do 105 | path = test_path 106 | expect { output.register }.to raise_error(LogStash::ConfigurationError) 107 | output.close 108 | end 109 | end 110 | end 111 | 112 | it 'allow to have dynamic part after the file root' do 113 | path = '/tmp/%{name}' 114 | output = LogStash::Outputs::File.new({ "path" => path }) 115 | expect { output.register }.not_to raise_error 116 | end 117 | end 118 | 119 | describe "receiving events" do 120 | 121 | context "when write_behavior => 'overwrite'" do 122 | let(:tmp) { Stud::Temporary.pathname } 123 | let(:config) { 124 | { 125 | "write_behavior" => "overwrite", 126 | "path" => tmp, 127 | "codec" => LogStash::Codecs::JSONLines.new, 128 | "flush_interval" => 0 129 | } 130 | } 131 | let(:output) { LogStash::Outputs::File.new(config) } 132 | 133 | let(:count) { Flores::Random.integer(1..10) } 134 | let(:events) do 135 | Flores::Random.iterations(1..10).collect do |i| 136 | LogStash::Event.new("value" => i) 137 | end 138 | end 139 | 140 | before do 141 | output.register 142 | end 143 | 144 | after do 145 | File.unlink(tmp) if File.exist?(tmp) 146 | end 147 | 148 | it "should write only the last event of a batch" do 149 | output.multi_receive(events) 150 | result = LogStash::Json.load(File.read(tmp)) 151 | expect(result["value"]).to be == events.last.get("value") 152 | end 153 | 154 | context "the file" do 155 | it "should only contain the last event received" do 156 | events.each do |event| 157 | output.multi_receive([event]) 158 | result = LogStash::Json.load(File.read(tmp)) 159 | expect(result["value"]).to be == event.get("value") 160 | end 161 | end 162 | end 163 | end 164 | 165 | context "when the output file is deleted" do 166 | 167 | let(:temp_file) { Tempfile.new('logstash-spec-output-file_deleted') } 168 | 169 | let(:config) do 170 | { "path" => temp_file.path, "flush_interval" => 0 } 171 | end 172 | 173 | it "should recreate the required file if deleted" do 174 | output = LogStash::Outputs::File.new(config) 175 | output.register 176 | 177 | 10.times do |i| 178 | event = LogStash::Event.new("event_id" => i) 179 | output.multi_receive([event]) 180 | end 181 | FileUtils.rm(temp_file) 182 | 10.times do |i| 183 | event = LogStash::Event.new("event_id" => i+10) 184 | output.multi_receive([event]) 185 | end 186 | 187 | expect(FileTest.size(temp_file.path)).to be > 0 188 | end 189 | 190 | context "when appending to the error log" do 191 | 192 | let(:config) do 193 | { "path" => temp_file.path, "flush_interval" => 0, "create_if_deleted" => false } 194 | end 195 | 196 | it "should append the events to the filename_failure location" do 197 | output = LogStash::Outputs::File.new(config) 198 | output.register 199 | 200 | 10.times do |i| 201 | event = LogStash::Event.new("event_id" => i) 202 | output.multi_receive([event]) 203 | end 204 | FileUtils.rm(temp_file) 205 | 10.times do |i| 206 | event = LogStash::Event.new("event_id" => i+10) 207 | output.multi_receive([event]) 208 | end 209 | expect(FileTest.exist?(temp_file.path)).to be_falsey 210 | expect(FileTest.size(output.failure_path)).to be > 0 211 | end 212 | 213 | end 214 | 215 | end 216 | 217 | context "when using an interpolated path" do 218 | context "when trying to write outside the files root directory" do 219 | let(:bad_event) do 220 | event = LogStash::Event.new 221 | event.set('error', '../uncool/directory') 222 | event 223 | end 224 | 225 | it 'writes the bad event in the specified error file' do 226 | Stud::Temporary.directory('filepath_error') do |path| 227 | config = { 228 | "path" => "#{path}/%{error}", 229 | "filename_failure" => "_error" 230 | } 231 | 232 | # Trying to write outside the file root 233 | outside_path = "#{'../' * path.split(File::SEPARATOR).size}notcool" 234 | bad_event.set("error", outside_path) 235 | 236 | 237 | output = LogStash::Outputs::File.new(config) 238 | output.register 239 | output.multi_receive([bad_event]) 240 | 241 | error_file = File.join(path, config["filename_failure"]) 242 | 243 | expect(File.exist?(error_file)).to eq(true) 244 | output.close 245 | end 246 | end 247 | 248 | it 'doesnt decode relatives paths urlencoded' do 249 | Stud::Temporary.directory('filepath_error') do |path| 250 | encoded_once = "%2E%2E%2ftest" # ../test 251 | encoded_twice = "%252E%252E%252F%252E%252E%252Ftest" # ../../test 252 | 253 | output = LogStash::Outputs::File.new({ "path" => "/#{path}/%{error}"}) 254 | output.register 255 | 256 | bad_event.set('error', encoded_once) 257 | output.multi_receive([bad_event]) 258 | 259 | bad_event.set('error', encoded_twice) 260 | output.multi_receive([bad_event]) 261 | 262 | expect(Dir.glob(File.join(path, "*")).size).to eq(2) 263 | output.close 264 | end 265 | end 266 | 267 | it 'doesnt write outside the file if the path is double escaped' do 268 | Stud::Temporary.directory('filepath_error') do |path| 269 | output = LogStash::Outputs::File.new({ "path" => "/#{path}/%{error}"}) 270 | output.register 271 | 272 | bad_event.set('error', '../..//test') 273 | output.multi_receive([bad_event]) 274 | 275 | expect(Dir.glob(File.join(path, "*")).size).to eq(1) 276 | output.close 277 | end 278 | end 279 | end 280 | 281 | context 'when trying to write inside the file root directory' do 282 | it 'write the event to the generated filename' do 283 | good_event = LogStash::Event.new 284 | good_event.set('error', '42.txt') 285 | 286 | Stud::Temporary.directory do |path| 287 | config = { "path" => "#{path}/%{error}" } 288 | output = LogStash::Outputs::File.new(config) 289 | output.register 290 | output.multi_receive([good_event]) 291 | 292 | good_file = File.join(path, good_event.get('error')) 293 | expect(File.exist?(good_file)).to eq(true) 294 | output.close 295 | end 296 | end 297 | 298 | it 'write the events to a file when some part of a folder or file is dynamic' do 299 | t = Time.now.utc 300 | good_event = LogStash::Event.new("@timestamp" => t) 301 | 302 | Stud::Temporary.directory do |path| 303 | dynamic_path = "#{path}/failed_syslog-%{+YYYY-MM-dd}" 304 | expected_path = "#{path}/failed_syslog-#{t.strftime("%Y-%m-%d")}" 305 | 306 | config = { "path" => dynamic_path } 307 | output = LogStash::Outputs::File.new(config) 308 | output.register 309 | output.multi_receive([good_event]) 310 | 311 | expect(File.exist?(expected_path)).to eq(true) 312 | output.close 313 | end 314 | end 315 | 316 | it 'write the events to the generated path containing multiples fieldref' do 317 | t = Time.now.utc 318 | good_event = LogStash::Event.new("error" => 42, 319 | "@timestamp" => t, 320 | "level" => "critical", 321 | "weird_path" => '/inside/../deep/nested') 322 | 323 | Stud::Temporary.directory do |path| 324 | dynamic_path = "#{path}/%{error}/%{level}/%{weird_path}/failed_syslog-%{+YYYY-MM-dd}" 325 | expected_path = "#{path}/42/critical/deep/nested/failed_syslog-#{t.strftime("%Y-%m-%d")}" 326 | 327 | config = { "path" => dynamic_path } 328 | 329 | output = LogStash::Outputs::File.new(config) 330 | output.register 331 | output.multi_receive([good_event]) 332 | 333 | expect(File.exist?(expected_path)).to eq(true) 334 | output.close 335 | end 336 | end 337 | 338 | it 'write the event to the generated filename with multiple deep' do 339 | good_event = LogStash::Event.new 340 | good_event.set('error', '/inside/errors/42.txt') 341 | 342 | Stud::Temporary.directory do |path| 343 | config = { "path" => "#{path}/%{error}" } 344 | output = LogStash::Outputs::File.new(config) 345 | output.register 346 | output.multi_receive([good_event]) 347 | 348 | good_file = File.join(path, good_event.get('error')) 349 | expect(File.exist?(good_file)).to eq(true) 350 | output.close 351 | end 352 | end 353 | end 354 | end 355 | context "output string format" do 356 | context "when using default configuration" do 357 | it 'write the event as a json line' do 358 | good_event = LogStash::Event.new 359 | good_event.set('message', 'hello world') 360 | 361 | Stud::Temporary.directory do |path| 362 | config = { "path" => "#{path}/output.txt" } 363 | output = LogStash::Outputs::File.new(config) 364 | output.register 365 | output.multi_receive([good_event]) 366 | good_file = File.join(path, 'output.txt') 367 | expect(File.exist?(good_file)).to eq(true) 368 | output.close #teardown first to allow reading the file 369 | File.open(good_file) {|f| 370 | event = LogStash::Event.new(LogStash::Json.load(f.readline)) 371 | expect(event.get("message")).to eq("hello world") 372 | } 373 | end 374 | end 375 | end 376 | context "when using line codec" do 377 | it 'writes event using specified format' do 378 | good_event = LogStash::Event.new 379 | good_event.set('message', "hello world") 380 | 381 | Stud::Temporary.directory do |path| 382 | config = { "path" => "#{path}/output.txt" } 383 | output = LogStash::Outputs::File.new(config.merge("codec" => LogStash::Codecs::Line.new({ "format" => "Custom format: %{message}"}))) 384 | output.register 385 | output.multi_receive([good_event]) 386 | good_file = File.join(path, 'output.txt') 387 | expect(File.exist?(good_file)).to eq(true) 388 | output.close #teardown first to allow reading the file 389 | File.open(good_file) {|f| 390 | line = f.readline 391 | expect(line).to eq("Custom format: hello world\n") 392 | } 393 | end 394 | end 395 | end 396 | context "when using file and dir modes" do 397 | it 'dirs and files are created with correct atypical permissions' do 398 | good_event = LogStash::Event.new 399 | good_event.set('message', "hello world") 400 | 401 | Stud::Temporary.directory do |path| 402 | config = { 403 | "path" => "#{path}/is/nested/output.txt", 404 | "dir_mode" => 0751, 405 | "file_mode" => 0610, 406 | } 407 | output = LogStash::Outputs::File.new(config) 408 | output.register 409 | output.multi_receive([good_event]) 410 | good_file = File.join(path, 'is/nested/output.txt') 411 | expect(File.exist?(good_file)).to eq(true) 412 | expect(File.stat(good_file).mode.to_s(8)[-3..-1]).to eq('610') 413 | first_good_dir = File.join(path, 'is') 414 | expect(File.stat(first_good_dir).mode.to_s(8)[-3..-1]).to eq('751') 415 | second_good_dir = File.join(path, 'is/nested') 416 | expect(File.stat(second_good_dir).mode.to_s(8)[-3..-1]).to eq('751') 417 | output.close #teardown first to allow reading the file 418 | File.open(good_file) {|f| 419 | event = LogStash::Event.new(LogStash::Json.load(f.readline)) 420 | expect(event.get("message")).to eq("hello world") 421 | } 422 | end 423 | end 424 | end 425 | end 426 | 427 | context "with non-zero flush interval" do 428 | let(:temporary_output_file) { Stud::Temporary.pathname } 429 | 430 | let(:event_count) { 10 } 431 | let(:flush_interval) { 5 } 432 | 433 | let(:events) do 434 | event_count.times.map do |idx| 435 | LogStash::Event.new("value" => idx) 436 | end 437 | end 438 | 439 | let(:config) { 440 | { 441 | "path" => temporary_output_file, 442 | "codec" => LogStash::Codecs::JSONLines.new, 443 | "flush_interval" => flush_interval 444 | } 445 | } 446 | let(:output) { LogStash::Outputs::File.new(config) } 447 | 448 | before(:each) { output.register } 449 | after(:each) do 450 | output.close 451 | File.exist?(temporary_output_file) && File.unlink(temporary_output_file) 452 | end 453 | 454 | it 'eventually flushes without receiving additional events' do 455 | output.multi_receive(events) 456 | 457 | # events should not all be flushed just yet... 458 | expect(File.read(temporary_output_file)).to satisfy("have less than #{event_count} lines") do |contents| 459 | contents && contents.lines.count < event_count 460 | end 461 | 462 | # wait for the flusher to run... 463 | sleep(flush_interval + 1) 464 | 465 | # events should all be flushed 466 | expect(File.read(temporary_output_file)).to satisfy("have exactly #{event_count} lines") do |contents| 467 | contents && contents.lines.count == event_count 468 | end 469 | end 470 | end 471 | end 472 | end 473 | --------------------------------------------------------------------------------