Recipe: Apache Logs + rsyslog (parsing) + Elasticsearch

Original post: Recipe: Apache Logs + rsyslog (parsing) + Elasticsearch by @Sematext

This recipe is about tailing Apache HTTPD logs with rsyslog, parsing them into structured JSON documents, and forwarding them to Elasticsearch (or a log analytics SaaS, like Logsene, which exposes the Elasticsearch API). Having them indexed in a structured way will allow you to do better analytics with tools like Kibana:


We’ll also cover pushing logs coming from the syslog socket and kernel, and how to buffer all of them properly. So this is quite a complete recipe for your centralized logging needs.

Getting the ingredients

Even though most distros already have rsyslog installed, it’s highly recommended to get the latest stable from the rsyslog repositories. The packages you’ll need are:

With the ingredients in place, let’s start cooking a configuration. The configuration needs to do the following:

  • load the required modules
  • configure inputs: tailing Apache logs and system logs
  • configure the main queue to buffer your messages. This is also the place to define the number of worker threads and batch sizes (which will also be Elasticsearch bulk sizes)
  • parse common Apache logs into JSON
  • define a template where you’d specify how JSON messages would look like. You’d use this template to send logs to Logsene/Elasticsearch via the Elasticsearch output

Loading modules

Here, we’ll need imfile to tail files, mmnormalize to parse them, and omelasticsearch to send them. If you want to tail the system logs, you’d also need to include imuxsock and imklog (for kernel logs).

# system logs
# file
# parser
# sender

Configure inputs

For system logs, you typically don’t need any special configuration (unless you want to listen to a non-default Unix Socket). For Apache logs, you’d point to the file(s) you want to monitor. You can use wildcards for file names as well. You also need to specify a syslog tag for each input. You can use this tag later for filtering.


NOTE: By default, rsyslog will not poll for file changes every N seconds. Instead, it will rely on the kernel (via inotify) to poke it when files get changed. This makes the process quite realtime and scales well, especially if you have many files changing rarely. Inotify is also less prone to bugs when it comes to file rotation and other events that would otherwise happen between two “polls”. You can still use the legacy mode=”polling” by specifying it in imfile’s module parameters.

Queue and workers

By default, all incoming messages go into a main queue. You can also separate flows (e.g. files and system logs) by using different rulesets but let’s keep it simple for now.

For tailing files, this kind of queue would work well:


This would be a small in-memory queue of 10K messages, which works well if Elasticsearch goes down, because the data is still in the file and rsyslog can stop tailing when the queue becomes full, and then resume tailing. 4 worker threads will pick batches of up to 1000 messages from the queue, parse them (see below) and send the resulting JSONs to Elasticsearch.

If you need a larger queue (e.g. if you have lots of system logs and want to make sure they’re not lost), I would recommend using a disk-assisted memory queue, that will spill to disk whenever it uses too much memory:

  queue.highWatermark="500000"    # max no. of events to hold in memory
  queue.lowWatermark="200000"     # use memory queue again, when it's back to this level
  queue.spoolDirectory="/var/run/rsyslog/queues"  # where to write on disk
  queue.maxDiskSpace="5g"        # it will stop at this much disk space
  queue.size="5000000"           # or this many messages
  queue.saveOnShutdown="on"      # save memory queue contents to disk when rsyslog is exiting

Parsing with mmnormalize

The message normalization module uses liblognorm to do the parsing. So in the configuration you’d simply point rsyslog to the liblognorm rulebase:


where apache.rb will contain rules for parsing apache logs, that can look like this:


rule=:%clientip:word% %ident:word% %auth:word% [%timestamp:char-to:]%] "%verb:word% %request:word% HTTP/%httpversion:float%" %response:number% %bytes:number% "%referrer:char-to:"%" "%agent:char-to:"%"%blob:rest%

Where version=2 indicates that rsyslog should use liblognorm’s v2 engine (which is was introduced in rsyslog 8.13) and then you have the actual rule for parsing logs. You can find more details about configuring those rules in the liblognorm documentation.

Besides parsing Apache logs, creating new rules typically requires a lot of trial and error. To check your rules without messing with rsyslog, you can use the lognormalizer binary like:

head -1 /path/to/log.file | /usr/lib/lognorm/lognormalizer -r /path/to/rulebase.rb -e json

NOTE: If you’re used to Logstash’s grok, this kind of parsing rules will look very familiar. However, things are quite different under the hood. Grok is a nice abstraction over regular expressions, while liblognorm builds parse trees out of specialized parsers. This makes liblognorm much faster, especially as you add more rules. In fact, it scales so well, that for all practical purposes, performance depends on the length of the log lines and not on the number of rules. This post explains the theory behind this assuption, and this is actually proven by various tests. The downside is that you’ll lose some of the flexibility offered by regular expressions. You can still use regular expressions with liblognorm (you’d need to set allow_regex to on when loading mmnormalize) but then you’d lose a lot of the benefits that come with the parse tree approach.

Template for parsed logs

Since we want to push logs to Elasticsearch as JSON, we’d need to use templates to format them. For Apache logs, by the time parsing ended, you already have all the relevant fields in the $!all-json variable, that you’ll use as a template:

