Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
wiibaa committed Apr 16, 2015
0 parents commit 9282948
Show file tree
Hide file tree
Showing 8 changed files with 502 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.gem
Gemfile.lock
.bundle
vendor
3 changes: 3 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
source 'https://rubygems.org'
gemspec
gem "logstash", :github => "elasticsearch/logstash", :branch => "1.5"
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright (c) 2012-2014 Elasticsearch <http://www.elasticsearch.org>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
95 changes: 95 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Logstash Plugin

This is a plugin for [Logstash](https://github.com/elasticsearch/logstash).

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.

## Documentation

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.elasticsearch.org/guide/en/logstash/current/).

- For formatting code or config example, you can use the asciidoc `[source,ruby]` directive
- For more asciidoc formatting tips, see the excellent reference here https://github.com/elasticsearch/docs#asciidoc-guide

## Need Help?

Need help? Try #logstash on freenode IRC or the [email protected] mailing list.

## Developing

### 1. Plugin Developement and Testing

#### Code
- To get started, you'll need JRuby with the Bundler gem installed.

- Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization.

- Install dependencies
```sh
bundle install
```

#### Test

```sh
bundle exec rspec
```

The Logstash code required to run the tests/specs is specified in the `Gemfile` by the line similar to:
```ruby
gem "logstash", :github => "elasticsearch/logstash", :branch => "1.5"
```
To test against another version or a local Logstash, edit the `Gemfile` to specify an alternative location, for example:
```ruby
gem "logstash", :github => "elasticsearch/logstash", :ref => "master"
```
```ruby
gem "logstash", :path => "/your/local/logstash"
```

Then update your dependencies and run your tests:

```sh
bundle install
bundle exec rspec
```

### 2. Running your unpublished Plugin in Logstash

#### 2.1 Run in a local Logstash clone

- Edit Logstash `tools/Gemfile` and add the local plugin path, for example:
```ruby
gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome"
```
- Update Logstash dependencies
```sh
rake vendor:gems
```
- Run Logstash with your plugin
```sh
bin/logstash -e 'filter {awesome {}}'
```
At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash.

#### 2.2 Run in an installed Logstash

- Build your plugin gem
```sh
gem build logstash-filter-awesome.gemspec
```
- Install the plugin from the Logstash home
```sh
bin/plugin install /your/local/plugin/logstash-filter-awesome.gem
```
- Start Logstash and proceed to test the plugin

## Contributing

All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin.

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.

It is more important to me that you are able to contribute.

