1+ <?php
2+
3+ namespace Overtrue \LaravelOpenTelemetry \Support ;
4+
5+ use Illuminate \Contracts \Foundation \Application ;
6+ use Illuminate \Support \Facades \Log ;
7+ use OpenTelemetry \API \Metrics \GaugeInterface ;
8+ use OpenTelemetry \API \Metrics \HistogramInterface ;
9+ use OpenTelemetry \API \Metrics \MeterInterface ;
10+ use OpenTelemetry \API \Metrics \Noop \NoopMeter ;
11+ use OpenTelemetry \API \Metrics \CounterInterface ;
12+ use OpenTelemetry \API \Metrics \ObservableGaugeInterface ;
13+ use Throwable ;
14+
15+ class Metric
16+ {
17+ private static ?bool $ enabled = null ;
18+
19+ public function __construct (protected Application $ app )
20+ {
21+ }
22+
23+
24+ // ======================= Enable/Disable Management =======================
25+
26+ public function enable (): void
27+ {
28+ self ::$ enabled = true ;
29+ }
30+
31+ public function disable (): void
32+ {
33+ self ::$ enabled = false ;
34+ }
35+
36+ public function isEnabled (): bool
37+ {
38+ if (self ::$ enabled === null ) {
39+ return config ('otel.enabled ' , true );
40+ }
41+
42+ return self ::$ enabled ;
43+ }
44+
45+
46+ // ======================= Core OpenTelemetry API =======================
47+
48+ /**
49+ * Get the meter instance
50+ */
51+ public function meter (): MeterInterface
52+ {
53+ if (!$ this ->isEnabled ()) {
54+ return new NoopMeter ;
55+ }
56+
57+ try {
58+ return $ this ->app ->get (MeterInterface::class);
59+ } catch (Throwable $ e ) {
60+ Log::error ('[laravel-open-telemetry] Meter not found ' , [
61+ 'error ' => $ e ->getMessage (),
62+ 'line ' => $ e ->getLine (),
63+ 'file ' => $ e ->getFile (),
64+ ]);
65+
66+ return new NoopMeter ;
67+ }
68+ }
69+
70+ public function createCounter (string $ name , ?string $ unit = null ,
71+ ?string $ description = null , array $ advisory = []): CounterInterface
72+ {
73+ return $ this ->meter ()->createCounter ($ name , $ unit , $ description , $ advisory );
74+ }
75+
76+ public function createHistogram (string $ name , ?string $ unit = null ,
77+ ?string $ description = null , array $ advisory = []): HistogramInterface
78+ {
79+ return $ this ->meter ()->createHistogram ($ name , $ unit , $ description , $ advisory );
80+ }
81+
82+ public function createGauge (string $ name , ?string $ unit = null ,
83+ ?string $ description = null , array $ advisory = []): GaugeInterface
84+ {
85+ return $ this ->meter ()->createGauge ($ name , $ unit , $ description , $ advisory );
86+ }
87+
88+ public function createObservableGauge (string $ name , ?string $ unit = null ,
89+ ?string $ description = null , array |callable $ advisory = [], callable ...$ callbacks ): ObservableGaugeInterface
90+ {
91+ return $ this ->meter ()->createObservableGauge ($ name , $ unit , $ description , $ advisory , $ callbacks );
92+ }
93+
94+
95+ }
0 commit comments