Skip to content
This repository was archived by the owner on Dec 5, 2025. It is now read-only.

Commit 615b7cb

Browse files
committed
feat: db sql
1 parent 650d51f commit 615b7cb

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/Watchers/AuthenticateWatcher.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,18 @@
66

77
use Illuminate\Auth\Events\Login;
88
use Illuminate\Contracts\Foundation\Application;
9-
use Illuminate\Support\Facades\Event;
109
use OpenTelemetry\API\Trace\Span;
11-
use OpenTelemetry\SemConv\TraceAttributes;
1210
use Overtrue\LaravelOpenTelemetry\Facades\Measure;
1311

1412
class AuthenticateWatcher implements Watcher
1513
{
1614
public function register(Application $app): void
1715
{
18-
Event::listen(Login::class, function (Login $event) {
16+
$app['events']->listen(Login::class, function (Login $event) {
1917
$span = Measure::activeSpan();
2018

2119
if ($span instanceof Span) {
22-
$span->setAttribute(TraceAttributes::DB_USER, $event->user->getKey());
20+
$span->setAttribute('user.id', $event->user->getKey());
2321
}
2422
});
2523
}

src/Watchers/DatabaseQueryWatcher.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,45 @@ public function recordQuery(QueryExecuted $query): void
2929
$operationName = null;
3030
}
3131

32-
$span = Measure::span(sprintf('[DB] %s', $operationName))
32+
$table = $this->getTableName($query->sql);
33+
$rawSql = $query->connection->getQueryGrammar()?->substituteBindingsIntoRawSql($query->sql, $query->bindings);
34+
35+
$spanName = sprintf('[DB][%s][%s] %s', $operationName, $table, Str::limit($rawSql, 50));
36+
37+
$span = Measure::span($spanName)
3338
->setSpanKind(SpanKind::KIND_CLIENT)
3439
->setStartTimestamp($this->getEventStartTimestampNs($query->time))
3540
->start();
3641

3742
$span->setAttributes([
43+
'db.sql.raw' => $rawSql,
3844
TraceAttributes::DB_SYSTEM => $query->connection->getDriverName(),
3945
TraceAttributes::DB_NAME => $query->connection->getDatabaseName(),
4046
TraceAttributes::DB_OPERATION => $operationName,
4147
TraceAttributes::DB_USER => $query->connection->getConfig('username'),
4248
TraceAttributes::DB_STATEMENT => $query->sql,
49+
TraceAttributes::DB_SQL_TABLE => $table,
4350
]);
4451

4552
$span->end();
4653
}
54+
55+
protected function getTableName(string $sql): string
56+
{
57+
// update
58+
if (preg_match('/update\s+`?(\w+)`?/i', $sql, $matches)) {
59+
return $matches[1];
60+
}
61+
62+
// insert
63+
if (preg_match('/insert\s+into\s+`?(\w+)`?/i', $sql, $matches)) {
64+
return $matches[1];
65+
}
66+
67+
if (preg_match('/from\s+`?(\w+)`?/i', $sql, $matches)) {
68+
return $matches[1];
69+
}
70+
71+
return 'unknown';
72+
}
4773
}

0 commit comments

Comments
 (0)