## Getting Started
### Minimal Setup
1. **Install the package**:
```bash
composer require babymarkt/influxdb2-bundle
Ensure the bundle is enabled in config/bundles.php:
Babymarkt\Symfony\Influxdb2Bundle\BabymarktInfluxdb2Bundle::class => ['all' => true],
Configure InfluxDB2:
Add minimal config to config/packages/babymarkt_influxdb2.yaml:
babymarkt_influxdb2:
client:
url: https://your-influxdb-url:8086
token: your-token-here
org: your-org
bucket: your-bucket
First Use Case:
Inject the default WriteApi into a service to write metrics:
use InfluxDB2\WriteApi;
class MetricsLogger {
public function __construct(private WriteApi $writeApi) {}
public function log(string $measurement, array $tags, array $fields) {
$point = \InfluxDB2\Point::measurement($measurement)
->addTags($tags)
->addFields($fields)
->timestamp(time(), \InfluxDB2\WritePrecision::MS);
$this->writeApi->writePoint($point);
}
}
Use environment variables for sensitive data (e.g., token) and override config per environment:
# config/packages/babymarkt_influxdb2.yaml
babymarkt_influxdb2:
client:
url: '%env(INFLUXDB_URL)%'
token: '%env(INFLUXDB_TOKEN)%'
org: '%env(INFLUXDB_ORG)%'
bucket: '%env(INFLUXDB_BUCKET)%'
Define multiple connections (e.g., production, staging) and inject specific APIs:
babymarkt_influxdb2:
client:
connections:
production:
url: https://prod-influxdb:8086
token: %env(INFLUXDB_PROD_TOKEN)%
org: prod-org
bucket: prod-bucket
staging:
url: https://staging-influxdb:8086
token: %env(INFLUXDB_STAGING_TOKEN)%
org: staging-org
bucket: staging-bucket
Inject via service definition:
services:
App\Service\StagingMetricsLogger:
arguments:
- '@babymarkt_influxdb.staging_write_api'
Use QueryApi to fetch data with Flux queries:
use InfluxDB2\QueryApi;
class AnalyticsService {
public function __construct(private QueryApi $queryApi) {}
public function getUserActivity(string $userId, string $timeRange) {
$query = sprintf(
'from(bucket: "your-bucket")
|> range(%s)
|> filter(fn: (r) => r._measurement == "user_activity" and r.user_id == "%s")',
$timeRange,
$userId
);
$result = $this->queryApi->query($query);
return $result->records();
}
}
Configure batching for high-throughput writes:
babymarkt_influxdb2:
api:
write:
option_sets:
high_throughput:
options:
write_type: BATCHING
batch_size: 10000
retry_interval: 5000
max_retries: 5
Inject the custom option set:
services:
App\Service\HighVolumeLogger:
arguments:
- '@babymarkt_influxdb.high_throughput_write_api'
Set default tags per connection to avoid repetition:
babymarkt_influxdb2:
client:
connections:
default:
tags:
environment: production
application: your-app
Use Symfony’s Messenger to queue writes for async processing:
use Symfony\Component\Messenger\MessageBusInterface;
class AsyncMetricsLogger {
public function __construct(
private WriteApi $writeApi,
private MessageBusInterface $bus
) {}
public function logAsync(string $measurement, array $data) {
$this->bus->dispatch(new LogMetricsMessage($measurement, $data));
}
}
Token Security:
ParameterBag..env files to version control.Connection Timeouts:
timeout: 10 may be too short for slow networks. Increase if writes fail intermittently:
babymarkt_influxdb2:
client:
connections:
default:
timeout: 30
SSL Verification:
verifySSL (e.g., for self-signed certs) is insecure. Use proper certificates instead:
babymarkt_influxdb2:
client:
connections:
default:
verifySSL: false # Avoid this in production!
Query Timeouts:
timeout in the query:
$query = '... | range(...)';
$result = $this->queryApi->query($query, ['timeout' => '1m']);
Bucket/Org Mismatch:
org and bucket in config match the InfluxDB instance. Errors like 404 Not Found often indicate this.Precision Handling:
precision: 'ns' may cause issues with some time libraries. Use 's' (seconds) for simplicity:
babymarkt_influxdb2:
client:
connections:
default:
precision: 's'
Enable Debug Logging:
babymarkt_influxdb2:
client:
connections:
default:
debug: true
logFile: '%kernel.logs_dir%/influxdb.log'
Check logs for HTTP request/response details.
Ping Command:
Use the babymarkt_influxdb:ping command to verify connectivity:
php bin/console babymarkt_influxdb:ping -c=default
Ready Service: Check InfluxDB instance health programmatically:
$readyService = $client->createService(\InfluxDB2\Service\ReadyService::class);
$status = $readyService->getReady()->getStatus(); // "ready" or "not_ready"
Query Validation: Test Flux queries in the InfluxDB UI first to catch syntax errors early.
Custom Services: Extend the bundle by creating your own services that wrap InfluxDB2 APIs:
namespace App\Service;
use InfluxDB2\Client;
use InfluxDB2\Service\BucketsService;
class BucketManager {
public function __construct(private Client $client) {}
public function createBucket(string $name, string $org, int $duration = 0) {
$bucketsService = $this->client->createService(BucketsService::class);
return $bucketsService->createBucket($name, $org, $duration);
}
}
Event Listeners: Listen for InfluxDB events (e.g., write failures) using Symfony’s event system:
namespace App\EventListener;
use InfluxDB2\WriteApi;
use Psr\Log\LoggerInterface;
class WriteFailureListener {
public function __construct(private LoggerInterface $logger) {}
public function onWriteFailure(WriteApi $writeApi, \Throwable $exception) {
$this->logger->error('InfluxDB write failed', [
'exception' => $exception->getMessage(),
]);
}
}
Console Command Extensions:
Extend existing commands (e.g., babymarkt_influxdb:buckets:list) by overriding their logic:
namespace App\Command;
use Babymarkt\Symfony\Influxdb2Bundle\Command\BucketsListCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CustomBuckets
How can I help you explore Laravel packages today?