-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathklp.py
executable file
·5689 lines (4819 loc) · 184 KB
/
klp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2024 Dirk Loss
"""
klp: Kool Logfmt Parser
For logs in key=value format (and some others), show only the interesting parts
"""
# Standard library imports for functionality
import argparse
import configparser
import contextlib
import csv
import dataclasses
import datetime as dt
import errno
import gzip
import inspect
import itertools
import io
import json
import multiprocessing
import os
import pprint
import re
import shlex
import shutil
import signal
import sqlite3
import sys
import textwrap
import unittest
import zipfile
from functools import partial
# Some modules to make available for filtering and templating
import base64
import collections
import datetime
import hashlib
import math
import random
import string
# Standard library typing imports
from typing import (
Dict,
Optional,
Any,
Tuple,
List,
Iterator,
Set,
Union,
TextIO,
Callable,
TypeVar,
)
# Type variable for generic types
T = TypeVar("T") # Used for generic type hints if needed
__version__ = "0.76.1"
INPUT_QUOTE = r"\""
# Names of keys our program cares about. Use lowercase keys here.
# In display order.
TS_KEYS = "_klp_timedelta ts time timestamp t at _ts @t _klp_ts".split()
TS_KEYS_NONKLP = [k for k in TS_KEYS if not k.startswith("_klp_")]
MSG_KEYS = "msg message @m".split()
LEVEL_KEYS = "log_level level lvl loglevel severity levelname @l".split()
# Regular expressions
RE_LOGFMT = re.compile(r'([\w.]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s]*))')
RE_WHITESPACE = re.compile(r"\s")
RE_EOL_OR_TAB = re.compile(r"\\n|\\t|\\r")
RE_EXTRACT_KEY = re.compile(r"^(\w+)~(.*)")
RE_CLF = re.compile(
r'(?P<host>\S+) (?P<ident>\S+) (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<request>[^"]+)" (?P<status>\d+) (?P<size>\d+|-)'
)
RE_COMBINED = re.compile(
r'(?P<host>\S+) (?P<ident>\S+) (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<request>[^"]+)" (?P<status>\d+) (?P<size>\d+|-) "(?P<referrer>[^"]*)" "(?P<agent>[^"]*)"'
)
RE_UNIX = re.compile(
r"(?P<timestamp>\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+"
r"(?P<hostname>\S+)\s+"
r"(?P<service>\S+?)(?:\[(?P<pid>\d+)\])?\s*:\s+"
r"(?P<message>.*)"
)
# ANSI Escape Codes and a short, temporary replacement sentinel that should not occur otherwise in the text
COLOR_CODES = {
"black": ("\x1b[30m", "\x01"),
"red": ("\x1b[31m", "\x02"),
"green": ("\x1b[32m", "\x03"),
"yellow": ("\x1b[33m", "\x04"),
"blue": ("\x1b[34m", "\x05"),
"magenta": ("\x1b[35m", "\x06"),
"cyan": ("\x1b[36m", "\x07"),
"white": ("\x1b[37m", "\x08"),
# Skip 0x09 to 0x0D (not supported by textwrap.wrap)
"bright_black": ("\x1b[1;30m", "\x0e"),
"bright_red": ("\x1b[1;31m", "\x0f"),
"bright_green": ("\x1b[1;32m", "\x10"),
"bright_yellow": ("\x1b[1;33m", "\x11"),
"bright_blue": ("\x1b[1;34m", "\x12"),
"bright_magenta": ("\x1b[1;35m", "\x13"),
"bright_cyan": ("\x1b[1;36m", "\x14"),
"bright_white": ("\x1b[1;37m", "\x15"),
"bold": ("\x1b[1m", "\x16"),
"off": ("\x1b[0m", "\x17"),
"underline": ("\x1b[4m", "\x18"),
"italic": ("\x1b[3m", "\x19"),
"reverse": ("\x1b[7m", "\x1a"),
}
COLOR = {key: color for key, (color, _) in COLOR_CODES.items()}
SCOLOR = {key: scolor for key, (_, scolor) in COLOR_CODES.items()}
THEMES = {
"default": {
"keys": "green",
"quotes": "off",
"message_key": "off",
"timestamp_key": "off",
"levels": {
"trace": "cyan",
"finest": "cyan",
"debug": "bright_cyan",
"finer": "bright_cyan",
"config": "bright_cyan",
"info": "bright_green",
"notice": "bright_green",
"warn": "bright_yellow",
"warning": "bright_yellow",
"error": "bright_red",
"err": "bright_red",
"fatal": "bright_red",
"panic": "bright_red",
"alert": "bright_red",
"crit": "bright_red",
"critical": "bright_red",
"emerg": "bright_red",
"emergency": "bright_red",
"severe": "bright_red",
},
"context_prefix": {
"before": "blue",
"match": "bright_magenta",
"after": "blue",
"fuse_first": "blue",
"fuse_last": "blue",
},
"skipped_marker": {"before": "cyan", "number": "cyan", "after": "cyan"},
"gap_marker": {"before": "blue", "label": "blue", "after": "blue"},
},
"classic": {
"keys": "green",
"quotes": "black",
"message_key": "bright_black",
"timestamp_key": "off",
"levels": {
"trace": "blue",
"debug": "cyan",
"info": "bright_green",
"notice": "bright_green",
"warn": "bright_yellow",
"warning": "bright_yellow",
"error": "bright_red",
"err": "bright_red",
"fatal": "bright_red",
"panic": "bright_red",
"alert": "bright_red",
"crit": "bright_red",
"emerg": "bright_red",
},
"context_prefix": {
"before": "blue",
"match": "bright_magenta",
"after": "blue",
"fuse_first": "blue",
"fuse_last": "blue",
},
"skipped_marker": {"before": "blue", "number": "black", "after": "blue"},
"gap_marker": {"before": "blue", "label": "black", "after": "blue"},
},
"light": {
"keys": "blue",
"quotes": "off",
"message_key": "off",
"timestamp_key": "off",
"levels": {
"trace": "magenta",
"debug": "cyan",
"info": "green",
"notice": "green",
"warn": "yellow",
"warning": "yellow",
"error": "red",
"err": "red",
"fatal": "bright_red",
"panic": "bright_red",
"alert": "bright_red",
"crit": "bright_red",
"emerg": "bright_red",
},
"context_prefix": {
"before": "blue",
"match": "magenta",
"after": "blue",
"fuse_first": "blue",
"fuse_last": "blue",
},
"skipped_marker": {"before": "cyan", "number": "bright_black", "after": "cyan"},
"gap_marker": {"before": "blue", "label": "bright_black", "after": "blue"},
},
"tty": {
"keys": "italic",
"quotes": "off",
"message_key": "off",
"timestamp_key": "off",
"levels": {
"trace": "off",
"debug": "off",
"info": "off",
"notice": "off",
"warn": "bold",
"warning": "bold",
"error": "reverse",
"err": "reverse",
"fatal": "reverse",
"panic": "reverse",
"alert": "reverse",
"crit": "reverse",
"emerg": "reverse",
},
"context_prefix": {
"before": "off",
"match": "reverse",
"after": "off",
"fuse_first": "italic",
"fuse_last": "italic",
},
"skipped_marker": {"before": "off", "number": "underline", "after": "off"},
"gap_marker": {"before": "off", "label": "underline", "after": "off"},
},
}
BUILTIN_REGEXES = {
# https://www.regular-expressions.info/email.html
"email": [r"\b(([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b))"],
"err": [
r"(?i)\b((error|err|panic|crit|critical|alert|fatal|emerg|failed|failure|exception))\b"
],
"fqdn": [
r"\b(((?:[a-z](?:[a-z0-9-]{0,63}[a-z0-9])?\.){2,}[a-z0-9][a-z0-9-]{0,8}))"
],
"function": [r"\b(([\w\.]+\([^)]*\)))"],
"gitcommit": [r"\b(([0-9a-fA-F]{7,40}))\b"],
"hexcolor": [r"((#[0-9A-Fa-f]{6}))\b"],
"ipv4": [
r"\b((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\b"
],
"ipv6": [
r"\b(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\b"
],
"isotime": [
r"\b(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?\b)"
],
"json": [r"((\{[^{}]*?\}))"],
"jwt": [r"((eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*))"],
"mac": [
r"\b(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))\b",
r"\b(([0-9A-Fa-f]{4}\.){2}([0-9A-Fa-f]{4}))\b",
],
"md5": [r"\b(([a-fA-F0-9]{32}))\b"],
"oauth": [r"\b((ya29\.[0-9A-Za-z_-]+))\b"],
"path": [r"((^|(?<=[^./\w-]))(/[.\w-]+)+/?)"],
"sha1": [r"\b(([a-fA-F0-9]{40}))\b"],
"sha256": [r"\b(([a-fA-F0-9]{64}))\b"],
"sql": [
r'"(((?:SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE|MERGE)\s+(?:(?!"|\().|\([^)]*\))*))"'
],
"url": [
r"\b(((?:[a-z][a-z0-9+.-]*):\/\/(?:(?:[^\s:@]+(?::[^\s:@]*)?@)?(?:[^\s:/?#]+)(?::\d+)?(?:\/[^\s?#]*)?(?:\?[^\s#]*)?(?:#[^\s]*)?)))\b"
],
"uuid": [
r"\b(([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}))\b"
],
"version": [r"\b(([vV])\d+\.\d+(\.\d+)?(-[a-zA-Z0-9]+)?)\b"],
"winpath": [r"((^|(?<=[^:\\]))(?:[A-Za-z]:|\\\\|\.|\.\.)?(?:\\[\w.()\- ]+)+\\?)"],
"winregistry": [r"((HKEY_[A-Z_]+(?:\\[A-Za-z0-9_]+)+))"],
}
EPILOG = f"""
INTERVAL units: us=microseconds/ms=milliseconds/s=seconds/m=minutes/h=hours/d=days/w=weeks"
Highlighted keys: {",".join(TS_KEYS + MSG_KEYS + LEVEL_KEYS)}
"""
terminal_width = shutil.get_terminal_size((80, 24)).columns
_klp_global_num = 0
_klp_global_list = []
_klp_global_set = set({})
_klp_global_dict = {}
def build_globals_dict(modules: List[Any]) -> Dict[str, Any]:
"""
Build a dictionary of modules and their exported functions for template evaluation.
Creates a dictionary mapping names to module objects and functions for use in
evaluating Python expressions in templates and filters.
Args:
modules: List of module objects to include in the globals dictionary
Returns:
Dict[str, Any]: Dictionary containing:
- Module objects mapped to their names
- Standard functions with their existing docstrings
- Auto-generated regex extraction functions
Side Effects:
- Creates extraction functions for each builtin regex pattern
- Preserves original docstrings of included functions
"""
d = {}
# Add the modules
for module in modules:
name = module.__name__
d[name] = module
# Add the standard functions - use their existing docstrings
standard_funcs = [
extract_json,
extract_regex,
format_datetime,
guess_datetime,
parse_kv,
parse_logfmt,
parse_jsonl,
parse_clf,
parse_combined,
parse_log4j,
parse_cef,
parse_unix,
parse_line,
parse_data,
pprint_json,
sh,
]
for func in standard_funcs:
d[func.__name__] = func
# Add regex extraction functions
for regex_name in BUILTIN_REGEXES:
func = create_extraction_function(regex_name)
d[func.__name__] = func
return d
def print_output(*myargs: Any, **kwargs: Any) -> None:
"""
Print output to the configured output file with specified arguments.
Wrapper around the print function that directs output to args.output_file.
All arguments are passed directly to print().
Args:
*myargs: Variable positional arguments to pass to print()
**kwargs: Variable keyword arguments to pass to print()
Side Effects:
- Writes to file specified by args.output_file
- Uses print() behavior for actual output
Example:
>>> print_output("test", end="\\n") # Writes "test\\n" to args.output_file
"""
print(*myargs, **kwargs, file=args.output_file)
def handle_error(
message: str,
e: Optional[Exception] = None,
exitcode: int = 1,
debug_eval: bool = False,
debug_where: bool = False,
**kwargs,
) -> None:
"""Handle errors according to error_handling setting.
Args:
message: Error description message
e: Optional exception that was caught
exitcode: Exit code to use when error_handling is "exit" (default: 1)
debug_eval: Treat debug_eval like debug
debug_where: Treat debug_where like debug
**kwargs: Additional arguments passed to print_err
Side Effects:
- May print to stderr depending on error_handling setting
- May exit program if error_handling is "exit"
"""
error_text = f"{message}" if e is None else f"{message}: {e}"
if args.error_handling == "ignore":
if (
args.debug
or (debug_eval and args.debug_eval)
or (debug_where and args.debug_where)
):
print_err(error_text, **kwargs)
return
elif args.error_handling == "print":
print_err(error_text, **kwargs)
else: # exit
print_err(error_text, **kwargs)
sys.exit(exitcode)
def get_default_process_count() -> int:
"""
Calculate the default number of processes for parallel processing.
Determines optimal process count based on CPU count, reserving one CPU
for the main process to maintain system responsiveness.
Returns:
int: Number of processes to use:
- CPU count minus 1 if multiple CPUs available
- Minimum of 1 process
- 1 if CPU count cannot be determined
Notes:
- Uses multiprocessing.cpu_count() when available
- Handles NotImplementedError gracefully
- Never returns less than 1
- Used as default when parallel processing is enabled
Example:
On a 4-core system:
>>> get_default_process_count()
3
"""
try:
return max(multiprocessing.cpu_count() - 1, 1)
except NotImplementedError:
return 1
def extract_json(text: str) -> str:
"""
Extract the first valid JSON object or array from a text string.
The function searches for valid JSON structures within the text, attempting to extract
complete JSON objects or arrays. It handles nested structures and ensures the extracted
JSON is valid.
Args:
text (str): The string containing potential JSON content
Returns:
str: The first valid JSON object or array found in the text as a string
Raises:
ValueError: If no valid JSON object or array can be found in the input text
Examples:
>>> extract_json('foo { "key": "value" } bar')
'{ "key": "value" }'
>>> extract_json('[1, 2, {"a": "b"}]')
'[1, 2, {"a": "b"}]'
"""
json_start_chars = {"{", "["}
json_end_chars = {"}": "{", "]": "["}
start = None
stack = []
for i, char in enumerate(text):
if char in json_start_chars:
if start is None:
start = i
stack.append(char)
elif char in json_end_chars:
if stack and stack[-1] == json_end_chars[char]:
stack.pop()
if not stack:
json_str = text[start : i + 1]
try:
json.loads(json_str)
return json_str
except json.JSONDecodeError:
pass
start = None
raise ValueError(f"Could not extract JSON from {text!r}")
def pprint_json(json_string, indent=2, sort_keys=True, ensure_ascii=False):
"""
Pretty-print a JSON string.
Args:
json_string (str): The JSON string to be pretty-printed.
indent (int, optional): Number of spaces to use for indentation. Defaults to 2.
sort_keys (bool, optional): Whether to sort the dictionary keys. Defaults to True.
ensure_ascii (bool, optional): Whether to escape non-ASCII characters. Defaults to False.
Returns:
str: A pretty-printed JSON string.
Raises:
ValueError: If the provided string is not a valid JSON.
Example:
>>> input_json = '{"name":"John", "age":30, "city":"New York"}'
>>> pprint_json(input_json, indent=4)
'{
"age": 30,
"city": "New York",
"name": "John"
}'
"""
try:
parsed_json = json.loads(json_string)
pretty_json = json.dumps(
parsed_json, indent=indent, sort_keys=sort_keys, ensure_ascii=ensure_ascii
)
return pretty_json
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON string: {e}")
def guess_datetime(timestamp: str) -> Optional[datetime.datetime]:
"""
Attempt to convert a given timestamp string into a datetime object using various datetime converters.
The function tries different datetime formats in order until it finds one that successfully parses
the timestamp. When a successful format is found, it's moved to the front of the list to optimize
future parsing of similar timestamps.
Args:
timestamp (str): The timestamp string to be converted
Returns:
Optional[datetime.datetime]: A datetime object if conversion is successful, None otherwise
Side Effects:
Updates the global dt_conv_order list to prioritize successful converters
Examples:
>>> guess_datetime("2024-03-16T14:30:00Z")
datetime.datetime(2024, 3, 16, 14, 30, tzinfo=datetime.timezone.utc)
>>> guess_datetime("invalid")
None
"""
global dt_conv_order
datetime = None
for i in dt_conv_order:
converter = datetime_converters[i]
try:
datetime = converter(timestamp)
# print("guess", i, timestamp, "as", datetime, datetime.tzname(), file=sys.stderr) # debug
if datetime is None:
continue
else:
break
except (AttributeError, ValueError, TypeError):
continue
# Bring found converter to the front so that it's tried first next time
if not dt_conv_order[0] == i:
dt_conv_order.insert(0, dt_conv_order.pop(i))
return datetime
def format_datetime(val):
"""
Format a given datetime string into a standardized ISO 8601 format string with milliseconds precision.
The function converts the input datetime string to either local time or UTC time based on the specified
command-line arguments (`--localtime` or `--utc`). It then formats the datetime object into the ISO 8601
format, including milliseconds.
Args:
val (str): The datetime string to be formatted.
Returns:
str: The formatted datetime string in ISO 8601 format with milliseconds precision. The returned string
will be in local time if `--localtime` is True, or in UTC time with a "Z" suffix if `--utc`
is True.
Raises:
ValueError: If the input `val` cannot be parsed as a datetime.
Notes:
- The function uses the `to_datetime` function to parse the input datetime string.
- The `args` object is expected to have the boolean attributes `localtime` and `utc` which determine
the desired timezone for the output.
Example:
>>> args.localtime = True
>>> format_datetime("2023-10-05 14:48:00")
'2023-10-05T14:48:00.000Z'
>>> args.utc = True
>>> format_datetime("2023-10-05 14:48:00")
'2023-10-05T14:48:00.000Z'
"""
try:
if args.localtime:
val = to_datetime(val).astimezone().isoformat(timespec="milliseconds")
elif args.utc:
val = (
to_datetime(val)
.astimezone(dt.timezone.utc)
.isoformat(timespec="milliseconds")
.replace("+00:00", "Z")
)
except ValueError as e:
handle_error("Failed to format datetime", e)
return val
def extract_regex(
pattern: str, s: str, *groupargs: int
) -> Optional[Union[str, Tuple[str, ...]]]:
r"""
Extract substring(s) from text that match a specified regular expression pattern.
Searches for the first match of a regex pattern in the input string and returns
the specified capture groups.
Args:
pattern (str): The regular expression pattern to search for
s (str): The string to search within
*groupargs (int): Variable number of group indices to retrieve from the match
Returns:
Optional[Union[str, Tuple[str, ...]]]:
- If one group requested: The matched group as string or None
- If multiple groups: Tuple of matched groups or None
- Returns None if pattern doesn't match
Examples:
>>> extract_regex(r"(\d+)", "There are 123 apples", 0)
'123'
>>> extract_regex(r"(\d+)\D+(\d+)", "12 apples and 34 oranges", 1, 2)
('12', '34')
"""
match = re.search(pattern, s)
if match:
return match.group(*groupargs)
return None
def extract_builtin_regex(regex_name, s):
if regex_name in BUILTIN_REGEXES:
pattern = BUILTIN_REGEXES[regex_name][0]
match = re.search(pattern, s)
if match:
return match.group()
return None
def create_extraction_function(regex_name: str) -> Callable[[str], Optional[str]]:
"""
Create a function that extracts text matching a built-in regex pattern.
Factory function that generates extraction functions for built-in regex patterns.
The generated functions are named extract_{regex_name} and include proper docstrings.
Args:
regex_name: Name of the built-in regex pattern to use
Returns:
Callable[[str], Optional[str]]: Function that:
- Takes a string argument
- Returns first match of the pattern or None
- Has descriptive name and docstring
Example:
>>> extract_email = create_extraction_function("email")
>>> extract_email("Contact us at test@example.com")
'test@example.com'
"""
def extraction_function(s):
"""Extract the first match of a built-in regex pattern from a string.
Args:
s (str): String to search in
Returns:
str or None: First match of the pattern, or None if no match found
"""
if regex_name in BUILTIN_REGEXES:
pattern = BUILTIN_REGEXES[regex_name][0]
match = re.search(pattern, s)
if match:
return match.group()
return None
doc = {
"email": "email address",
"err": "error value",
"fqdn": "fully qualified domain name (FQDN)",
"function": "function calls",
"gitcommit": "git commit hash",
"hexcolor": "hex color code",
"ipv4": "IPv4 address",
"ipv6": "IPv6 address",
"isotime": "ISO 8601 datetime string",
"json": "JSON string",
"jwt": "JSON Web Token (JWT)",
"mac": "MAC address",
"md5": "MD5 hash",
"path": "Unix file path",
"oauth": "OAuth token",
"sha1": "SHA-1 hash",
"sha256": "SHA-256 hash",
"sql": "SQL query",
"url": "URL",
"uuid": "UUID",
"version": "software version identifier",
"winregistry": "Windows registry key",
}
extraction_function.__name__ = f"extract_{regex_name}"
pattern = doc.get(regex_name, regex_name)
extraction_function.__doc__ = f"""Return the first {pattern} in a given string."""
return extraction_function
def get_code(code_or_script):
"""
Load code from a string or file path.
If prefixed with '@', reads from file. Otherwise, returns input directly.
"""
if not code_or_script.startswith("@"):
return code_or_script
try:
with open(code_or_script[1:], "r", encoding="utf-8") as file:
return file.read()
except Exception as e:
raise ValueError(f"Error reading code from file: {e}")
def apply_input_exec(event):
events = [event]
if args.input_exec:
for item in args.input_exec:
code = get_code(item)
new_events = []
for event in events:
new_events.extend(input_exec(code, event))
events = new_events
return events
def parse_linebased(line, format):
def identity(x):
return x
format_parsers = {
# line-based
"logfmt": parse_logfmt,
"jsonl": parse_jsonl,
"clf": parse_clf,
"combined": parse_combined,
"log4j": parse_log4j,
"cef": parse_cef,
"unix": parse_unix,
"line": parse_line,
"ts1m": parse_ts1m,
"ts1lm": parse_ts1lm,
"ts2m": parse_ts2m,
"ts2lm": parse_ts2lm,
"ts3m": parse_ts3m,
"ts3lm": parse_ts3lm,
"ts4m": parse_ts4m,
"ts4lm": parse_ts4lm,
"ts5m": parse_ts5m,
"ts5lm": parse_ts5lm,
# Non-line-based (have already been parsed)
"json": identity,
"csv": identity,
"tsv": identity,
"psv": identity,
"table": identity,
"data": identity,
}
parser = format_parsers.get(format)
if not parser:
raise ValueError(f"Unknown input format: {format}")
return parser(line)
def parse_chunk(chunk, input_format):
return [parse_linebased(line, input_format) for line in chunk]
def init_worker():
# Let the main process handle CTRL-C
signal.signal(signal.SIGINT, signal.SIG_IGN)
def parallel_process(
file_paths: List[str], args: argparse.Namespace
) -> Iterator[Tuple[Dict[str, Any], int]]:
"""
Process multiple files in parallel using a process pool.
Implements parallel processing of log files using Python's multiprocessing.
Handles file chunking, worker initialization, and signal handling for
graceful interruption.
Args:
file_paths: List of paths to files to process
args: Command line arguments namespace containing:
- parallel: Number of processes to use (or None for auto)
- input_format: Format of input files
- input_encoding: File encoding to use
Yields:
Tuple[Dict[str, Any], int]: Each tuple contains:
- Parsed event dictionary
- Line number in current file
Side Effects:
- Creates a process pool
- Sets up signal handlers in worker processes
- Chunks files for efficient parallel processing
Notes:
- Uses get_default_process_count() when args.parallel is None
- Chunk size is fixed at 10000 lines for memory efficiency
- Workers ignore SIGINT to allow main process to handle cleanup
"""
def chunk_file(file_path):
chunk_size = 10000
with file_opener(file_path, encoding=args.input_encoding) as f:
while True:
chunk = list(itertools.islice(f, chunk_size))
if not chunk:
break
yield chunk
parse_func = partial(parse_chunk, input_format=args.input_format)
process_count = args.parallel or get_default_process_count()
with multiprocessing.Pool(process_count, init_worker) as pool:
for file_path in file_paths:
chunks = chunk_file(file_path)
start_line = 1
for parsed_chunk in pool.imap(parse_func, chunks):
for i, event in enumerate(parsed_chunk, start=start_line):
yield event, i
start_line += len(parsed_chunk)
def parse_logfmt(text: str) -> Dict[str, str]:
"""
Parse a logfmt-formatted string into a dictionary.
Logfmt is a log format that produces logs as key-value pairs separated by spaces, where values
can be either quoted or unquoted. This function extracts these pairs into a dictionary.
Args:
text (str): A logfmt-formatted string
Returns:
Dict[str, str]: A dictionary where keys are logfmt keys and values are their corresponding
unescaped values (quoted values are unescaped, unquoted values are kept as-is)
Example:
>>> parse_logfmt('key1="value 1" key2=simple')
{'key1': 'value 1', 'key2': 'simple'}
"""
return {
key: (unescape(quoted_val) if quoted_val else unquoted_val)
for key, quoted_val, unquoted_val in RE_LOGFMT.findall(text)
}
def split_startswith(s: str, pattern: str, keep_all: bool = True) -> List[str]:
"""
Split string into parts where each part starts with text matching a regex pattern.
Splits a string into sections based on where matches of the pattern occur. The pattern
matches are included at the start of each section except possibly the first one.
Args:
s (str): Input string that may contain newlines
pattern (str): Regular expression pattern that should match the start of each part
Returns:
List[str]: List of string parts including:
- Text before first match (if non-empty)
- Parts starting with pattern match extending until next match
- Final part from last match to end of string
If pattern matches empty string or doesn't match, returns [s]
Examples:
>>> split_startswith("A.\\nB.\\nC.\\n", r"\\.\\n")
['A', '.\\nB', '.\\nC', '.\\n']
>>> split_startswith("axbxcx", "x")
['a', 'xb', 'xc', 'x']
"""
# Handle empty pattern or patterns that could match empty string
if not pattern or re.match(pattern, ""):
return [s]
# If string is empty, return list with empty string
if not s:
return [""]
# Find all starting positions of the pattern
matches = list(re.finditer(pattern, s))
if not matches:
if keep_all:
return [s]
else:
return []
result = []
# Add the part before first match only if it's non-empty
if keep_all and matches[0].start() > 0:
result.append(s[: matches[0].start()])
# Process each match
for i, match in enumerate(matches):
start = match.start()
# If this is the last match, go to the end of string
if i == len(matches) - 1:
result.append(s[start:])
else:
# Otherwise, go until the start of the next match
next_start = matches[i + 1].start()
result.append(s[start:next_start])
return result
def split_endswith(s, pattern, keep_all=True):
r"""
Split a string into parts where each part ends with text matching the specified regex pattern.
Uses greedy (non-overlapping) matching and preserves the pattern in the output.
Args:
s (str): Input string that may contain newlines
pattern (str): Regular expression pattern that should match the end of each part
Returns:
List[str]: List of string parts, where each part ends with text matching the pattern.
If pattern matches empty string, returns [s].
If pattern doesn't match anywhere, returns [s].
Includes any remaining text after the last match.
Examples:
>>> split_endswith("A.\nB.\nC.\n", r"\.\n")
['A.\n', 'B.\n', 'C.\n']
>>> split_endswith("A.\nB.\nC", r"\.\n")
['A.\n', 'B.\n', 'C']
>>> split_endswith("aaaa", "aa")
['aa', 'aa']
>>> split_endswith("x", "x")
['x']
>>> split_endswith("axbxcx", "x")
['ax', 'bx', 'cx']
>>> split_endswith("abc", ".*")
['abc']
>>> split_endswith("", r"\.\n")
['']
"""
# Handle empty pattern or patterns that could match empty string
if not pattern or re.match(pattern, ""):
return [s]
# If string is empty, return list with empty string