template(name="all-json" type="list"){

Template for time-based indices

For the logging use-case, you’d probably want to use time-based indices (e.g. if you keep your logs for 7 days, you can have one index per day). Such a design will give your cluster a lot more capacity due to the way Elasticsearch merges data in the background (you can learn the details in our presentations at GeeCON and Berlin Buzzwords).

To make rsyslog use daily or other time-based indices, you need to define a template that builds an index name off the timestamp of each log. This is one that names them logstash-YYYY.MM.DD, like Logstash does by default:

  type="list") {
    property(name="timereported" dateFormat="rfc3339" position.from="1""4")
    property(name="timereported" dateFormat="rfc3339" position.from="6""7")
    property(name="timereported" dateFormat="rfc3339" position.from="9""10")

And then you’d use this template in the Elasticsearch output:


Putting both Apache and system logs together

If you use the same rsyslog to parse system logs, mmnormalize won’t parse them (because they don’t match Apache’s common log format). In this case, you’ll need to pick the rsyslog properties you want and build an additional JSON template:

  type="list") {
      constant(value="\"timestamp\":\"")     property(name="timereported" dateFormat="rfc3339")
      constant(value="\",\"host\":\"")        property(name="hostname")
      constant(value="\",\"severity\":\"")    property(name="syslogseverity-text")
      constant(value="\",\"facility\":\"")    property(name="syslogfacility-text")
      constant(value="\",\"tag\":\"")   property(name="syslogtag" format="json")
      constant(value="\",\"message\":\"")    property(name="msg" format="json")

Then you can make rsyslog decide: if a log was parsed successfully, use the all-json template. If not, use the plain-syslog one:

if $parsesuccess == "OK" then {
} else {

And that’s it! Now you can restart rsyslog and get both your system and Apache logs parsed, buffered and indexed into Elasticsearch. If you’re a Logsene user, the recipe is a bit simpler: you’d follow the same steps, except that you’ll skip the logstash-index template (Logsene does that for you) and your Elasticsearch actions will look like this:

  template="all-json or plain-syslog"

Changelog for 7.3.4 (v7-devel)

Version 7.3.4 [devel] 2012-11-23

  • further (and rather drastically) improved disk queue performance
    we now save one third of the IO calls
  • imklog: added ParseKernelTimestamp parameter (import from 5.10.2)
    Thanks to Marius Tomaschewski for the patch.
  • imklog: added KeepKernelTimestamp parameter (import from 5.10.2)
    Thanks to Marius Tomaschewski for the patch.
  • bugfix: improper handling of backslash in string-type template()s
  • bugfix: leading quote (“) in string-type template() lead to thight loop
    on startup
  • bugfix: no error msg on invalid field option in legacy/string template
  • bugfix: imklog mistakenly took kernel timestamp subseconds as nanoseconds
    … actually, they are microseconds. So the fractional part of the
    timestamp was not properly formatted. (import from 5.10.2)
    Thanks to Marius Tomaschewski for the bug report and the patch idea.

Changelog for 6.2.1 (v6-stable)

Version 6.2.1 [v6-stable], 2012-05-10

  • change plugin config interface to be compatible with pre-v6.2 system
    The functionality was already removed (because it is superseeded by the
    v6.3+ config language), but code was still present. I have now removed
    those parts that affect interface. Full removal will happen in v6.3, in
    order to limit potential regressions. However, it was considered useful
    enough to do the interface change in v6-stable; this also eases merging
  • re-licensed larger parts of the codebase under the Apache license 2.0
  • bugfix: omprog made rsyslog abort on startup if not binary to
    execute was configured
  • bugfix: imklog invalidly computed facility and severity
  • bugfix: stopped DA queue was never processed after a restart due to a
    regression from statistics module
  • bugfix: memory leak in array passing output module mode
  • bugfix: ommysql did not properly init/exit the mysql runtime library
    this could lead to segfaults. Triggering condition: multiple action
    instances using ommysql. Thanks to Tomas Heinrich for reporting this
    problem and providing an initial patch (which my solution is based on,
    I need to add more code to clean the mess up).
  • bugfix: rsyslog did not terminate when delayable inputs were blocked
    due to unvailable sources. Fixes:
    Thanks to Marcin M for bringing up this problem and Andre Lorbach
    for helping to reproduce and fix it.
  • bugfix/tcpflood: sending small test files did not work correctly

rsyslog 5.8.8 (v5-stable) released

This is a bug-fixing release. It fixes the wrong computed facility and severity in imklog and a problem with rsyslog aborting on startup if no binary to execute was configured for omprog.



As always, feedback is appreciated.

Best regards,

Florian Riedl

Changelog for 6.3.7 (v6-devel)

Version 6.3.7  [DEVEL] 2012-02-02

  • imported refactored v5.9.6 imklog linux driver, now combined with BSD driver
  • removed imtemplate/omtemplate template modules, as this was waste of time
    The actual input/output modules are better copy templates. Instead, the now-removed modules cost time for maintenance AND often caused confusion on what their role was.
  • added  new stats objects
  • improved support for new v6 config system. The build-in output modules now all support the new config language
  • bugfix: facility local<x> was not correctly interpreted in legacy filters
    Was only accepted if it was the first PRI in a multi-filter PRI. Thanks to forum user Mark for bringing this to our attention.
  • bugfix: potential abort after reading invalid X.509 certificate
    Thanks to Tomas Heinrich for the patch
  • bufgix: legacy parsing of some filters did not work correctly
  • bugfix: rsyslog aborted during startup if there is an error in loading an action and legacy configuration mode is used
  • bugfix: bsd klog driver did no longer compile
  • relicensed larger parts of the code under Apache (ASL) 2.0
Scroll to top