File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change @@ -15,6 +15,11 @@ class Logger
1515 'logOwl ' ,
1616 ];
1717
18+ /**
19+ * @var float|null
20+ */
21+ protected $ samplePercent = null ;
22+
1823 /**
1924 * @var Adapter
2025 */
@@ -51,6 +56,12 @@ public function addLog(Log $log): int
5156 throw new Exception ('Log is not ready to be pushed. ' );
5257 }
5358
59+ if (! is_null ($ this ->samplePercent )) {
60+ if (rand (0 , 100 ) <= $ this ->samplePercent ) {
61+ return 0 ;
62+ }
63+ }
64+
5465 if ($ this ->adapter ->validate ($ log )) {
5566 // Push log
5667 return $ this ->adapter ->push ($ log );
@@ -85,4 +96,27 @@ public static function hasProvider(string $providerName): bool
8596
8697 return false ;
8798 }
99+
100+ /**
101+ * Return only a sample of the logs from this logger
102+ *
103+ * @param float $sample Total percentage of issues to use with 100% being 1
104+ * @return self
105+ */
106+ public function setSample (float $ sample ): self
107+ {
108+ $ this ->samplePercent = $ sample * 100 ;
109+
110+ return $ this ;
111+ }
112+
113+ /**
114+ * Get the current sample value as a percentage
115+ *
116+ * @return float|null
117+ */
118+ public function getSample (): float |null
119+ {
120+ return $ this ->samplePercent ;
121+ }
88122}
Original file line number Diff line number Diff line change @@ -58,4 +58,32 @@ public function testAdapter(): void
5858 $ response = $ logger ->addLog ($ this ->log );
5959 $ this ->assertEquals ($ this ->expected , $ response );
6060 }
61+
62+ /**
63+ * @throws \Throwable
64+ */
65+ public function testSampler (): void
66+ {
67+ if (empty ($ this ->log ) || empty ($ this ->adapter )) {
68+ throw new \Exception ('Log or adapter not set ' );
69+ }
70+
71+ $ logger = new Logger ($ this ->adapter );
72+ $ logger ->setSample (0.1 );
73+
74+ $ results = [];
75+ $ zeroCount = 0 ;
76+
77+ for ($ x = 0 ; $ x <= 100 ; $ x ++) {
78+ $ result = $ logger ->addLog ($ this ->log );
79+ $ results [] = $ result ;
80+ if ($ result === 0 ) {
81+ $ zeroCount ++;
82+ }
83+ }
84+
85+ $ zeroPercentage = ($ zeroCount / count ($ results )) * 100 ;
86+
87+ $ this ->assertLessThan (20 , $ zeroPercentage );
88+ }
6189}
You can’t perform that action at this time.
0 commit comments