如何从雄辩的多个连接中记录每个查询(外部Laravel)

发布于 2025-01-22 20:12:36 字数 1912 浏览 0 评论 0原文

我在应用程序,一个SQLServ和另一个MySQL中使用多个数据库连接。我想依次从两个服务器上调试每个查询。因此,请使用Manager :: getQueryLog()我需要使用event :: Listen。我使用Slimframework,带有PHP-DI。

index.php

// Create container & database
$containerBuilder = new DI\ContainerBuilder(App\Lib\Container::class);
$containerBuilder->useAnnotations(false);
$containerBuilder->addDefinitions(__DIR__ . '/../config/settings.php');
$container = $containerBuilder->build();
$app = \DI\Bridge\Slim\Bridge::create($container);

// Register database
$capsule = new \Illuminate\Database\Capsule\Manager();
foreach ($container->get('database') as $con => $config) {
    $capsule->addConnection($config, $con);
}

$capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher()); 
// Throw error A facade root has not been set. pretty sure it 
// was because i use it outside laravel

$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);

// Listen
DB::listen(function($query) {
    Log::info(
       $query->sql,
       $query->bindings,
       $query->time
    );
});

app \ lib \ container :: class

namespace App\Lib;

use DI\Container as DIContainer;

class Container extends DIContainer
{
    public function __get($key)
    {
        if ($this->has($key)) {
            return $this->get($key);
        }
    }
}

如何从多个连接中记录每个查询,但是按顺序排序,如下所示。

select * from tableInMySQL limit 0,10;
select TOP 10 * from [tableInMSSQL];
update tableInMySQL set field='value';

编辑

就像我之前说过的,我使用 slimframework,带有php-di
因此,我整体上都不使用 laravel 。 (不使用服务提供商)

db ::听听投掷错误,$ capsule-> getConnection('con_name') - > getEventDisPatcher() return> return

I use multiple database connections in my app, one SQLServ, and another MySQL. I want to debug every query from both servers sequentially. therefore rather using Manager::getQueryLog() i need to use Event::listen. I use SlimFramework, with PHP-DI.

index.php

// Create container & database
$containerBuilder = new DI\ContainerBuilder(App\Lib\Container::class);
$containerBuilder->useAnnotations(false);
$containerBuilder->addDefinitions(__DIR__ . '/../config/settings.php');
$container = $containerBuilder->build();
$app = \DI\Bridge\Slim\Bridge::create($container);

// Register database
$capsule = new \Illuminate\Database\Capsule\Manager();
foreach ($container->get('database') as $con => $config) {
    $capsule->addConnection($config, $con);
}

$capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher()); 
// Throw error A facade root has not been set. pretty sure it 
// was because i use it outside laravel

$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);

// Listen
DB::listen(function($query) {
    Log::info(
       $query->sql,
       $query->bindings,
       $query->time
    );
});

App\Lib\Container::class

namespace App\Lib;

use DI\Container as DIContainer;

class Container extends DIContainer
{
    public function __get($key)
    {
        if ($this->has($key)) {
            return $this->get($key);
        }
    }
}

How to log every query from multiple connections, but in sequential order, something like the following.

select * from tableInMySQL limit 0,10;
select TOP 10 * from [tableInMSSQL];
update tableInMySQL set field='value';

EDIT

like I said earlier, I use SlimFramework, with PHP-DI.
So, I'm not use LARAVEL as a whole. (not using service provider)

the DB::listen throw error, $capsule->getConnection('con_name')->getEventDispatcher() return null

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

吝吻 2025-01-29 20:12:37

要在顺序顺序中记录多个DB连接的查询,我们需要EnableQueryLog首先,对单独的Logger进行了配置。

$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);

$capsule->connection('<MySqlConnectionName>')->enableQueryLog();
$capsule->connection('<SqlServerConnectionName>')->enableQueryLog();
//$capsule->connection('<MongoConnectionName>')->enableQueryLog(); 

