pyclef API

Submodules

pyclef.collection module

CLEF Event Collection Module

This module provides a container class for managing collections of CLEF log events. The ClefEventCollection class offers convenient methods for filtering, slicing, and iterating over log events, making it easy to work with multiple events as a cohesive unit.

The collection implements common Python protocols (iterator, sequence, length) allowing it to be used naturally with Python’s built-in functions and idioms.

Classes:
ClefEventCollection: A container for multiple ClefEvent instances with

filtering, slicing, and iteration capabilities.

Example

Basic collection usage:

from pyclef import ClefParser

parser = ClefParser('log.clef')
events = parser.parse()  # Returns ClefEventCollection

# Check if collection has events
if events:
    print(f"Found {len(events)} events")

# Iterate over events
for event in events:
    print(event.message)

Filtering events:

# Filter using a predicate function
errors = events.filter(lambda e: e.level == 'Error')

# Filter with complex conditions
recent_errors = events.filter(
    lambda e: e.level == 'Error' and
             e.timestamp > '2026-01-24T00:00:00Z'
)
class pyclef.collection.ClefEventCollection[source]

Bases: object

A container for managing multiple CLEF log events.

This class provides a high-level interface for working with collections of ClefEvent instances. It supports filtering, slicing, iteration, and other operations that make it easy to process and analyze log events in bulk.

add_event(event: ClefEvent) None[source]

Add an event to the collection.

Parameters:

event – The ClefEvent instance to add to the collection.

Example

>>> collection = ClefEventCollection()
>>> event = ClefEvent(reified={'@l': 'Info'}, user={})
>>> collection.add_event(event)
>>> len(collection)
1
filter(predicate: Callable[[ClefEvent], bool]) ClefEventCollection[source]

Filter events using a predicate function.

Parameters:

predicate – A callable that takes a ClefEvent and returns a boolean.

Returns:

A new ClefEventCollection containing the filtered events.

Example

>>> errors = collection.filter(lambda e: e.level == 'Error')
>>> len(errors) <= len(collection)
True
get_all_events() List[ClefEvent][source]

Get all events as a Python list.

Returns:

A new list containing all events in order.

pyclef.event module

CLEF Event Representation Module

This module provides the core data structure for representing individual CLEF (Compact Log Event Format) log events. Each event contains both reified (standard) fields and user-defined custom fields.

The ClefEvent class serves as the primary interface for accessing log event data, providing convenient property accessors for standard CLEF fields and direct access to custom application-specific fields.

Classes:
ClefEvent: Dataclass representing a single CLEF log event with both standard

and custom fields.

Standard CLEF Fields:
  • @t (timestamp): ISO 8601 timestamp of the event

  • @m (message): Rendered log message

  • @mt (message_template): Structured message template

  • @l (level): Log level (e.g., Information, Warning, Error)

  • @x (exception): Exception details and stack trace

  • @i (event_id): Unique event identifier

  • @r (renderings): Alternative renderings of message parameters

Example

Basic event access:

from pyclef import ClefParser

parser = ClefParser('log.clef')
events = parser.parse()

for event in events:
    print(f"{event.timestamp} [{event.level}] {event.message}")

    # Access custom fields
    if 'UserId' in event.user:
        print(f"User: {event.user['UserId']}")

Working with event data:

event = events[0]

# Standard fields via properties
print(event.timestamp)  # "2026-01-24T10:00:00.123Z"
print(event.level)      # "Information"
print(event.message)    # "User logged in successfully"

# Custom fields via user dictionary
print(event.user['Environment'])  # "Production"
print(event.user['RequestId'])    # "abc-123"

Converting events:

# To dictionary
event_dict = event.to_dict()
# {'reified': {...}, 'user': {...}}

# To JSON string
json_str = event.to_json()
# '{"reified": {...}, "user": {...}}'

Checking for exceptions:

for event in events:
    if event.level == 'Error' and event.exception:
        print(f"Exception occurred: {event.exception}")

Notes

  • All standard CLEF fields are accessed via properties returning Optional values

  • Custom/user fields are stored in the ‘user’ dictionary attribute

  • Reified fields contain standard CLEF metadata

  • Events are immutable once created (dataclass with frozen=False by default)

  • None is returned for missing standard fields

class pyclef.event.ClefEvent(reified: Dict[str, Any], user: Dict[str, Any])[source]

Bases: object

Represents a single CLEF (Compact Log Event Format) log event.

A CLEF event consists of two main components: 1. Reified fields: Standard CLEF fields like timestamp, level, message, etc. 2. User fields: Custom application-specific fields

This class provides property accessors for all standard CLEF fields and direct dictionary access for custom fields. It implements useful methods for serialization and representation.

reified

Dictionary containing standard CLEF fields (those starting with @). Keys use the CLEF format (e.g., ‘@t’, ‘@l’).

Type:

Dict[str, Any]

user

Dictionary containing custom application-defined fields. These are any fields that don’t start with @ in the original CLEF log entry.

Type:

Dict[str, Any]

Properties:
  • timestamp: ISO 8601 formatted event timestamp (@t field).

  • level: Log level string (@l field), e.g., ‘Information’, ‘Warning’, ‘Error’.

  • message: Rendered log message (@m field) with parameters substituted.

  • message_template: Structured message template (@mt field) before substitution.

  • exception: Exception information (@x field) including stack trace.

  • event_id: Event identifier (@i field), can be any type.

  • renderings: Alternative renderings (@r field) of message parameters.

Example

Creating an event (typically done by parser):

>>> from pyclef.event import ClefEvent
>>> event = ClefEvent(reified={'@t': '2026-01-24T10:00:00.123Z', '@l': 'Information', '@m': 'User logged in successfully'}, user={'UserId': '12345'})
>>> event.timestamp
'2026-01-24T10:00:00.123Z'
>>> event.level
'Information'
>>> event.message
'User logged in successfully'
>>> event.user['UserId']
'12345'
property event_id: Any | None
property exception: str | None
property level: str | None
property message: str | None
property message_template: str | None
reified: Dict[str, Any]
property renderings: Any | None
property timestamp: str | None
to_dict() Dict[str, Any][source]

Convert event to dictionary

to_json() str[source]

Convert event to JSON string

user: Dict[str, Any]

pyclef.exceptions module

CLEF Parsing Exceptions Module

This module defines custom exceptions for handling errors that occur during CLEF (Compact Log Event Format) file parsing and processing operations.

All exceptions inherit from the base ClefParseError class, allowing for hierarchical exception handling. This enables callers to catch specific errors or all CLEF-related errors using the base class.

Exception Hierarchy:
    ClefParseError (base)
    ├── ClefFileNotFoundError
    ├── ClefJSONDecodeError
    └── ClefIOError
Classes:

ClefParseError: Base exception for all CLEF parsing errors. ClefFileNotFoundError: Raised when a CLEF file cannot be found. ClefJSONDecodeError: Raised when JSON decoding fails on a specific line. ClefIOError: Raised when I/O operations fail during file reading.

Example

Basic exception handling:

from pyclef import ClefParser
from pyclef.exceptions import (
    ClefFileNotFoundError,
    ClefJSONDecodeError,
    ClefParseError
)

try:
    parser = ClefParser('logs/app.clef')
    events = parser.parse()
except ClefFileNotFoundError as e:
    print(f"File not found: {e.file_path}")
except ClefJSONDecodeError as e:
    print(f"Invalid JSON at line {e.line_num}: {e.original_error}")
except ClefParseError as e:
    print(f"General parsing error: {e}")

Catching all CLEF errors:

try:
    parser = ClefParser('logs/app.clef')
    events = parser.parse()
