Skip to content

Drain Parser [Code]

Drain uses the DetectMatePerformance implementation, which also provides a batch API for processing large collections of logs. DetectMatePerformance

In/out

Input and output schemas in the pipeline

Schema Description
Input LogSchema Unstructured log
Output ParserSchema Structured log
Learns from training data Auto-configuration Needs events Federation
✅ ✅ ❌ ✅

Not yet stable

This parser is not yet in a stable release and may behave differently across platforms or hardware.

Description

The original Drain algorithm uses a fixed-depth tree to narrow the search for a matching log group. The first level below the root branches on the number of tokens in the message. The next levels use leading tokens in order. At the leaf, Drain scores each candidate template by the fraction of tokens that match at the same positions. A similarity threshold determines whether Drain updates the best-matching group or starts a new one. Drain paper, Section III

Drain groups messages by token count and leading tokens. The Hello world group yields the template Hello world <*> you.

In DetectMate, Drain generates templates from buffered logs when training ends. It groups cleaned messages by token count, capped at max_childs, and by their first depth tokens. Within each group, messages join a cluster when their similarity to its first message exceeds sim_thres. The score is the fraction of matching bytes at the same positions over the length of the shorter message.

Each template keeps the tokens that agree at the same position and uses <*> where they vary. For example, Hello world and you and Hello world or you produce Hello world <*> you. After training, a tree matcher uses the learned templates to parse incoming messages. A match for Hello world to you returns that template and puts to in variables.

Federation

Drain inherits the concatenation strategy from ParserGenerator. Aggregation collects the templates learned by each participating parser, removes duplicates, and sorts the result. Each participant builds its matcher from that shared list, giving the same template the same eventID across the federation. Distributed parsing paper, Section 4.3.1

Training after federation

When retraining finishes, the parser replaces the federated template set with templates generated from its local training buffer. Templates learned only by other participants are lost.

Examples

Templates are kept when training resumes (default):

Example
import yaml
from detectmatelibrary.parsers.drain import DrainParser
from detectmatelibrary import schemas

with open("docs/examples/parsers/drain_parser.yaml") as f:
    config = yaml.safe_load(f)


def log(text: str) -> schemas.LogSchema:
    return schemas.LogSchema({"log": text})


parser = DrainParser(name="DrainParser", config=config)

# the first 2 logs train the parser (data_use_training: 2)
print(parser.process(log("hello there, general kenobi!"))["template"])  # templates not yet generated
print(parser.process(log("hello there, captain kenobi!"))["template"])  # templates not yet generated
print(parser.process(log("hello there, sergeant kenobi!"))["template"])  # hello there <*> kenobi

# train on one more log, then go back to parsing
parser.update_state("keep_training")
parser.process(log("bella ciao bella ciao"))
parser.update_state("stop_training")

print(parser.process(log("hello there, sergeant kenobi!"))["template"])  # hello there <*> kenobi

Templates are reset after each training round (reset_in_post_train: true):

Reset example
# Clear the training buffer after each round.
config["parsers"]["DrainParser"]["params"]["reset_in_post_train"] = True
parser = DrainParser(name="DrainParser", config=config)

parser.process(log("hello there, general kenobi!"))
parser.process(log("hello there, captain kenobi!"))
print(parser.process(log("hello there, sergeant kenobi!"))["template"])  # hello there <*> kenobi

parser.update_state("keep_training")
parser.process(log("bella ciao bella ciao"))
parser.update_state("stop_training")

# template not found: the second round only learned "bella ciao bella ciao"
print(parser.process(log("hello there, sergeant kenobi!"))["template"])

Configuration file

The configuration used by the examples above. It sets only what this use case needs; every other parameter keeps its default (see Configuration arguments).

Configuration
parsers:
  DrainParser:
    method_type: drain_parser
    params:
      data_use_training: 2    # the first 2 logs are used to mine templates

The same file works unchanged in both places a parser runs:

  • Library: load it with yaml.safe_load and pass the dict as config=, as in the example. The key under parsers: must match the parser's name.
  • DetectMateService: use it as the service's parser configuration.

Configuration arguments

Arguments are grouped by YAML block. Scope identifies fields specific to Drain and fields inherited from the parser generator base. When Drain overrides an inherited default, the base default appears in parentheses. Shared parser generator parameters

Top level
Field Type Default Scope Description
method_type string drain_parser shared Indicates what type of method it is.
auto_config boolean False shared Runs the configuration step before the training process.
params
Field Type Default Scope Description
depth integer 2 specific Number of leading tokens used to group training logs.
max_childs integer 10 specific Upper limit on the token count used for grouping.
sim_thres number 0.2 specific Similarity score a message must exceed to join a cluster.
start_id integer 10 shared Number used to start the unique ID generator.
data_use_training integer, null None shared Number of logs used for training. None skips training.
data_use_configure integer, null None shared Number of logs used for the configuration step. None skips it.
use_config_data_as_training boolean True shared Reuse configuration records as training data.
train_buffer_max_records integer 100000 shared Configure records kept in memory for training (use_config_data_as_training) before the buffer spills to Parquet files on disk, in parts of this many records.
train_buffer_dir string, null None shared Local directory for the spilled training buffer. None uses the system temp directory (TMPDIR). Each spill goes to a private detectmate-train-* directory, removed after training reads it; a killed process leaves it behind.
connector_name string, null None shared Add a connector to the output schema.
connector_url string, null None shared Set up the URL of the connector for the output schema.
log_format string, null None shared Pattern with named fields such as <Time> and <Content> for splitting a raw log.
time_format string, null None shared Format used to parse the timestamp field.
log_source string, null None shared Process only inputs of the same log source.
reset_in_post_train boolean False shared Clear buffered training logs after generating templates.
Finetune array [['depth', [1, 2, 3, 4]], ['max_childs', [10, 40]], ['sim_thres', [0.2, 0.4, 0.6, 0.8]]] (shared: []) shared Candidate [parameter, values] pairs for automatic configuration.