-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathlogs_simple.go
More file actions
1295 lines (1063 loc) · 37 KB
/
Copy pathlogs_simple.go
File metadata and controls
1295 lines (1063 loc) · 37 KB
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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2024-present Datadog, Inc.
package cmd
import (
"fmt"
"io"
"regexp"
"strings"
"time"
"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
"github.com/DataDog/pup/pkg/formatter"
"github.com/spf13/cobra"
)
var logsCmd = &cobra.Command{
Use: "logs",
Short: "Search and analyze logs",
Long: `Search and analyze log data with flexible queries and time ranges.
The logs command provides comprehensive access to Datadog's log management capabilities
including search, querying, aggregation, archives management, custom destinations,
log-based metrics, and restriction queries.
CAPABILITIES:
• Search logs with flexible queries (v1 API)
• Query and aggregate logs (v2 API)
• List logs with filtering (v2 API)
• Manage log archives (CRUD operations)
• Manage custom destinations for logs
• Create and manage log-based metrics
• Configure restriction queries for access control
LOG QUERY SYNTAX:
Logs use a query language similar to web search:
• status:error - Match by status
• service:web-app - Match by service
• @user.id:12345 - Match by attribute
• host:i-* - Wildcard matching
• "exact phrase" - Exact phrase matching
• AND, OR, NOT - Boolean operators
TIME RANGES:
Supported time formats:
• Relative: 1h, 30m, 7d, 1w (hour, minute, day, week)
• Absolute: Unix timestamp in milliseconds
• now: Current time
EXAMPLES:
# Search for error logs in the last hour
pup logs search --query="status:error" --from="1h"
# Query logs from a specific service
pup logs query --query="service:web-app" --from="4h" --to="now"
# Aggregate logs by status
pup logs aggregate --query="*" --compute="count" --group-by="status"
# List log archives
pup logs archives list
# Get specific archive details
pup logs archives get "my-archive-id"
# List log-based metrics
pup logs metrics list
# Create a log-based metric
pup logs metrics create --name="error.count" --query="status:error"
# List custom destinations
pup logs custom-destinations list
# List restriction queries
pup logs restriction-queries list
AUTHENTICATION:
Requires either OAuth2 authentication (pup auth login) or API keys
(DD_API_KEY and DD_APP_KEY environment variables).`,
}
// V1 Logs API Commands (logs.yaml)
var logsSearchCmd = &cobra.Command{
Use: "search",
Short: "Search logs (v1 API)",
Long: `Search logs using the v1 Logs API with flexible query syntax.
This command provides access to historical log data using Datadog's search query
language. Results are returned in reverse chronological order (newest first).
QUERY SYNTAX:
• Basic: status:error
• Service: service:web-app
• Attributes: @user.id:12345
• Tags: env:production
• Wildcards: host:i-*
• Boolean: status:error AND service:web-app
• Negation: -status:info
TIME PARAMETERS:
--from Start time (required)
• Relative: 1h, 30m, 7d (ago from now)
• Absolute: Unix timestamp in milliseconds
--to End time (default: now)
• Same format as --from
• Must be after --from
OPTIONS:
--limit Maximum number of logs to return (default: 50, max: 1000)
--sort Sort order: asc or desc (default: desc)
--index Comma-separated list of log indexes to search
EXAMPLES:
# Search for errors in the last hour
pup logs search --query="status:error" --from="1h"
# Search specific service with time range
pup logs search --query="service:api" --from="2h" --to="1h"
# Search with attributes and limit
pup logs search --query="@http.status_code:500" --from="30m" --limit=100
# Search multiple conditions
pup logs search --query="status:error AND service:web" --from="4h"
# Search in specific indexes
pup logs search --query="*" --from="1h" --index="main,retention"
OUTPUT:
Returns an array of log events with:
• id: Log event ID
• content: Log message/content
• timestamp: Event timestamp
• attributes: Log attributes (tags, metadata)
• service: Service name
• host: Host identifier`,
RunE: runLogsSearch,
}
var logsListCmd = &cobra.Command{
Use: "list",
Short: "List logs (v2 API)",
Long: `List logs using the v2 Logs API with advanced filtering.
This command provides access to log data with more advanced filtering and
pagination capabilities compared to the v1 search API.
FILTERS:
--query Log query using search syntax
--from Start time (required)
--to End time (default: now)
--limit Number of logs to return (default: 10)
--sort Sort order: timestamp, -timestamp (default: -timestamp)
EXAMPLES:
# List recent logs
pup logs list --from="1h"
# List logs with query filter
pup logs list --query="service:api" --from="2h" --limit=50
# List logs sorted by timestamp ascending
pup logs list --query="*" --from="30m" --sort="timestamp"`,
RunE: runLogsList,
}
// V2 Logs API Commands
var logsQueryCmd = &cobra.Command{
Use: "query",
Short: "Query logs (v2 API)",
Long: `Query logs using the v2 Logs API with advanced capabilities.
This is the recommended modern API for querying logs with better performance
and more features than the v1 search API.
OPTIONS:
--query Log query (required)
--from Start time (required)
--to End time (default: now)
--limit Maximum results (default: 50)
--sort Sort order: timestamp, -timestamp
--timezone Timezone for timestamps (e.g., "America/New_York")
EXAMPLES:
# Query recent errors
pup logs query --query="status:error" --from="1h"
# Query with specific timezone
pup logs query --query="service:web" --from="4h" --timezone="America/New_York"
# Query with custom sort
pup logs query --query="@user.action:login" --from="1d" --sort="timestamp"`,
RunE: runLogsQuery,
}
var logsAggregateCmd = &cobra.Command{
Use: "aggregate",
Short: "Aggregate logs (v2 API)",
Long: `Aggregate logs with grouping and metrics computation.
Perform statistical analysis on log data by grouping and computing metrics.
This is useful for understanding log patterns, volumes, and distributions.
AGGREGATION OPTIONS:
--query Log query to filter data (required)
--from Start time (required)
--to End time (default: now)
--compute Metric to compute (count, cardinality, percentile, etc.)
--group-by Field to group by (e.g., "status", "service", "@http.status_code")
--limit Maximum number of groups (default: 10)
COMPUTE METRICS:
• count: Count of logs
• cardinality(@field): Unique values of a field
• avg(@field): Average value
• sum(@field): Sum of values
• min(@field): Minimum value
• max(@field): Maximum value
• percentile(@field, 99): Percentile calculation
EXAMPLES:
# Count logs by status
pup logs aggregate --query="*" --from="1h" --compute="count" --group-by="status"
# Count unique users
pup logs aggregate --query="service:web" --from="4h" --compute="cardinality(@user.id)"
# Average response time by service
pup logs aggregate --query="*" --from="1h" --compute="avg(@duration)" --group-by="service"
# 99th percentile latency
pup logs aggregate --query="service:api" --from="2h" --compute="percentile(@duration, 99)"
# Error rate by HTTP status code
pup logs aggregate --query="status:error" --from="1d" --compute="count" --group-by="@http.status_code"`,
RunE: runLogsAggregate,
}
// Logs Archives Commands (logs_archives.yaml)
var logsArchivesCmd = &cobra.Command{
Use: "archives",
Short: "Manage log archives",
Long: `Manage log archives for long-term storage.
Log archives allow you to store logs in external storage (S3, GCS, Azure)
for compliance, auditing, and cost optimization. Archives can be rehydrated
back into Datadog for analysis.
CAPABILITIES:
• List all log archives
• Get archive details
• Create new archives
• Update archive configuration
• Delete archives
• Manage archive ordering
STORAGE DESTINATIONS:
• AWS S3 buckets
• Google Cloud Storage
• Azure Blob Storage
EXAMPLES:
# List all archives
pup logs archives list
# Get specific archive
pup logs archives get "my-archive-id"
# Delete archive
pup logs archives delete "my-archive-id"`,
}
var logsArchivesListCmd = &cobra.Command{
Use: "list",
Short: "List all log archives",
Long: `List all configured log archives.
Returns details about all log archives including their storage destinations,
query filters, and rehydration settings.
OUTPUT:
• archive_id: Unique archive identifier
• name: Archive name
• query: Log query filter for archive
• destination: Storage destination details
• state: Archive state (active, paused)
• rehydration_max_scan_size_in_gb: Max rehydration size
EXAMPLES:
# List all archives
pup logs archives list
# List and filter with jq
pup logs archives list | jq '.data[] | select(.attributes.state == "active")'`,
RunE: runLogsArchivesList,
}
var logsArchivesGetCmd = &cobra.Command{
Use: "get [archive-id]",
Short: "Get log archive details",
Long: `Get detailed information about a specific log archive.
ARGUMENTS:
archive-id The unique identifier of the archive
EXAMPLES:
# Get archive details
pup logs archives get "my-archive-id"
# Save archive config to file
pup logs archives get "my-archive-id" > archive-config.json`,
Args: cobra.ExactArgs(1),
RunE: runLogsArchivesGet,
}
var logsArchivesDeleteCmd = &cobra.Command{
Use: "delete [archive-id]",
Short: "Delete a log archive",
Long: `Delete a log archive configuration.
WARNING: This removes the archive configuration from Datadog. It does not
delete the archived data from the storage destination.
ARGUMENTS:
archive-id The unique identifier of the archive to delete
FLAGS:
--yes, -y Skip confirmation prompt
EXAMPLES:
# Delete with confirmation
pup logs archives delete "my-archive-id"
# Delete without confirmation
pup logs archives delete "my-archive-id" --yes`,
Args: cobra.ExactArgs(1),
RunE: runLogsArchivesDelete,
}
// Custom Destinations Commands (logs_custom_destinations.yaml)
var logsCustomDestinationsCmd = &cobra.Command{
Use: "custom-destinations",
Short: "Manage custom log destinations",
Long: `Manage custom destinations for forwarding logs.
Custom destinations allow you to forward logs to external systems in real-time
for processing, storage, or integration with third-party tools.
DESTINATION TYPES:
• HTTP endpoints
• Splunk
• Elasticsearch
• Custom integrations
EXAMPLES:
# List all custom destinations
pup logs custom-destinations list
# Get destination details
pup logs custom-destinations get "destination-id"`,
}
var logsCustomDestinationsListCmd = &cobra.Command{
Use: "list",
Short: "List custom log destinations",
Long: `List all configured custom log destinations.
OUTPUT:
• id: Destination identifier
• name: Destination name
• type: Destination type (http, splunk, etc.)
• enabled: Whether destination is active
• query: Log query filter
EXAMPLES:
# List all destinations
pup logs custom-destinations list`,
RunE: runLogsCustomDestinationsList,
}
var logsCustomDestinationsGetCmd = &cobra.Command{
Use: "get [destination-id]",
Short: "Get custom destination details",
Args: cobra.ExactArgs(1),
RunE: runLogsCustomDestinationsGet,
}
// Logs Metrics Commands (logs_metrics.yaml)
var logsMetricsCmd = &cobra.Command{
Use: "metrics",
Short: "Manage log-based metrics",
Long: `Manage log-based metrics for long-term trending and alerting.
Log-based metrics convert log data into metrics for:
• Long-term storage and trending (15 months)
• Efficient alerting and monitoring
• Dashboard visualization
• Cost optimization (metrics are cheaper than logs)
METRIC TYPES:
• Count: Number of logs matching a query
• Distribution: Statistical distribution of a numeric field
EXAMPLES:
# List all log-based metrics
pup logs metrics list
# Get metric details
pup logs metrics get "error.count"
# Delete a metric
pup logs metrics delete "error.count"`,
}
var logsMetricsListCmd = &cobra.Command{
Use: "list",
Short: "List log-based metrics",
Long: `List all configured log-based metrics.
OUTPUT:
• id: Metric identifier
• name: Metric name
• type: count or distribution
• query: Log query filter
• group_by: Grouping dimensions
• compute: Aggregation field (for distribution metrics)
EXAMPLES:
# List all metrics
pup logs metrics list
# Filter active metrics
pup logs metrics list | jq '.data[] | select(.attributes.is_active == true)'`,
RunE: runLogsMetricsList,
}
var logsMetricsGetCmd = &cobra.Command{
Use: "get [metric-id]",
Short: "Get log-based metric details",
Args: cobra.ExactArgs(1),
RunE: runLogsMetricsGet,
}
var logsMetricsDeleteCmd = &cobra.Command{
Use: "delete [metric-id]",
Short: "Delete a log-based metric",
Args: cobra.ExactArgs(1),
RunE: runLogsMetricsDelete,
}
// Restriction Queries Commands (logs_restriction_queries.yaml)
var logsRestrictionQueriesCmd = &cobra.Command{
Use: "restriction-queries",
Short: "Manage log restriction queries",
Long: `Manage restriction queries for log access control.
Restriction queries control which logs users and roles can access based on
query filters. This enables fine-grained access control for sensitive data.
USE CASES:
• Limit access to production logs
• Restrict PII/sensitive data access
• Enforce compliance requirements
• Multi-tenant log isolation
EXAMPLES:
# List all restriction queries
pup logs restriction-queries list
# Get restriction query details
pup logs restriction-queries get "query-id"`,
}
var logsRestrictionQueriesListCmd = &cobra.Command{
Use: "list",
Short: "List restriction queries",
RunE: runLogsRestrictionQueriesList,
}
var logsRestrictionQueriesGetCmd = &cobra.Command{
Use: "get [query-id]",
Short: "Get restriction query details",
Args: cobra.ExactArgs(1),
RunE: runLogsRestrictionQueriesGet,
}
// Command flags
var (
// Common flags
logsQuery string
logsFrom string
logsTo string
logsLimit int
logsSort string
logsIndex string
logsTimezone string
// Aggregate flags
logsCompute string
logsGroupBy string
)
func init() {
// Search command flags (v1)
logsSearchCmd.Flags().StringVar(&logsQuery, "query", "", "Search query (required)")
logsSearchCmd.Flags().StringVar(&logsFrom, "from", "", "Start time: 1h, 30m, 7d, or timestamp (required)")
logsSearchCmd.Flags().StringVar(&logsTo, "to", "now", "End time: 1h, 30m, now, or timestamp")
logsSearchCmd.Flags().IntVar(&logsLimit, "limit", 50, "Maximum number of logs (1-1000)")
logsSearchCmd.Flags().StringVar(&logsSort, "sort", "desc", "Sort order: asc or desc")
logsSearchCmd.Flags().StringVar(&logsIndex, "index", "", "Comma-separated log indexes")
if err := logsSearchCmd.MarkFlagRequired("query"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
if err := logsSearchCmd.MarkFlagRequired("from"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
// List command flags (v2)
logsListCmd.Flags().StringVar(&logsQuery, "query", "*", "Search query")
logsListCmd.Flags().StringVar(&logsFrom, "from", "", "Start time (required)")
logsListCmd.Flags().StringVar(&logsTo, "to", "now", "End time")
logsListCmd.Flags().IntVar(&logsLimit, "limit", 10, "Number of logs")
logsListCmd.Flags().StringVar(&logsSort, "sort", "-timestamp", "Sort order")
if err := logsListCmd.MarkFlagRequired("from"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
// Query command flags (v2)
logsQueryCmd.Flags().StringVar(&logsQuery, "query", "", "Log query (required)")
logsQueryCmd.Flags().StringVar(&logsFrom, "from", "", "Start time (required)")
logsQueryCmd.Flags().StringVar(&logsTo, "to", "now", "End time")
logsQueryCmd.Flags().IntVar(&logsLimit, "limit", 50, "Maximum results")
logsQueryCmd.Flags().StringVar(&logsSort, "sort", "-timestamp", "Sort order")
logsQueryCmd.Flags().StringVar(&logsTimezone, "timezone", "", "Timezone for timestamps")
if err := logsQueryCmd.MarkFlagRequired("query"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
if err := logsQueryCmd.MarkFlagRequired("from"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
// Aggregate command flags (v2)
logsAggregateCmd.Flags().StringVar(&logsQuery, "query", "", "Log query (required)")
logsAggregateCmd.Flags().StringVar(&logsFrom, "from", "", "Start time (required)")
logsAggregateCmd.Flags().StringVar(&logsTo, "to", "now", "End time")
logsAggregateCmd.Flags().StringVar(&logsCompute, "compute", "count", "Metric to compute")
logsAggregateCmd.Flags().StringVar(&logsGroupBy, "group-by", "", "Field to group by")
logsAggregateCmd.Flags().IntVar(&logsLimit, "limit", 10, "Maximum groups")
if err := logsAggregateCmd.MarkFlagRequired("query"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
if err := logsAggregateCmd.MarkFlagRequired("from"); err != nil {
panic(fmt.Errorf("failed to mark flag as required: %w", err))
}
// Add subcommands
logsCmd.AddCommand(logsSearchCmd)
logsCmd.AddCommand(logsListCmd)
logsCmd.AddCommand(logsQueryCmd)
logsCmd.AddCommand(logsAggregateCmd)
// Archives subcommands
logsArchivesCmd.AddCommand(logsArchivesListCmd)
logsArchivesCmd.AddCommand(logsArchivesGetCmd)
logsArchivesCmd.AddCommand(logsArchivesDeleteCmd)
logsCmd.AddCommand(logsArchivesCmd)
// Custom destinations subcommands
logsCustomDestinationsCmd.AddCommand(logsCustomDestinationsListCmd)
logsCustomDestinationsCmd.AddCommand(logsCustomDestinationsGetCmd)
logsCmd.AddCommand(logsCustomDestinationsCmd)
// Metrics subcommands
logsMetricsCmd.AddCommand(logsMetricsListCmd)
logsMetricsCmd.AddCommand(logsMetricsGetCmd)
logsMetricsCmd.AddCommand(logsMetricsDeleteCmd)
logsCmd.AddCommand(logsMetricsCmd)
// Restriction queries subcommands
logsRestrictionQueriesCmd.AddCommand(logsRestrictionQueriesListCmd)
logsRestrictionQueriesCmd.AddCommand(logsRestrictionQueriesGetCmd)
logsCmd.AddCommand(logsRestrictionQueriesCmd)
}
// Helper functions
// parseTimeString converts relative or absolute time to Unix timestamp in milliseconds (UTC)
func parseTimeString(timeStr string) (int64, error) {
if timeStr == "now" {
return time.Now().UTC().UnixMilli(), nil
}
// Try parsing as relative time (1h, 30m, 7d)
if len(timeStr) >= 2 {
unit := timeStr[len(timeStr)-1:]
valueStr := timeStr[:len(timeStr)-1]
var value int64
if _, err := fmt.Sscanf(valueStr, "%d", &value); err == nil {
var duration time.Duration
switch unit {
case "s":
duration = time.Duration(value) * time.Second
case "m":
duration = time.Duration(value) * time.Minute
case "h":
duration = time.Duration(value) * time.Hour
case "d":
duration = time.Duration(value) * 24 * time.Hour
case "w":
duration = time.Duration(value) * 7 * 24 * time.Hour
default:
return 0, fmt.Errorf("invalid time unit: %s (use s, m, h, d, or w)", unit)
}
return time.Now().UTC().Add(-duration).UnixMilli(), nil
}
}
// Try parsing as Unix timestamp (milliseconds)
var timestamp int64
if _, err := fmt.Sscanf(timeStr, "%d", ×tamp); err == nil {
return timestamp, nil
}
return 0, fmt.Errorf("invalid time format: %s (use relative like '1h' or Unix timestamp)", timeStr)
}
// parseComputeString parses compute strings like "count", "avg(@duration)", "percentile(@duration, 99)"
// and returns the aggregation function and metric field
func parseComputeString(compute string) (aggregation string, metric string, err error) {
compute = strings.TrimSpace(compute)
// List of valid aggregation functions (from API error message)
validFunctions := []string{
"count", "max", "min", "avg", "sum", "median",
"cardinality", "delta", "most_frequent", "earliest",
"any", "latest", "dd_sketch", "top_n",
}
// Check for simple count
if strings.ToLower(compute) == "count" {
return "count", "", nil
}
// Parse format: function(metric) or function(metric, param)
// Examples: avg(@duration), percentile(@duration, 99), cardinality(@user.id)
re := regexp.MustCompile(`^(\w+)\(([^,)]+)(?:,\s*(\d+))?\)$`)
matches := re.FindStringSubmatch(compute)
if matches == nil {
// No parentheses - treat as a simple aggregation function
funcLower := strings.ToLower(compute)
for _, valid := range validFunctions {
if funcLower == valid {
return funcLower, "", nil
}
}
return "", "", fmt.Errorf("invalid compute format: %q\n\nExpected format:\n - count\n - function(metric) e.g. avg(@duration), sum(@bytes), cardinality(@user.id)\n - percentile(metric, N) e.g. percentile(@duration, 99)\n\nSupported functions: %s",
compute, strings.Join(validFunctions, ", "))
}
aggregation = strings.ToLower(matches[1])
metric = strings.TrimSpace(matches[2])
percentileValue := ""
if len(matches) > 3 && matches[3] != "" {
percentileValue = matches[3]
}
// Handle percentile special case: convert "percentile" to "pcNN"
if aggregation == "percentile" {
if percentileValue == "" {
return "", "", fmt.Errorf("percentile requires a percentile value: e.g. percentile(@duration, 99)")
}
aggregation = "pc" + percentileValue
}
// Validate aggregation function
isValid := false
for _, valid := range validFunctions {
if aggregation == valid {
isValid = true
break
}
}
// Also allow pcNN format (e.g., pc99, pc95, pc50)
if strings.HasPrefix(aggregation, "pc") {
isValid = true
}
if !isValid {
return "", "", fmt.Errorf("unknown aggregation function: %q\n\nSupported functions: %s, percentiles (pc50, pc75, pc90, pc95, pc99)",
aggregation, strings.Join(validFunctions, ", "))
}
return aggregation, metric, nil
}
// Implementation functions
func runLogsSearch(cmd *cobra.Command, args []string) error {
client, err := getClient()
if err != nil {
return err
}
fromTime, err := parseTimeString(logsFrom)
if err != nil {
return fmt.Errorf("invalid --from time: %w", err)
}
toTime, err := parseTimeString(logsTo)
if err != nil {
return fmt.Errorf("invalid --to time: %w", err)
}
// Use v2 API instead of deprecated v1 API
api := datadogV2.NewLogsApi(client.V2())
query := logsQuery
from := fmt.Sprintf("%d", fromTime)
to := fmt.Sprintf("%d", toTime)
limit := int32(logsLimit)
// Convert v1 sort values (asc/desc) to v2 format (timestamp/-timestamp)
v2Sort := datadogV2.LogsSort("-timestamp") // default: descending
if logsSort == "asc" {
v2Sort = datadogV2.LogsSort("timestamp")
}
body := datadogV2.LogsListRequest{
Filter: &datadogV2.LogsQueryFilter{
Query: &query,
From: &from,
To: &to,
},
Page: &datadogV2.LogsListRequestPage{
Limit: &limit,
},
Sort: &v2Sort,
}
// Note: v2 API doesn't support the index parameter the same way v1 did
// If index filtering is needed, it should be included in the query string
opts := datadogV2.ListLogsOptionalParameters{
Body: &body,
}
// Fetch first page
resp, r, err := api.ListLogs(client.Context(), opts)
if err != nil {
if r != nil && r.Body != nil {
bodyBytes, readErr := io.ReadAll(r.Body)
if readErr == nil && len(bodyBytes) > 0 {
fromTimeObj := time.UnixMilli(fromTime).UTC()
toTimeObj := time.UnixMilli(toTime).UTC()
return fmt.Errorf("failed to search logs: %w\nStatus: %d\nAPI Response: %s\n\nRequest Details:\n- Query: %s\n- From: %s UTC (parsed from: %s)\n- To: %s UTC (parsed from: %s)\n- Limit: %d\n\nTroubleshooting:\n- Verify your time range is valid\n- Check that your query syntax is correct\n- Ensure you have proper permissions",
err, r.StatusCode, string(bodyBytes),
logsQuery,
fromTimeObj.Format(time.RFC3339), logsFrom,
toTimeObj.Format(time.RFC3339), logsTo,
logsLimit)
}
return fmt.Errorf("failed to search logs: %w (status: %d)", err, r.StatusCode)
}
return fmt.Errorf("failed to search logs: %w", err)
}
// Collect logs up to the requested limit
allLogs := resp.GetData()
pageCount := 1
// Follow pagination until we hit the limit or run out of pages
for logsLimit > 0 && len(allLogs) < logsLimit {
meta, ok := resp.GetMetaOk()
if !ok || meta == nil {
break
}
page, ok := meta.GetPageOk()
if !ok || page == nil {
break
}
cursor, ok := page.GetAfterOk()
if !ok || cursor == nil || *cursor == "" {
break
}
remaining := logsLimit - len(allLogs)
if remaining <= 0 {
break
}
remainingLimit := int32(remaining)
if remainingLimit < limit {
body.Page.Limit = &remainingLimit
}
body.Page.Cursor = cursor
opts.Body = &body
resp, r, err = api.ListLogs(client.Context(), opts)
if err != nil {
printOutput("Warning: Failed to fetch page %d: %v\n", pageCount+1, err)
break
}
allLogs = append(allLogs, resp.GetData()...)
pageCount++
}
if logsLimit > 0 && len(allLogs) > logsLimit {
allLogs = allLogs[:logsLimit]
}
// Show helpful message if no logs found
if len(allLogs) == 0 {
printOutput("No logs found matching your query.\n\n")
printOutput("Tips:\n")
printOutput("- Try a broader time range (e.g., --from=\"30d\")\n")
printOutput("- Verify the service name exists in your logs\n")
printOutput("- Check your query syntax: https://docs.datadoghq.com/logs/explorer/search_syntax/\n")
printOutput("- Try a simpler query like --query=\"*\" to see any logs\n")
return nil
}
finalResp := resp
if pageCount > 1 {
finalResp.SetData(allLogs)
printOutput("Fetched %d logs across %d pages\n\n", len(allLogs), pageCount)
}
output, err := formatter.FormatOutput(finalResp, formatter.OutputFormat(outputFormat))
if err != nil {
return err
}
printOutput("%s\n", output)
return nil
}
func runLogsList(cmd *cobra.Command, args []string) error {
client, err := getClient()
if err != nil {
return err
}
fromTime, err := parseTimeString(logsFrom)
if err != nil {
return fmt.Errorf("invalid --from time: %w", err)
}
toTime, err := parseTimeString(logsTo)
if err != nil {
return fmt.Errorf("invalid --to time: %w", err)
}
api := datadogV2.NewLogsApi(client.V2())
query := logsQuery
from := fmt.Sprintf("%d", fromTime)
to := fmt.Sprintf("%d", toTime)
limit := int32(logsLimit)
sort := datadogV2.LogsSort(logsSort)
opts := datadogV2.ListLogsOptionalParameters{
Body: &datadogV2.LogsListRequest{
Filter: &datadogV2.LogsQueryFilter{
Query: &query,
From: &from,
To: &to,
},
Page: &datadogV2.LogsListRequestPage{
Limit: &limit,
},
Sort: &sort,
},
}
resp, r, err := api.ListLogs(client.Context(), opts)
if err != nil {
if r != nil && r.Body != nil {
bodyBytes, readErr := io.ReadAll(r.Body)
if readErr == nil && len(bodyBytes) > 0 {
return fmt.Errorf("failed to list logs: %w\nStatus: %d\nAPI Response: %s", err, r.StatusCode, string(bodyBytes))
}
return fmt.Errorf("failed to list logs: %w (status: %d)", err, r.StatusCode)
}
return fmt.Errorf("failed to list logs: %w", err)
}
output, err := formatter.FormatOutput(resp, formatter.OutputFormat(outputFormat))
if err != nil {
return err
}
printOutput("%s\n", output)
return nil
}
func runLogsQuery(cmd *cobra.Command, args []string) error {
client, err := getClient()
if err != nil {
return err
}
fromTime, err := parseTimeString(logsFrom)
if err != nil {
return fmt.Errorf("invalid --from time: %w", err)
}
toTime, err := parseTimeString(logsTo)
if err != nil {
return fmt.Errorf("invalid --to time: %w", err)
}
api := datadogV2.NewLogsApi(client.V2())
query := logsQuery
from := fmt.Sprintf("%d", fromTime)
to := fmt.Sprintf("%d", toTime)
limit := int32(logsLimit)
sort := datadogV2.LogsSort(logsSort)
body := datadogV2.LogsListRequest{
Filter: &datadogV2.LogsQueryFilter{
Query: &query,
From: &from,
To: &to,
},
Page: &datadogV2.LogsListRequestPage{
Limit: &limit,
},
Sort: &sort,
}
opts := datadogV2.ListLogsOptionalParameters{
Body: &body,
}
resp, r, err := api.ListLogs(client.Context(), opts)
if err != nil {
if r != nil && r.Body != nil {
bodyBytes, readErr := io.ReadAll(r.Body)
if readErr == nil && len(bodyBytes) > 0 {
return fmt.Errorf("failed to query logs: %w\nStatus: %d\nAPI Response: %s", err, r.StatusCode, string(bodyBytes))
}
return fmt.Errorf("failed to query logs: %w (status: %d)", err, r.StatusCode)
}
return fmt.Errorf("failed to query logs: %w", err)
}
output, err := formatter.FormatOutput(resp, formatter.OutputFormat(outputFormat))
if err != nil {
return err
}
printOutput("%s\n", output)
return nil
}
func runLogsAggregate(cmd *cobra.Command, args []string) error {
client, err := getClient()
if err != nil {
return err
}
fromTime, err := parseTimeString(logsFrom)
if err != nil {
return fmt.Errorf("invalid --from time: %w", err)
}
toTime, err := parseTimeString(logsTo)
if err != nil {
return fmt.Errorf("invalid --to time: %w", err)
}
// Parse the compute string to extract aggregation and metric
aggregation, metric, err := parseComputeString(logsCompute)
if err != nil {
return fmt.Errorf("invalid --compute value: %w", err)
}
api := datadogV2.NewLogsApi(client.V2())
// Build compute aggregation
compute := datadogV2.LogsCompute{
Aggregation: datadogV2.LogsAggregationFunction(aggregation),
}
// Add metric field if present
if metric != "" {
compute.Metric = &metric