except ClefParseError as e:
    # Catches all CLEF-related exceptions
    print(f"CLEF parsing failed: {e}")

Accessing exception properties:

try:
    parser = ClefParser('invalid.clef')
    events = parser.parse()
except ClefJSONDecodeError as e:
    print(f"Line number: {e.line_num}")
    print(f"Content: {e.line_content}")
    print(f"Original error: {e.original_error}")

Notes

  • All exceptions preserve the original error via the ‘original_error’ attribute

  • Exception messages are formatted to provide context for debugging

  • Line content in ClefJSONDecodeError is truncated to 100 characters for readability

exception pyclef.exceptions.ClefFileNotFoundError(file_path: str)[source]

Bases: ClefParseError

Raised when a CLEF file cannot be found at the specified path.

This exception is raised when attempting to open a CLEF file that does not exist or is not accessible at the given file path.

file_path

The path to the file that was not found.

Type:

str

Parameters:

file_path – The path to the missing CLEF file.

Example

>>> from pyclef import ClefParser
>>> from pyclef.exceptions import ClefFileNotFoundError
>>>
>>> try:
...     parser = ClefParser('nonexistent.clef')
...     events = parser.parse()
... except ClefFileNotFoundError as e:
...     print(f"Cannot find file: {e.file_path}")
Cannot find file: nonexistent.clef
exception pyclef.exceptions.ClefIOError(file_path: str, original_error: Exception)[source]

Bases: ClefParseError

Raised when an I/O error occurs while reading a CLEF file.

This exception is raised for various I/O-related errors such as permission denied, disk read errors, or other file system issues that prevent the CLEF file from being read successfully.

file_path

The path to the file that caused the I/O error.

Type:

str

original_error

The underlying IOError or OSError.

Type:

Exception

Parameters:
  • file_path – The path to the CLEF file being accessed.

  • original_error – The original I/O exception that was raised.

Example

>>> from pyclef import ClefParser
>>> from pyclef.exceptions import ClefIOError
>>>
>>> try:
...     parser = ClefParser('/protected/log.clef')
...     events = parser.parse()
... except ClefIOError as e:
...     print(f"Cannot read file: {e.file_path}")
...     print(f"Reason: {e.original_error}")
Cannot read file: /protected/log.clef
Reason: [Errno 13] Permission denied: '/protected/log.clef'

Notes

  • Common causes include permission issues, disk errors, or network failures

  • The original_error contains the specific system error details

  • File path is preserved for debugging and logging purposes

exception pyclef.exceptions.ClefJSONDecodeError(line_num: int, line_content: str, original_error: Exception)[source]

Bases: ClefParseError

Raised when a line in the CLEF file contains invalid JSON.

CLEF files use newline-delimited JSON (NDJSON) format where each line must be valid JSON. This exception is raised when a line fails to parse as valid JSON, typically due to syntax errors or malformed data.

line_num

The line number (1-indexed) where the error occurred.

Type:

int

line_content

The content of the line that failed to parse.

Type:

str

original_error

The underlying JSONDecodeError from the json module.

Type:

Exception

Parameters:
  • line_num – The line number where JSON decoding failed (1-indexed).

  • line_content – The actual content of the problematic line.

  • original_error – The original JSONDecodeError exception.

Example

