Repository navigation
Expand file tree
/
Copy pathapi.R
More file actions
1151 lines (1068 loc) · 36.5 KB
/
Copy pathapi.R
File metadata and controls
1151 lines (1068 loc) · 36.5 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
#' Get a tracer from the default tracer provider
#'
#' Calls [get_default_tracer_provider()] to get the default tracer
#' provider. Then calls its `$get_tracer()` method to create a new tracer.
#'
#' Usually you do not need to call this function directly, because
#' [start_local_active_span()] calls it for you.
#'
#' Calling `get_tracer()` multiple times with the same `name` (or same
#' auto-deduced name) will return the same (internal) tracer object.
#' (Even if the R external pointer objects representing them are
#' different.)
#'
#' A tracer is only deleted if its tracer provider is deleted and garbage
#' collected.
#'
#' @param name Name of the new tracer. If missing, then deduced
#' automatically using [default_tracer_name()]. Make sure you read
#' the manual page of [default_tracer_name()] before using this argument.
#' @param version Optional. Specifies the version of the instrumentation
#' scope if the scope has a version (e.g. R package version).
#' Example value: `"1.0.0"`.
#' @param schema_url Optional. Specifies the Schema URL that should be
#' recorded in the emitted telemetry.
#' @param attributes Optional. Specifies the instrumentation scope
#' attributes to associate with emitted telemetry.
#' @param ... Additional arguments are passed to the `get_tracer()`
#' method of the provider.
#' @param provider Tracer provider to use. If `NULL`, then it uses
#' [get_default_tracer_provider()] to get a tracer provider.
#'
#' @return An OpenTelemetry tracer, an [otel_tracer] object.
#'
#' @export
#' @family low level trace API
#' @examples
#' myfun <- function() {
#' trc <- otel::get_tracer()
#' spn <- trc$start_span()
#' on.exit(otel::end_span(spn), add = TRUE)
#' otel::local_active_span(spn, end_on_exit = TRUE)
#' }
#' myfun()
# safe start
get_tracer <- function(
name = NULL,
version = NULL,
schema_url = NULL,
attributes = NULL,
...,
provider = NULL
) {
tryCatch({ # safe
# does setup if necessary
provider <- provider %||% get_default_tracer_provider()
trc <- provider$get_tracer(name, version, schema_url, attributes, ...)
invisible(trc)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
tracer_noop$new() # safe
}) # safe
}
# safe end
get_tracer_safe <- get_tracer
# Tracer for otel's own use, e.g. to query the active span. These do not
# depend on the tracer name, so we use a fixed name, and cache the tracer,
# to avoid looking up the tracer name from the call stack on every call.
# The cached tracer is only reused if the default tracer provider has
# not changed, e.g. otelsdk::with_otel_record() sets a new one.
# If `tracer` is a tracer object or a tracer name, then it is used instead.
otel_tracer_name <- "org.r-lib.otel"
get_otel_tracer <- function(tracer = NULL) {
if (inherits(tracer, "otel_tracer")) {
return(tracer)
}
if (!is.null(tracer)) {
return(get_tracer(tracer))
}
provider <- get_default_tracer_provider()
cache <- the$otel_tracer
if (!is.null(cache) && identical(cache$provider, provider)) {
return(cache$tracer)
}
trc <- get_tracer(otel_tracer_name, provider = provider)
the$otel_tracer <- list(provider = provider, tracer = trc)
trc
}
#' Get a logger from the default logger provider
#'
#' @param name Name of the new tracer. If missing, then deduced automatically.
#' @param minimum_severity A log level, the minimum severity log messages
#' to log. See [log_severity_levels].
#' @param ... Additional arguments are passed to the `get_logger()`
#' method of the provider.
#' @param provider Tracer provider to use. If `NULL`, then it uses
#' [get_default_tracer_provider()] to get a tracer provider.
#' @inheritParams get_tracer
#'
#' @return An [otel_logger] object.
#'
#' @export
#' @family low level logs API
#' @examples
#' myfun <- function() {
#' lgr <- otel::get_logger()
#' otel::log("Log message", logger = lgr)
#' }
#' myfun()
# safe start
get_logger <- function(
name = NULL,
minimum_severity = NULL,
version = NULL,
schema_url = NULL,
attributes = NULL,
...,
provider = NULL
) {
tryCatch({ # safe
# does setup if necessary
provider <- provider %||% get_default_logger_provider()
lgr <- provider$get_logger(
name,
minimum_severity,
version,
schema_url,
attributes,
...
)
invisible(lgr)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
get_logger_safe <- get_logger
#' Get a meter from the default meter provider
#'
#' @param name Name of the new tracer. If missing, then deduced automatically.
#' @param ... Additional arguments are passed to the `get_meter()`
#' method of the provider.
#' @param provider Meter provider to use. If `NULL`, then it uses
#' [get_default_meter_provider()] to get a tracer provider.
#'
#' @return An [otel_meter] object.
#'
#' @inheritParams get_tracer
#' @export
#' @family low level metrics API
#' @examples
#' myfun <- function() {
#' mtr <- otel::get_meter()
#' ctr <- mtr$create_counter("session-count")
#' ctr$add(1)
#' }
#' myfun()
# safe start
get_meter <- function(
name = NULL,
version = NULL,
schema_url = NULL,
attributes = NULL,
...,
provider = NULL
) {
tryCatch({ # safe
# does setup if necessary
provider <- provider %||% get_default_meter_provider()
mtr <- provider$get_meter(name, version, schema_url, attributes, ...)
invisible(mtr)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
meter_noop$new() # safe
}) # safe
}
# safe end
get_meter_safe <- get_meter
#' Activate an OpenTelemetry span for an R scope
#'
#' @description
#' Activates the span for the caller (or other) frame.
#'
#' Usually you need this function for spans created with [start_span()],
#' which does not activate the new span. Usually you don't need it for
#' spans created with [start_local_active_span()], because it activates
#' the new span automatically.
#'
#' @details
#' When the frame ends, the span is deactivated and the previously active
#' span will be active again, if there was any.
#'
#' It is possible to activate the same span for multiple R frames.
#'
#' @param span The OpenTelemetry span to activate.
#' @param end_on_exit Whether to end the span when exiting the activation
#' scope.
#' @param activation_scope The scope to activate the span for, defaults to
#' the caller frame.
#' @return Nothing.
#'
#' @export
#' @family OpenTelemetry trace API
#' @family tracing for concurrent code
#' @inherit start_span examples
# safe start
local_active_span <- function(
span,
end_on_exit = FALSE,
activation_scope = parent.frame()
) {
tryCatch({ # safe
invisible(span$activate(activation_scope, end_on_exit = end_on_exit))
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
}) # safe
}
# safe end
local_active_span_safe <- local_active_span
#' Evaluate R code with an active OpenTelemetry span
#'
#' @description
#' Activates the span for evaluating an R expression.
#'
#' Usually you need this function for spans created with [start_span()],
#' which does not activate the new span. Usually you don't need it for
#' spans created with [start_local_active_span()], because it activates
#' the new span automatically.
#'
#' @details
#' After `expr` is evaluated (or an error occurs), the span is deactivated
#' and the previously active span will be active again, if there was any.
#'
#' It is possible to activate the same span for multiple R frames.
#'
#' @param span The OpenTelemetry span to activate.
#' @param expr R expression to evaluate.
#' @param end_on_exit Whether to end after evaluating the R expression.
#' @return The return value of `expr`.
#'
#' @export
#' @family OpenTelemetry trace API
#' @family tracing for concurrent code
#' @examples
#' fun <- function() {
#' # start span, do not activate
#' spn <- otel::start_span("myfun")
#' # do not leak resources
#' on.exit(otel::end_span(spn), add = TRUE)
#' myfun <- function() {
#' otel::with_active_span(spn, {
#' # create child span
#' spn2 <- otel::start_local_active_span("myfun/2")
#' })
#' }
#'
#' myfun2 <- function() {
#' otel::with_active_span(spn, {
#' # create child span
#' spn3 <- otel::start_local_active_span("myfun/3")
#' })
#' }
#' myfun()
#' myfun2()
#' end_span(spn)
#' }
#' fun()
# safe start
with_active_span <- function(span, expr, end_on_exit = FALSE) {
local({
tryCatch({ # safe
invisible(span$activate(end_on_exit = end_on_exit))
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
}) # safe
expr
})
}
# safe end
with_active_span_safe <- with_active_span
#' OpenTelemetry log severity levels
#'
#' A named integer vector, the severity levels in numeric form.
#' The names are the severity levels in text form. otel functions accept
#' both forms as severity levels, but the text form is more readable.
#'
#' @export
#' @usage NULL
#' @format NULL
#' @seealso '[Environment Variables]' needed to set OpenTelemetry logging level.
#' @family OpenTelemetry logs API
#' @return Not applicable.
#' @examples
#' log_severity_levels
log_severity_levels <- c(
"trace" = 1L,
"trace2" = 2L,
"trace3" = 3L,
"trace4" = 4L,
"debug" = 5L,
"debug2" = 6L,
"debug3" = 7L,
"debug4" = 8L,
"info" = 9L,
"info2" = 10L,
"info3" = 11L,
"info4" = 12L,
"warn" = 13L,
"warn2" = 14L,
"warn3" = 15L,
"warn4" = 16L,
"error" = 17L,
"error2" = 18L,
"error3" = 19L,
"error4" = 20L,
"fatal" = 21L,
"fatal2" = 22L,
"fatal3" = 23L,
"fatal4" = 24L,
NULL
)
md_log_severity_levels <- paste0(
"\"",
names(log_severity_levels),
"\"",
collapse = ", "
)
#' Returns the active span, if any
#'
#' This is sometimes useful, to add additional attributes or links to the
#' currently active span.
#'
#' @param tracer Tracer object ([otel_tracer]) or tracer name to use.
#' If `NULL`, then otel uses an internal tracer. You usually do not
#' need to set this, the active span does not depend on the tracer.
#'
#' Passing a tracer might give the wrong result. If it is a no-op
#' tracer, then the result is an invalid span (context), or no HTTP
#' headers, even if there is an active span. This happens if the
#' tracer's scope is turned off, e.g. via the `OTEL_R_SUPPRESS_SCOPES`
#' environment variable, or if the tracer was created before tracing
#' was turned on. The default `NULL` does not have this problem.
#'
#' @return The active span, an [otel_span] object, if any, or an invalid
#' span if there is no active span.
#' @export
#' @examples
#' fun <- function() {
#' otel::start_local_active_span("fun")
#' spn <- otel::get_active_span()
#' spn$set_attribute("key", "attribute-value")
#' }
#' fun()
# safe start
get_active_span <- function(tracer = NULL) {
tryCatch({ # safe
trc <- get_otel_tracer(tracer)
trc$get_active_span()
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
span_noop$new(NA_character_) # safe
}) # safe
}
# safe end
#' Returns the active span context
#'
#' This is sometimes useful for logs or metrics, to associate
#' logging and metrics reporting with traces.
#'
#' Note that logs and metrics instruments automatically use the current
#' span context, so often you don't need to call this function explicitly.
#'
#' @inheritParams get_active_span
#' @return The active span context, an [otel_span_context] object.
#' If there is no active span context, then an invalid span context is
#' returned, i.e. `spc$is_valid()` will be `FALSE` for the returned `spc`.
#'
#' @export
#' @examples
#' fun <- function() {
#' otel::start_local_active_span("fun")
#' fun2()
#' }
#' fun2 <- function() {
#' otel::log("Log message", span_context = otel::get_active_span_context())
#' }
#' fun()
# safe start
get_active_span_context <- function(tracer = NULL) {
tryCatch({ # safe
trc <- get_otel_tracer(tracer)
trc$get_active_span_context()
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
span_context_noop$new(NA_character_) # safe
}) # safe
}
# safe end
get_active_span_context_safe <- get_active_span_context
#' Pack the currently active span context into standard HTTP OpenTelemetry
#' headers
#'
#' The returned headers can be sent over HTTP, or set as environment
#' variables for subprocesses.
#'
#' @inheritParams get_active_span
#' @return A named character vector, with lowercase names. It might be an
#' empty vector, e.g. if tracing is disabled.
#'
#' @export
#' @seealso [extract_http_context()]
#' @examples
#' hdr <- otel::pack_http_context()
#' ctx <- otel::extract_http_context()
#' ctx$is_valid()
# safe start
pack_http_context <- function(tracer = NULL) {
tryCatch({ # safe
trc <- get_otel_tracer(tracer)
trc$get_active_span_context()$to_http_headers()
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
structure(character(), names = character()) # safe
}) # safe
}
# safe end
pack_http_context_safe <- pack_http_context
#' Extract a span context from HTTP headers received from a client
#'
#' The return value can be used as the `parent` option when starting
#' a span.
#'
#' @param headers A named list with one or two strings: `traceparent` is
#' mandatory, and `tracestate` is optional.
#' @inheritParams get_active_span
#'
#' @return And [otel_span_context] object.
#'
#' @export
#' @seealso [pack_http_context()]
#' @inherit pack_http_context examples
# safe start
extract_http_context <- function(headers, tracer = NULL) {
tryCatch({ # safe
trc <- get_otel_tracer(tracer)
trc$extract_http_context(headers)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
span_context_noop$new(NA_character_) # safe
}) # safe
}
# safe end
extract_http_context_safe <- extract_http_context
#' Start an OpenTelemetry span.
#'
#' @description
#' Creates a new OpenTelemetry span and starts it, without activating it.
#'
#' Usually you want [start_local_active_span()] instead of `start_span`.
#' [start_local_active_span()] also activates the span for the caller frame,
#' and ends the span when the caller frame exits.
#'
#' @details
#' Only use `start_span()` is you need to manage the span's activation
#' manually. Otherwise use [start_local_active_span()].
#'
#' You must end the span by calling [end_span()]. Alternatively you
#' can also end it with [local_active_span()] or [with_active_span()] by
#' setting `end_on_exit = TRUE`.
#'
#' It is a good idea to end spans created with `start_span()` in an
#' [base::on.exit()] call.
#'
#' @param name `r doc_arg()[["span-name"]]`
#' @param attributes `r doc_arg()[["attributes"]]`
#' @param links `r doc_arg()[["links"]]`
#' @param options `r doc_arg()[["span-options"]]`
#' @param ... Additional arguments are passed to the `start_span()` method
#' of the tracer.
#' @param tracer A tracer object or the name of the tracer to use, see
#' [get_tracer()]. If `NULL` then [default_tracer_name()] is used.
#'
#' @return An OpenTelemetry span ([otel_span]).
#'
#' @family OpenTelemetry trace API
#' @export
#' @examples
#' fun <- function() {
#' # start span, do not activate
#' spn <- otel::start_span("myfun")
#' # do not leak resources
#' on.exit(otel::end_span(spn), add = TRUE)
#' myfun <- function() {
#' # activate span for this function
#' otel::local_active_span(spn)
#' # create child span
#' spn2 <- otel::start_local_active_span("myfun/2")
#' }
#'
#' myfun2 <- function() {
#' # activate span for this function
#' otel::local_active_span(spn)
#' # create child span
#' spn3 <- otel::start_local_active_span("myfun/3")
#' }
#' myfun()
#' myfun2()
#' end_span(spn)
#' }
#' fun()
# safe start
start_span <- function(
name = NULL,
attributes = NULL,
links = NULL,
options = NULL,
...,
tracer = NULL
) {
tryCatch({ # safe
if (!inherits(tracer, "otel_tracer")) {
tracer <- get_tracer(tracer)
}
invisible(tracer$start_span(name, attributes, links, options, ...))
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
span_noop$new() # safe
}) # safe
}
# safe end
start_span_safe <- start_span
#' End an OpenTelemetry span
#'
#' Spans created with [start_local_active_span()] end automatically by
#' default. You must end every other span manually, by calling `end_span`,
#' or using the `end_on_exit` argument of [local_active_span()] or
#' [with_active_span()].
#'
#'
#' @param span The span to end.
#' @param status_code Span status code to set before ending the span.
#' Possible values: `r paste(span_status_codes, collapse = ", ")`.
#' See [span_status_codes]. If `NULL`, the status is not changed.
#' @return Nothing.
#'
#' @inherit start_span examples
#' @family OpenTelemetry trace API
#'
#' @export
# safe start
end_span <- function(span, status_code = NULL) {
tryCatch({ # safe
identity(NULL)
span$end(status_code = status_code)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
invisible(NULL) # safe
}) # safe
}
# safe end
end_span_safe <- end_span
#' Start and activate a span
#'
#' @description
#' Creates, starts and activates an OpenTelemetry span.
#'
#' Usually you want this functions instead of [start_span()], which does
#' not activate the new span.
#'
#' @details
#' If `end_on_exit` is `TRUE` (the default), then it also ends the span
#' when the activation scope finishes.
#'
#' @param activation_scope The R scope to activate the span for. Defaults
#' to the caller frame.
#' @param end_on_exit Whether to also end the span when the activation scope
#' exits.
#' @inheritParams start_span
#'
#' @return The new OpenTelemetry span object (of class [otel_span]),
#' invisibly. See [otel_span] for information about the returned object.
#'
#' @family OpenTelemetry trace API
#' @export
#' @examples
#' fn1 <- function() {
#' otel::start_local_active_span("fn1")
#' fn2()
#' }
#' fn2 <- function() {
#' otel::start_local_active_span("fn2")
#' }
#' fn1()
# safe start
start_local_active_span <- function(
name = NULL,
attributes = NULL,
links = NULL,
options = NULL,
...,
tracer = NULL,
activation_scope = parent.frame(),
end_on_exit = TRUE
) {
tryCatch({ # safe
if (!inherits(tracer, "otel_tracer")) {
tracer <- get_tracer(tracer)
}
span <- tracer$start_span(name, attributes, links, options, ...)
span$activate(
activation_scope = activation_scope, end_on_exit = end_on_exit)
invisible(span)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
span_noop$new() # safe
}) # safe
}
# safe end
start_local_active_span_safe <- start_local_active_span
#' Check if tracing is active
#'
#' Checks whether OpenTelemetry tracing is active. This can be useful
#' to avoid unnecessary computation when tracing is inactive.
#'
#' It calls [get_tracer()] with `name` and then it calls the tracer's
#' `$is_enabled()` method.
#'
#' @param tracer Tracer object ([otel_tracer]). It can also be a tracer
#' name, the instrumentation scope, or `NULL` for determining the tracer
#' name automatically. Passed to [get_tracer()] if not a tracer object.
#' @return `TRUE` is OpenTelemetry tracing is active, `FALSE` otherwise.
#'
#' @export
#' @seealso '[Environment Variables]' needed to enable OpenTelemetry tracing.
#' @family OpenTelemetry trace API
#' @examples
#' fun <- function() {
#' if (otel::is_tracing_enabled()) {
#' xattr <- calculate_some_extra_attributes()
#' otel::start_local_active_span("fun", attributes = xattr)
#' }
#' # ...
#' }
# safe start
is_tracing_enabled <- function(tracer = NULL) {
tryCatch({ # safe
if (!inherits(tracer, "otel_tracer")) {
tracer <- get_tracer(tracer)
}
tracer$is_enabled()
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
FALSE # safe
}) # safe
}
# safe end
is_tracing_enabled_safe <- is_tracing_enabled
#' Check whether OpenTelemetry logging is active
#'
#' This is useful for avoiding computation when logging is inactive.
#'
#' It calls [get_logger()] with `name` and then it calls the logger's
#' `$is_enabled()` method.
#'
#' @param severity Check if logs are emitted at this severity level.
#' @param logger Logger object ([otel_logger]), or a logger name, the
#' instrumentation scope, to pass to [get_logger()].
#' @return `TRUE` is OpenTelemetry logging is active, `FALSE` otherwise.
#'
#' @export
#' @seealso '[Environment Variables]' needed to enable OpenTelemetry logging.
#' @family OpenTelemetry logs API
#' @examples
#' fun <- function() {
#' if (otel::is_logging_enabled()) {
#' xattr <- calculate_some_extra_attributes()
#' otel::log("Starting fun", attributes = xattr)
#' }
#' # ...
#' }
# safe start
is_logging_enabled <- function(severity = "info", logger = NULL) {
tryCatch({ # safe
if (!inherits(logger, "otel_tracer")) {
logger <- get_logger(logger)
}
logger$is_enabled(severity)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
FALSE # safe
}) # safe
}
# safe end
is_logging_enabled_safe <- is_logging_enabled
#' Check whether OpenTelemetry metrics collection is active
#'
#' This is useful for avoiding computation when metrics collection is inactive.
#'
#' It calls [get_meter()] with `name` and then it calls the meter's
#' `$is_enabled()` method.
#'
#' @param meter Meter object ([otel_meter]), or a meter name, the
#' instrumentation scope, to pass to [get_meter()].
#' @return `TRUE` is OpenTelemetry metrics collection is active,
#' `FALSE` otherwise.
#'
#' @export
#' @seealso '[Environment Variables]' needed to enable OpenTelemetry recording.
#' @family OpenTelemetry metrics API
#' @examples
#' fun <- function() {
#' if (otel::is_measuring_enabled()) {
#' xattr <- calculate_some_extra_attributes()
#' otel::counter_add("sessions", 1, attributes = xattr)
#' }
#' # ...
#' }
# safe start
is_measuring_enabled <- function(meter = NULL) {
tryCatch({ # safe
if (!inherits(meter, "otel_meter")) {
meter <- get_meter(meter)
}
meter$is_enabled()
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
FALSE # safe
}) # safe
}
# safe end
is_measuring_enabled_safe <- is_measuring_enabled
#' Log an OpenTelemetry log message
#'
#' @param msg Log message.
#' @param severity Log severity, a string, one of
#' `r md_log_severity_levels`.
#' @param ... Additional arguments are passed to the `$log()` method of
#' the logger.
#' @param logger Logger to use. If not an OpenTelemetry logger object
#' ([otel_logger]), then it passed to [get_logger()] to get a logger.
#' @return The logger, invisibly.
#'
#' @export
#' @seealso '[Environment Variables]' needed to enable OpenTelemetry logging.
#' @family OpenTelemetry logs API
#' @examples
#' host <- "my.db.host"
#' port <- 6667
#' otel::log("Connecting to database at {host}:{port}")
# safe start
log <- function(
msg,
...,
severity = "info",
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, severity, ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_safe <- log
#' @details `log_trace()` is the same as `log()` with `severity_level`
#' "trace".
#' @rdname log
#' @export
# safe start
log_trace <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "trace", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_trace_safe <- log_trace
#' @details `log_debug()` is the same as `log()` with `severity_level`
#' "debug".
#' @rdname log
#' @export
# safe start
log_debug <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "debug", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_debug_safe <- log_debug
#' @details `log_info()` is the same as `log()` with `severity_level`
#' "info".
#' @rdname log
#' @export
# safe start
log_info <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "info", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_info_safe <- log_info
#' @details `log_warn()` is the same as `log()` with `severity_level`
#' "warn".
#' @rdname log
#' @export
# safe start
log_warn <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "warn", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_warn_safe <- log_warn
#' @details `log_error)` is the same as `log()` with `severity_level`
#' "error".
#' @rdname log
#' @export
# safe start
log_error <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "error", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_error_safe <- log_error
#' @details `log_fatal()` is the same as `log()` with `severity_level`
#' "fatal".
#' @rdname log
#' @export
# safe start
log_fatal <- function(
msg,
...,
logger = NULL
) {
tryCatch({ # safe
if (!inherits(logger, "otel_logger")) {
logger <- get_logger()
}
logger$log(msg, "fatal", ...)
invisible(logger)
}, error = function(err) { # safe
errmsg("OpenTelemetry error: ", conditionMessage(err)) # safe
logger_noop$new() # safe
}) # safe
}
# safe end
log_fatal_safe <- log_fatal
#' Increase an OpenTelemetry counter
#'
#' @param name Name of the counter.
#' @param value Value to add to the counter, defaults to 1.
#' @param attributes Additional attributes to add.
#' @param context Span context. If missing the active context is used,
#' if any.
#' @param meter Meter object ([otel_meter]). Otherwise it is passed to
#' [get_meter()] to get a meter.
#'
#' @return The counter object ([otel_counter]), invisibly.
#'
#' @seealso '[Environment Variables]' needed to enable OpenTelemetry recording.
#' @family OpenTelemetry metrics instruments
#' @family OpenTelemetry metrics API
#' @export
#' @examples
#' otel::counter_add("total-session-count", 1)
# safe start
counter_add <- function(