Skip to content

Commit 0343fcc

Browse files
committed
Feat: add logging for debug
1 parent 8326fe7 commit 0343fcc

File tree

4 files changed

+81
-17
lines changed

4 files changed

+81
-17
lines changed

app/Commands/RunCommand.php

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
namespace Zoon\PyroSpy\Commands;
44

55
use InvalidArgumentException;
6+
use Monolog\Formatter\JsonFormatter;
7+
use Monolog\Handler\StreamHandler;
8+
use Monolog\Level;
9+
use Monolog\Logger;
610
use Symfony\Component\Console\Command\Command;
711
use Symfony\Component\Console\Input\InputDefinition;
812
use Symfony\Component\Console\Input\InputInterface;
@@ -41,7 +45,7 @@ protected function configure(): void
4145
'memory',
4246
'm',
4347
InputOption::VALUE_NONE,
44-
'Process memory traces instead of CPU traces'
48+
'Process memory traces instead of CPU traces',
4549
),
4650
new InputOption(
4751
'app',
@@ -98,6 +102,13 @@ protected function configure(): void
98102
'Process trace and phpspy comments/tags with custom class. Can be class or folder with classes',
99103
[],
100104
),
105+
new InputOption(
106+
'sendTimeout',
107+
null,
108+
InputOption::VALUE_OPTIONAL,
109+
'TCP connect timeout in seconds',
110+
10.0,
111+
),
101112
]))
102113
;
103114
}
@@ -134,6 +145,31 @@ protected function execute(InputInterface $input, OutputInterface $output): int
134145
throw new InvalidArgumentException('sendSampleFutureLimit must be positive value');
135146
}
136147

148+
$sendTimeout = (float) $input->getOption('sendTimeout');
149+
if ($sendTimeout <= 0) {
150+
throw new InvalidArgumentException('sendTimeout must be positive value');
151+
}
152+
153+
$verbosity = $output->getVerbosity();
154+
$logLevel = match ($verbosity) {
155+
OutputInterface::VERBOSITY_SILENT => Level::Emergency,
156+
OutputInterface::VERBOSITY_QUIET => Level::Alert,
157+
OutputInterface::VERBOSITY_NORMAL => Level::Error,
158+
OutputInterface::VERBOSITY_VERBOSE => Level::Warning,
159+
OutputInterface::VERBOSITY_VERY_VERBOSE => Level::Info,
160+
OutputInterface::VERBOSITY_DEBUG => Level::Debug,
161+
};
162+
$handler = new StreamHandler(STDERR, $logLevel);
163+
$formatter = new \Monolog\Formatter\LineFormatter(
164+
ignoreEmptyContextAndExtra: true,
165+
);
166+
$formatter->includeStacktraces(
167+
true,
168+
static fn(string $line): string => $logLevel->toRFC5424Level() >= Level::Notice->toRFC5424Level() ? '' : $line,
169+
);
170+
$handler->setFormatter($formatter);
171+
$logger = new Logger('pyrospy', [$handler]);
172+
137173
$pyroscopeAuthToken = (string) $input->getOption('pyroscopeAuthToken');
138174

139175
$tags = [];
@@ -170,11 +206,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int
170206
$tags,
171207
$pyroscopeAuthToken,
172208
SenderUnitsEnum::Bytes,
173-
SenderAggregationEnum::Average
209+
SenderAggregationEnum::Average,
210+
sendTimeout: $sendTimeout,
211+
logger: $logger,
174212
);
175213
} else {
176214
$aggregator = new CpuTraceAggregator();
177-
$sender = new SampleSender($pyroscope, $app, $rateHz, $tags, $pyroscopeAuthToken);
215+
$sender = new SampleSender(
216+
$pyroscope,
217+
$app,
218+
$rateHz,
219+
$tags,
220+
$pyroscopeAuthToken,
221+
logger: $logger,
222+
sendTimeout: $sendTimeout,
223+
);
178224
}
179225

180226
$processor = new Processor(
@@ -185,8 +231,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
185231
array_values(array_filter($plugins)),
186232
$sendSampleFutureLimit,
187233
$concurrentRequestLimit,
234+
$logger,
188235
);
236+
$logger->info('pyrospy started');
189237
$processor->process();
238+
$logger->info('pyrospy shutdown');
190239
return Command::SUCCESS;
191240
}
192241

app/Processor.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
use Amp\Pipeline\Queue;
88
use Generator;
99
use InvalidArgumentException;
10+
use Psr\Log\NullLogger;
1011
use Throwable;
1112
use Zoon\PyroSpy\Plugins\PluginInterface;
13+
use Psr\Log\LoggerInterface;
1214