>>> from pyclef import ClefParser
>>> from pyclef.exceptions import ClefJSONDecodeError
>>>
>>> try:
...     parser = ClefParser('malformed.clef')
...     events = parser.parse()
... except ClefJSONDecodeError as e:
...     print(f"JSON error at line {e.line_num}")
...     print(f"Content: {e.line_content[:50]}...")
...     print(f"Error: {e.original_error}")
JSON error at line 42
Content: {"@t":"2026-01-24T10:00:00Z","@m":"Missing clo...
Error: Expecting ',' delimiter: line 1 column 50 (char 49)

Notes

  • Line numbers start at 1 for user-friendly error messages

  • Line content is truncated to 100 characters in the error message

  • The full line content is available via the line_content attribute

  • The original JSONDecodeError provides detailed position information

exception pyclef.exceptions.ClefParseError[source]

Bases: Exception

Base exception for all CLEF parsing errors.

This is the parent class for all CLEF-related exceptions. Use this in exception handlers to catch any CLEF parsing error regardless of the specific type.

Example

>>> try:
...     parser = ClefParser('log.clef')
...     events = parser.parse()
... except ClefParseError as e:
...     print(f"Parsing failed: {e}")

pyclef.fields module

CLEF Field Definitions Module

This module defines the standard field names used in the CLEF (Compact Log Event Format) specification. These fields represent the core metadata and content of log events in the CLEF format.

CLEF uses @-prefixed field names for standard/reified fields to distinguish them from user-defined application fields. This module provides an enumeration of these standard fields for type-safe access throughout the library.

Classes:

ClefField: Enumeration of standard CLEF field names.

Standard Fields:
TIMESTAMP (@t):

ISO 8601 formatted timestamp indicating when the event occurred. Example: “2026-01-24T10:00:00.123Z”

MESSAGE (@m):

The rendered log message with all parameters substituted. Example: “User alice logged in from 192.168.1.1”

MESSAGE_TEMPLATE (@mt):

The structured message template before parameter substitution. Example: “User {UserId} logged in from {IpAddress}”

LEVEL (@l):

The log level/severity of the event. Examples: “Verbose”, “Debug”, “Information”, “Warning”, “Error”, “Fatal”

EXCEPTION (@x):

Exception information including type, message, and stack trace. Present when the log event is associated with an error/exception.

EVENT_ID (@i):

A unique identifier for this type of event, useful for categorization. Can be a string, integer, or other identifier type.

RENDERINGS (@r):

Alternative renderings of message template parameters. Provides different formatting or serialization options for parameters.

Example

Using field enums for type-safe access:

from pyclef.fields import ClefField

# Access field values
timestamp_field = ClefField.TIMESTAMP.value  # "@t"
level_field = ClefField.LEVEL.value          # "@l"

# Use in dictionary lookups
event_data = {
    ClefField.TIMESTAMP.value: "2026-01-24T10:00:00Z",
    ClefField.LEVEL.value: "Information",
    ClefField.MESSAGE.value: "Application started"
}

# Get timestamp from event
timestamp = event_data.get(ClefField.TIMESTAMP.value)

Checking if a field is a standard CLEF field:

from pyclef.fields import ClefField

# Get all standard field names
standard_fields = {field.value for field in ClefField}
# {'@t', '@m', '@mt', '@l', '@x', '@i', '@r'}

# Check if a field is standard
field_name = "@t"
is_standard = field_name in standard_fields  # True

field_name = "CustomField"
is_standard = field_name in standard_fields  # False

Iterating over all standard fields:

from pyclef.fields import ClefField

# List all standard fields
for field in ClefField:
    print(f"{field.name}: {field.value}")

# Output:
# TIMESTAMP: @t
# MESSAGE: @m
# MESSAGE_TEMPLATE: @mt
# LEVEL: @l
# EXCEPTION: @x
# EVENT_ID: @i
# RENDERINGS: @r

Notes

  • All CLEF standard fields use the @ prefix to avoid conflicts with user fields

  • ClefField inherits from both str and Enum for convenient string comparisons

  • The enum values are the actual CLEF field names as they appear in log files

  • User-defined fields (without @ prefix) are not part of this enumeration

  • Fields prefixed with @@ in raw CLEF are unescaped to @ in user fields

See also

class pyclef.fields.ClefField(*values)[source]

Bases: str, Enum

EVENT_ID = '@i'
EXCEPTION = '@x'
LEVEL = '@l'
MESSAGE = '@m'
MESSAGE_TEMPLATE = '@mt'
RENDERINGS = '@r'
TIMESTAMP = '@t'

pyclef.filter module

CLEF Event Filtering Module

This module provides a fluent builder interface for filtering CLEF log events based on various criteria including timestamps, log levels, message patterns, and custom fields.

Classes:
ClefEventFilterBuilder: Builder class for constructing complex event filters

using method chaining.

Example

Basic filtering by log level:

from pyclef import ClefParser

parser = ClefParser('log.clef')
events = parser.parse()

errors = parser.event_filter(events)            .level('Error')            .filter()

Advanced filtering with multiple criteria:

filtered = parser.event_filter(events)            .start_time('2026-01-24T00:00:00Z')            .end_time('2026-01-24T23:59:59Z')            .level('Warning')            .msg_regex(r'database.*timeout')            .user_fields({'Environment': 'Production'})            .filter()

Chaining multiple filters:

critical_errors = parser.event_filter(events)            .level('Error')            .exception_regex(r'NullPointerException')            .start_time('2026-01-24T10:00:00Z')            .filter()
Supported Filter Types:
  • Timestamp ranges (start_time, end_time)

  • Log levels (level)

  • Message patterns (msg_regex, msg_template_regex)

  • Exception patterns (exception_regex)

  • Rendering patterns (renderings_regex)

  • Custom user fields (user_fields)

  • Event IDs (eventid)

Notes

  • All filter methods return the builder instance for method chaining

  • Call filter() at the end to execute filtering and get results

  • Regex patterns use Python’s re module syntax

  • Invalid regex patterns raise ValueError

  • Timestamp filtering uses ISO 8601 format

class pyclef.filter.ClefEventFilterBuilder(events: ClefEventCollection | None)[source]

Bases: object

Builder for constructing and applying filters to CLEF event collections.

This class implements the builder pattern, allowing you to chain multiple filter criteria before executing the filter operation. All filter methods return self to enable fluent method chaining.

events

The collection of events to filter.

Type:

ClefEventCollection

Example

>>> from pyclef import ClefParser
>>> parser = ClefParser('log.clef')
>>> events = parser.parse()
>>>
>>> # Filter errors from the last hour
>>> recent_errors = parser.event_filter(events)        ...     .level('Error')        ...     .start_time('2026-01-24T10:00:00Z')        ...     .filter()
>>>
>>> # Filter by message pattern and custom field
>>> db_errors = parser.event_filter(events)        ...     .msg_regex(r'database.*failed')        ...     .user_fields({'Component': 'Database'})        ...     .filter()
end_time(value: str) ClefEventFilterBuilder[source]

Filter events that occurred on or before the specified timestamp.

Parameters:

value – ISO 8601 formatted timestamp string (e.g., ‘2026-01-24T23:59:59Z’).

Returns:

Self for method chaining.

Raises:

Example

>>> builder.end_time('2026-01-24T23:59:59Z')
eventid(value: Any) ClefEventFilterBuilder[source]

Filter events by event ID.

Parameters:

value – The event ID to filter by (can be string, int, or other types).

Returns:

Self for method chaining.

Example

>>> builder.eventid('evt_12345')
>>> builder.eventid(42)
exception_regex(value: str) ClefEventFilterBuilder[source]

Filter events by exception information using a regular expression.

Searches the exception stack trace or error message.

Parameters:

value – Regular expression pattern string.

Returns:

Self for method chaining.

Raises:

ValueError – If the regex pattern is invalid or empty.

Example

>>> builder.exception_regex(r'NullPointerException')
>>> builder.exception_regex(r'at com\.example\..*')
filter() ClefEventCollection[source]

Execute all configured filters and return the filtered event collection.

This method applies all previously configured filter criteria in sequence. An event must pass ALL filter conditions to be included in the result.

Returns:

A new ClefEventCollection containing only the events that match all filter criteria.

Raises:

Example

>>> filtered = builder            ...     .level('Error')            ...     .start_time('2026-01-24T00:00:00Z')            ...     .msg_regex(r'timeout')            ...     .filter()
>>> print(f"Found {len(filtered)} matching events")

Notes

  • Events without timestamps are excluded from time-based filters

  • Empty or None values are converted to empty strings for pattern matching

  • All filters use AND logic (events must match all conditions)

  • Malformed event data will be skipped with a warning

level(value: str) ClefEventFilterBuilder[source]

Filter events by log level.

Parameters:

value – Log level string (e.g., ‘Error’, ‘Warning’, ‘Information’, ‘Debug’).

Returns:

Self for method chaining.

Raises:

ValueError – If value is None or empty.

Example

>>> builder.level('Error')
msg_regex(value: str) ClefEventFilterBuilder[source]

Filter messages using a regular expression pattern.

Parameters:

value – Regular expression pattern string.

Returns:

Self for method chaining.

Raises:

ValueError – If the regex pattern is invalid or empty.

Example

>>> builder.msg_regex(r'failed.*timeout')
>>> builder.msg_regex(r'^ERROR: ')
msg_template_regex(value: str) ClefEventFilterBuilder[source]

Filter message templates using a regular expression pattern.

Message templates are the structured logging templates before parameter substitution (e.g., “User {UserId} logged in from {IpAddress}”).

Parameters:

value – Regular expression pattern string.

Returns:

Self for method chaining.

Raises:

ValueError – If the regex pattern is invalid or empty.

Example

>>> builder.msg_template_regex(r'User .* logged in')
renderings_regex(value: str) ClefEventFilterBuilder[source]

Filter events by renderings field using a regular expression.

Renderings contain alternative representations of log message parameters.

Parameters:

value – Regular expression pattern string.

Returns:

Self for method chaining.

Raises:

ValueError – If the regex pattern is invalid or empty.

Example

>>> builder.renderings_regex(r'format.*json')
start_time(value: str) ClefEventFilterBuilder[source]

Filter events that occurred on or after the specified timestamp.

Parameters:

value – ISO 8601 formatted timestamp string (e.g., ‘2026-01-24T10:00:00Z’).

Returns:

Self for method chaining.

Raises:

Example

>>> builder.start_time('2026-01-24T00:00:00Z')
user_fields(value: Dict[str, Any] | None) ClefEventFilterBuilder[source]

Filter events by custom user-defined fields.

Only events that have ALL specified field key-value pairs will be included.

Parameters:

value – Dictionary of field names and their expected values.

Returns:

Self for method chaining.

Raises:

ValueError – If value is None or empty dictionary.

Example

>>> builder.user_fields({'Environment': 'Production', 'Service': 'API'})
>>> builder.user_fields({'UserId': 12345})
exception pyclef.filter.ClefFilterError[source]

Bases: ClefParseError

Raised when filtering operations fail

exception pyclef.filter.ClefInvalidTimestampError(timestamp: str, original_error: Exception)[source]

Bases: ClefFilterError

Raised when timestamp parsing fails

pyclef.parser module

CLEF File Parser Module

This module provides the main parser for reading and processing CLEF (Compact Log Event Format) files. The ClefParser class handles file I/O, JSON parsing, and conversion of raw CLEF data into structured ClefEvent objects.

CLEF is a compact, newline-delimited JSON format for structured log events. Each line in a CLEF file represents a single log event with standard fields (prefixed with @) and optional user-defined fields.

Classes:
ClefParser: Main parser class for reading CLEF files and creating event

collections.

Features:
  • Memory-efficient streaming with iter_events() for large files

  • Bulk parsing with parse() for smaller files

  • Automatic field separation (reified vs user fields)

  • Comprehensive error handling with detailed exceptions

  • Support for custom encoding

Example

Basic file parsing:

from pyclef import ClefParser

# Parse entire file into collection
parser = ClefParser('application.clef')
events = parser.parse()

print(f"Loaded {len(events)} events")
for event in events:
    print(f"{event.timestamp} [{event.level}] {event.message}")

Memory-efficient streaming for large files:

parser = ClefParser('large_log.clef')

# Process events one at a time without loading all into memory
for event in parser.iter_events():
    if event.level == 'Error':
        print(f"Error found: {event.message}")
        break  # Can stop early

Using filters:

parser = ClefParser('application.clef')
events = parser.parse()

# Create a filter builder
filtered = parser.event_filter(events)
    .level('Error')
    .start_time('2026-01-24T00:00:00Z')
    .msg_regex(r'database.*timeout')
    .filter()

print(f"Found {len(filtered)} matching events")

Error handling:

from pyclef.exceptions import (
    ClefFileNotFoundError,
    ClefJSONDecodeError,
    ClefParseError
)

try:
    parser = ClefParser('log.clef')
    events = parser.parse()
except ClefFileNotFoundError as e:
    print(f"File not found: {e.file_path}")
except ClefJSONDecodeError as e:
    print(f"Invalid JSON at line {e.line_num}")
except ClefParseError as e:
    print(f"Parse error: {e}")

Custom encoding:

# Parse file with specific encoding
parser = ClefParser('log_utf16.clef')
events = parser.parse(encoding='utf-16')
CLEF Field Conventions:
  • Fields starting with @ are standard CLEF fields (reified)

  • Fields starting with @@ are user fields that should have a single @

  • All other fields are user-defined custom fields

Standard fields: @t, @m, @mt, @l, @x, @i, @r User field example: @@UserId becomes @UserId in the user dictionary

Notes

  • Use iter_events() for files larger than available memory

  • Use parse() for convenience when file size is manageable

  • All methods properly handle malformed JSON and missing files

  • Parser is stateless and thread-safe for reading different files

class pyclef.parser.ClefParser(file_path: str)[source]

Bases: object

Parser for CLEF (Compact Log Event Format) files.

This class provides methods for reading CLEF-formatted log files and converting them into structured ClefEvent objects. It supports both streaming (memory-efficient) and bulk parsing modes, with comprehensive error handling.

The parser automatically separates standard CLEF fields (those prefixed with @) from user-defined fields, and handles the @@ escape sequence for user fields that should start with a single @.

Class Attributes:
REIFIED_KEYS (set): Set of standard CLEF field names that should be

stored in the reified dictionary.

_file_path

Path to the CLEF file to be parsed.

Type:

str

Example

Basic usage:

>>> from pyclef import ClefParser
>>> parser = ClefParser('application.clef')
>>> events = parser.parse()
>>> len(events)
1000

Streaming large files:

>>> parser = ClefParser('huge_log.clef')
>>> for event in parser.iter_events():
...     if event.level == 'Fatal':
...         print(f"Fatal error: {event.message}")
...         break

Using with filters:

>>> events = parser.parse()
>>> errors = parser.event_filter(events)
...     .level('Error')
...     .filter()

Notes

  • The parser is stateless and can be reused for multiple parse operations

  • File is opened and closed automatically for each operation

  • Supports any text encoding recognized by Python’s open()

  • Thread-safe for reading different files with different instances

REIFIED_KEYS = {'@i', '@l', '@m', '@mt', '@r', '@t', '@x'}
event_filter(events: ClefEventCollection) ClefEventFilterBuilder[source]

Create a filter builder for event collection

property file_path: str

Public getter for the private _file_path attribute.

iter_events(encoding: str = 'utf-8') Iterator[ClefEvent][source]

Generator that yields events one at a time - best for huge files

parse(encoding: str = 'utf-8') ClefEventCollection[source]

Parse entire file into a collection

static parse_event(event: Dict[str, Any]) ClefEvent[source]

Parse a single event dictionary into ClefEvent

Module contents