// Listen
\Illuminate\Database\Capsule\Manager::listen(function($query) {
    if($query->connectionName == 'mysql') {
        $mysqlLogger->debug('mysql', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    } elseif($query->connectionName == 'sqlserver') {
        $sqlServerLogger->debug('mongodb', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    } /*elseif($query->connectionName == 'mongodb') {
        $mongoDbLogger->debug('mongodb', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    }*/
});

To log queries of multiple db connections in sequential order, we'll need to enableQueryLog first, have separate Logger configured.

$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);

$capsule->connection('<MySqlConnectionName>')->enableQueryLog();
$capsule->connection('<SqlServerConnectionName>')->enableQueryLog();
//$capsule->connection('<MongoConnectionName>')->enableQueryLog(); 

// Listen
\Illuminate\Database\Capsule\Manager::listen(function($query) {
    if($query->connectionName == 'mysql') {
        $mysqlLogger->debug('mysql', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    } elseif($query->connectionName == 'sqlserver') {
        $sqlServerLogger->debug('mongodb', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    } /*elseif($query->connectionName == 'mongodb') {
        $mongoDbLogger->debug('mongodb', [
            'query' => $query->sql,
            'bindings' => $query->bindings
        ]);
    }*/
});
给妤﹃绝世温柔 2025-01-29 20:12:37

对于在这里登陆的任何人,我们都需要在每个连接上附加听众

sett.php

return [
    'maintenance' => false,
    'base_path'   => empty($_ENV['SUBDIR']) ? '' : '/' . $_ENV['SUBDIR'],
    'database'    => [
        'default'  => [ // sql server
            "driver"   => env('DB_MSSQL_DRIVER'),
            "host"     => env('DB_MSSQL_HOST'),
            "port"     => env('DB_MSSQL_PORT'),
            "database" => env('DB_MSSQL_DATABASE'),
            "username" => env('DB_MSSQL_USERNAME'),
            'password' => env('DB_MSSQL_PASSWORD'),
        ],
        'mysql'  => [
            "driver"   => env('DB_MYSQL_DRIVER'),
            "host"     => env('DB_MYSQL_HOST'),
            "port"     => env('DB_MYSQL_PORT'),
            "database" => env('DB_MYSQL_DATABASE'),
            "username" => env('DB_MYSQL_USERNAME'),
            'password' => env('DB_MYSQL_PASSWORD'),
        ],
    ],
    "template"    => [
        "view"  => __DIR__ . "/../module",
        "cache" => __DIR__ . "/../cache",
    ],
];

index.php

// build PHP-DI container 
$container = $containerBuilder->build();

//register database
$capsule = new \Illuminate\Database\Capsule\Manager();
foreach ($container->get('database') as $con => $config) {
    $capsule->addConnection($config, $con);
    $capsule->getConnection($con)->setEventDispatcher(new \Illuminate\Events\Dispatcher());
    $capsule->getConnection($con)->listen(function ($q) {
        // or use logger
        $d = str_replace('?', "'?'", "[$q->connectionName]\t" . $q->sql);
        $d = vsprintf(str_replace('?', '%s', $d), $q->bindings);
        file_put_contents(__DIR__ . '/../log/sql.log', $d . PHP_EOL, FILE_APPEND);
    });

}
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);

for anyone who's landing here, we need to attach listener on every connection

setting.php

return [
    'maintenance' => false,
    'base_path'   => empty($_ENV['SUBDIR']) ? '' : '/' . $_ENV['SUBDIR'],
    'database'    => [
        'default'  => [ // sql server
            "driver"   => env('DB_MSSQL_DRIVER'),
            "host"     => env('DB_MSSQL_HOST'),
            "port"     => env('DB_MSSQL_PORT'),
            "database" => env('DB_MSSQL_DATABASE'),
            "username" => env('DB_MSSQL_USERNAME'),
            'password' => env('DB_MSSQL_PASSWORD'),
        ],
        'mysql'  => [
            "driver"   => env('DB_MYSQL_DRIVER'),
            "host"     => env('DB_MYSQL_HOST'),
            "port"     => env('DB_MYSQL_PORT'),
            "database" => env('DB_MYSQL_DATABASE'),
            "username" => env('DB_MYSQL_USERNAME'),
            'password' => env('DB_MYSQL_PASSWORD'),
        ],
    ],
    "template"    => [
        "view"  => __DIR__ . "/../module",
        "cache" => __DIR__ . "/../cache",
    ],
];

index.php

// build PHP-DI container 
$container = $containerBuilder->build();

//register database
$capsule = new \Illuminate\Database\Capsule\Manager();
foreach ($container->get('database') as $con => $config) {
    $capsule->addConnection($config, $con);
    $capsule->getConnection($con)->setEventDispatcher(new \Illuminate\Events\Dispatcher());
    $capsule->getConnection($con)->listen(function ($q) {
        // or use logger
        $d = str_replace('?', "'?'", "[$q->connectionName]\t" . $q->sql);
        $d = vsprintf(str_replace('?', '%s', $d), $q->bindings);
        file_put_contents(__DIR__ . '/../log/sql.log', $d . PHP_EOL, FILE_APPEND);
    });

}
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->set('connection', $capsule);
皇甫轩 2025-01-29 20:12:37

您应该在boot() app/app/provister/appserviceprovider.php 的功能中编写db ::收听事件。

DB::listen(function ($query) {
    $qry = str_replace(['?'], ['\'%s\''], $query->sql);
    $qry = vsprintf($qry, $query->bindings);
    Log::info('query_log', [
        'query' => $qry,
        'bindings' => $query->bindings,
    ]);
});

you should write DB::listen event in boot() function of app/Providers/AppServiceProvider.php

DB::listen(function ($query) {
    $qry = str_replace(['?'], ['\'%s\''], $query->sql);
    $qry = vsprintf($qry, $query->bindings);
    Log::info('query_log', [
        'query' => $qry,
        'bindings' => $query->bindings,
    ]);
});
风吹雪碎 2025-01-29 20:12:37

请将其添加到提供商/AppServiceProvider.php文件中,然后在Laravel日志文件中检查它们

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function register() {
    Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
        Log::debug($query->sql . ' - ' . serialize($query->bindings));
    });
}

Please add this to the Providers/AppServiceProvider.php file and check them in the laravel log file

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function register() {
    Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
        Log::debug($query->sql . ' - ' . serialize($query->bindings));
    });
}
吾家有女初长成 2025-01-29 20:12:37

我将那里的代码放入appserviceprovider.php上的boot()方法中,

       if (\App::environment('local')) {
            \DB::listen(function ($query) {
                \Log::info($query->sql);
            });
        }

因此,日志只能为开发环境编写。

I put there code into boot() method on AppServiceProvider.php

       if (\App::environment('local')) {
            \DB::listen(function ($query) {
                \Log::info($query->sql);
            });
        }

So, the log will be write only for development environment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文