1315
use function Amp\async;
1416
use function Amp\ByteStream\getStdin;
@@ -42,6 +44,7 @@ public function __construct(
4244
private readonly array $plugins,
4345
int $sendSampleFutureLimit,
4446
private readonly int $concurrentRequestLimit,
47+
private readonly LoggerInterface $logger = new NullLogger(),
4548
private ?\Amp\ByteStream\ReadableStream $dataReader = null,
4649
) {
4750
if ($this->dataReader === null) {
@@ -88,11 +91,7 @@ private function runProducer(): Future
8891
$tracePrepared = self::prepareTrace($trace);
8992
self::checkTrace($tracePrepared);
9093
} catch (Throwable $e) {
91-
echo $e->getMessage() . PHP_EOL;
92-
/**
93-
* @psalm-suppress ForbiddenCode
94-
*/
95-
var_dump($trace);
94+
$this->logger->error($e->getMessage());
9695
continue;
9796
}
9897

app/SampleSender.php

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use Amp\Http\Client\HttpClient;
66
use Amp\Http\Client\HttpClientBuilder;
77
use Amp\Http\Client\Request;
8+
use Psr\Log\LoggerInterface;
9+
use Psr\Log\NullLogger;
810

911
/**
1012
* @psalm-import-type TagsArray from Sample
@@ -25,6 +27,8 @@ public function __construct(
2527
private readonly string $authToken = '',
2628
private readonly SenderUnitsEnum $units = SenderUnitsEnum::Samples,
2729
private readonly SenderAggregationEnum $aggregation = SenderAggregationEnum::Sum,
30+
private readonly float $sendTimeout = 5.,
31+
private readonly LoggerInterface $logger = new NullLogger(),
2832
) {
2933
$this->client = (new HttpClientBuilder())
3034
->retry(0)
@@ -35,27 +39,38 @@ public function __construct(
3539

3640
public function sendSample(Sample $sample): bool
3741
{
42+
$metricsStart = microtime(true);
43+
$metricsSize = 0;
44+
$metricStatus = 'error';
3845
$url = $this->getUrl($sample->tags, $sample->fromTs, $sample->toTs);
3946
try {
40-
$request = new Request($url, 'POST', self::prepareBody($sample->samples));
41-
$request->setTcpConnectTimeout(5 * 60);
42-
$request->setTlsHandshakeTimeout(5 * 60);
43-
$request->setTransferTimeout(60 * 60);
44-
$request->setInactivityTimeout(60 * 60);
47+
$body = self::prepareBody($sample->samples);
48+
$metricsSize = strlen($body);
49+
$request = new Request($url, 'POST', $body);
50+
$request->setTcpConnectTimeout($this->sendTimeout / 2.0);
51+
$request->setTransferTimeout($this->sendTimeout);
4552
$request->setHeader('Content-Type', 'text/html');
4653
if (!empty($this->authToken)) {
4754
$request->addHeader('Authorization', 'Bearer ' . $this->authToken);
4855
}
4956
$response = $this->client->request($request);
5057
if ($response->getStatus() === 200) {
58+
$metricStatus = 'success';
5159
return true;
5260
}
53-
printf("\nerror on request to url '%s', status code: %s", $url, $response->getStatus());
54-
61+
$this->logger->warning('Non-200 response from pyroscope', ['url' => $url, 'status' => $response->getStatus()]);
5562
return false;
5663
} catch (\Throwable $exception) {
57-
printf("\nerror on request to url '%s', exception message: %s", $url, $exception->getMessage());
64+
$this->logger->error('Exception sending sample to pyroscope', ['url' => $url, 'message' => $exception->getMessage()]);
5865
return false;
66+
} finally {
67+
$metricsDuration = round(microtime(true) - $metricsStart, 3);
68+
$this->logger->info("Sample sent: $metricStatus", [
69+
'duration' => $metricsDuration,
70+
'samples_count' => count($sample->samples),
71+
'size_bytes' => $metricsSize,
72+
'status' => $metricStatus,
73+
]);
5974
}
6075
}
6176

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
"amphp/http-client": "^5",
2121
"amphp/byte-stream": "^2.0",
2222
"symfony/console": "^5|^6|^7",
23-
"amphp/pipeline": "^1.0"
23+
"amphp/pipeline": "^1.0",
24+
"monolog/monolog": "^3.9"
2425
},
2526
"autoload": {
2627
"psr-4": {

0 commit comments

Comments
 (0)