For more information about contributing, see the [CONTRIBUTING](https://github.com/elasticsearch/logstash/blob/master/CONTRIBUTING.md) file.
7 changes: 7 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@files=[]

task :default do
system("rake -T")
end

require "logstash/devutils/rake"
179 changes: 179 additions & 0 deletions lib/logstash/filters/date_formatter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "logstash/timestamp"

# The date_formatter filter is used for formatting date or timestamp from fields,
# storing formatted string in the field defined as `target`.
#
# This filter is especially useful for creating localized
# or time-zone specific date string.
#
# For example, to format @timestamp in French locale, use this configuration:
# [source,ruby]
# filter {
# date_formatter {
# source => "@timestamp"
# target => "locale_timestamp"
# pattern => "EEE, dd MMM yyyy"
# locale => "fr-FR"
# timezone => "Europe/Paris"
# }
# }
#
# Another example, to format @timestamp in Japanese, use this configuration:
# [source,ruby]
# filter {
# date_formatter {
# source => "@timestamp"
# target => "japan_date"
# pattern => "yyyy'年'MM'月'dd'日'"
# timezone => "Japan/Tokyo"
# }
# }
#
class LogStash::Filters::DateFormatter < LogStash::Filters::Base
if RUBY_ENGINE == "jruby"
JavaException = java.lang.Exception
end

config_name "date_formatter"

# Specify a time zone canonical ID to be used for date formatting.
# The valid IDs are listed on the http://joda-time.sourceforge.net/timezones.html[Joda.org available time zones page].
# If this is not specified the platform default will be used.
# Canonical ID is good as it takes care of daylight saving time for you
# For example, `America/Los_Angeles` or `Europe/Paris` are valid IDs.
#
# This configuration can be dynamic and include parts of the event using the %{field} syntax.
config :timezone, :validate => :string

# Specify a locale to be used for date formatting using either IETF-BCP47 or POSIX language tag.
# Simple examples are `en`,`en-US` for BCP47 or `en_US` for POSIX.
#
# The locale is mostly necessary to be set for formatting month names (pattern with `MMM`) and
# weekday names (pattern with `EEE`).
#
# If not specified, the platform default will be used.
#
# This configuration can be dynamic and include parts of the event using the %{field} syntax.
config :locale, :validate => :string

# The date formats allowed are anything allowed by Joda-Time (java time
# library). You can see the docs for this format here:
#
# http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html[joda.time.format.DateTimeFormat]
#
# This configuration can be dynamic and include parts of the event using the %{field} syntax.
config :pattern, :validate => :string, :required => true

# The name of the logstash event field containing the date/time value
# to be formatted.
# If this field is an array, only the first value will be used.
config :source, :validate => :string, :required => true

# Store the formatted string into the given target field.
# You cannot use `@timestamp` as a valid target!
config :target, :validate => :string, :required => true

# Append values to the `tags` field when date formatting fail
config :tag_on_failure, :validate => :array, :default => ["_dateformatfailure"]

public
def register
require "java"
if @target == "@timestamp"
raise LogStash::ConfigurationError, I18n.t("logstash.agent.configuration.invalid_plugin_register",
:plugin => "filter", :type => "date_formatter",
:error => "This filter cannot write its string result to the @timestamp field")
end

locale = nil
timezone = nil
if @locale && !@locale.index("%{").nil?
@per_event_locale = true
else
locale = @locale
end

if @timezone && !@timezone.index("%{").nil?
@per_event_timezone = true
else
timezone = @timezone
end

if !@pattern.index("%{").nil?
@per_event_pattern = true
else
begin
@base_formatter = localizedFormatter(createBaseFormatter(@pattern),locale,timezone)
rescue JavaException => e
raise LogStash::ConfigurationError, I18n.t("logstash.agent.configuration.invalid_plugin_register",
:plugin => "filter", :type => "date_formatter",
:error => "#{e.message} for pattern '#{@pattern}'")
end
end
end

def createBaseFormatter(pattern)
return org.joda.time.format.DateTimeFormat.forPattern(pattern)
end

def localizedFormatter(joda_formatter,locale,timezone)
if timezone
joda_formatter = joda_formatter.withZone(org.joda.time.DateTimeZone.forID(timezone))
end
if locale
if locale.include? '_'
@logger.warn("Date formatter filter uses BCP47 format for locale, replacing underscore with dash")
locale.gsub!('_','-')
end
joda_formatter = joda_formatter.withLocale(java.util.Locale.forLanguageTag(locale))
end
return joda_formatter
end
# def register

def getFormatter(event)
if @per_event_pattern || @per_event_locale || @per_event_timezone
return localizedFormatter(
@per_event_pattern ? createBaseFormatter(event.sprintf(@pattern)) : @base_formatter,
@per_event_locale ? event.sprintf(@locale) : @locale,
@per_event_timezone ? event.sprintf(@timezone) : @timezone)
else
#base formatter is already complete
return @base_formatter
end
end

public
def filter(event)
return unless filter?(event)
return unless event.include?(@source)
src = event[@source]
src = src.first if src.respond_to?(:each)
target = nil
begin
case src
when LogStash::Timestamp,Time
target = getFormatter(event).print((src.to_f * 1000.0).to_i)
else
@logger.warn("Unsupporter source field. It is neither a ruby Time or a Logstash::Timestamp")
end
rescue JavaException => e
@logger.warn("Failed formatting date from field", :field => @src,
:value => src, :exception => e.message)
# Tag this event. We can use this later to reparse+reindex logs if necessary.
@tag_on_failure.each do |tag|
event["tags"] ||= []
event["tags"] << tag unless event["tags"].include?(tag)
end
target = nil
end
if target
event[@target] = target
filter_matched(event)
end
return event
end # def filter
end # class LogStash::Filters::DateFormatter
26 changes: 26 additions & 0 deletions logstash-filter-date_formatter.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Gem::Specification.new do |s|

s.name = 'logstash-filter-date_formatter'
s.version = '0.0.1'
s.licenses = ['Apache License (2.0)']
s.summary = "The date_formatter filter is used for formatting date or time from fields containing a time object like @timestamp, and then storing that formatted string in the field defined as target."
s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program"
s.authors = ["Elasticsearch"]
s.email = '[email protected]'
s.homepage = "http://www.elasticsearch.org/guide/en/logstash/current/index.html"
s.require_paths = ["lib"]

# Files
s.files = `git ls-files`.split($\)+::Dir.glob('vendor/*')

# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})

# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "filter" }

# Gem dependencies
s.add_runtime_dependency 'logstash', '>= 1.4.0', '< 2.0.0'
s.add_development_dependency 'logstash-devutils'
end

Loading

0 comments on commit 9282948

Please sign in to comment.