caixingyue/laravel-star-log

这是一个增强Laravel日志格式的包。它可以注入请求ID、工匠ID、队列ID,并支持路由请求日志、HTTP客户端请求日志、SQL查询日志等增强功能。

v1.0.1 2024-09-10 10:21 UTC

This package is auto-updated.

Last update: 2024-09-10 10:24:23 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

这是一个增强Laravel日志格式的包。它可以注入请求ID、工匠ID、队列ID,并支持路由请求日志、HTTP客户端请求日志、SQL查询日志等增强功能。

安装

您可以通过composer安装此包

composer require caixingyue/laravel-star-log

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="star-log-config"

用法

日志格式配置

安装完成后,您需要在config/logging.php配置文件中添加新的channels信息。以下是一个常见参考示例,您可以根据需要修改配置。

use Caixingyue\LaravelStarLog\Formatter\StrengthenFormatter;

'channels' => [
    'star_daily' => [
        'driver' => 'daily',
        'formatter' => StrengthenFormatter::class,
        'formatter_with' => [
            // Defined as microsecond time
            'dateFormat' => 'Y-m-d H:i:s.u'
        ],
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
        'days' => env('LOG_DAILY_DAYS', 14),
        'replace_placeholders' => true,
    ],
],

// [2024-09-03 08:32:05.161104] local.INFO[App.Http.Controllers.ExampleController@index:12]: Hello, I am now in the index method under the ExampleController controller and have issued this record.

注入请求ID

如果您想注入请求ID,可以在应用程序的bootstrap/app.php文件中添加到全局middleware堆栈

use Caixingyue\LaravelStarLog\Http\Middleware\AssignRequestId;

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(AssignRequestId::class);
})

// [2024-09-03 08:36:10.896827] 7146967637.INFO[App.Http.Controllers.ExampleController@index:12]: Hello, I am now in the index method under the ExampleController controller and have issued this record.

启用请求日志

如果您希望客户端在请求路由时自动记录请求和响应信息,可以将此中间件添加到应用程序的bootstrap/app.php文件的全局middleware堆栈中

use Caixingyue\LaravelStarLog\Http\Middleware\RouteLog;

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(RouteLog::class);
})

// [2024-09-03 08:39:18.923444] 8055622306.INFO[System@request:96]: [Macintosh|OS X|PC端] - [127.0.0.1] - GET[/] - 请求报文: [null] 
// [2024-09-03 08:39:18.935572] 8055622306.INFO[App.Http.Controllers.ExampleController@index:12]: Hello, I am now in the index method under the ExampleController controller and have issued this record.  
// [2024-09-03 08:39:18.938116] 8055622306.INFO[System@response:118]: 耗时[0.09s] - 内存消耗[2mb] - 响应报文: {"code":"success"}

路由配置

有时我们希望在响应中返回请求ID以解决问题,或者我们不希望记录某些URL或方法请求的日志,甚至某些秘密字段信息。在这些情况下,您可以在starlog.php配置文件中添加相关配置。

当您希望在响应中返回请求ID时,可以在env配置中将STAR_LOG_RESPONSE_HEAD_ID设置为true

'route' => [
    'response_head_id' => env('STAR_LOG_RESPONSE_HEAD_ID', false),
],

如果您不希望记录某些URL的请求日志,可以在except中添加要排除的信息。

  • 例如,您可以添加/home以排除路径https://example.com/home的处理。
  • 您可以使用*通配符匹配模式中的所有路径。例如,/admin/*将排除所有以/admin/开头的路径。
  • 如果需要,您还可以添加包括域名和协议在内的完整URL。
  • 如果您希望根据URL的查询字符串排除某些路径,也可以包含这些信息。例如,/search?q=laravel
'route' => [
    'except' => [
        //
    ],
],

如果您不希望记录某些方法的请求,如GETPOST等,可以在except_method中添加要排除的信息。

'route' => [
    'except_method' => [
        //
    ],
],

对于您不希望记录在日志中的某些秘密信息字段,可以在secret_fields字段中添加相关的字段名称,系统将在记录数据之前自动将其替换为******。目前,我们已将current_passwordpasswordpassword_confirmation配置为秘密字段,如有必要可进行调整。

'route' => [
    'secret_fields' => [
        'current_password',
        'password',
        'password_confirmation',
    ],
],

注入Artisan ID

如果您想注入artisan ID,可以在您的命令类中使用InjectionId方法

use Caixingyue\LaravelStarLog\Console\InjectionId;

class Example extends Command
{
    use InjectionId;
}

// [2024-09-03 10:20:24.107848] 90819036.INFO[App.Console.Commands.Example@handle:52]: Hello, I have now issued this record under the Example command class.

注入队列ID

如果您想注入队列ID,可以在您的作业类中使用InjectionId方法

use Caixingyue\LaravelStarLog\Queue\InjectionId;

class ExampleJob implements ShouldQueue
{
    use InjectionId;
}

// [2024-09-03 10:24:37.351645] 57326518.INFO[App.Jobs.ExampleJob@handle:30]: Hello, I have now issued this record under the ExampleJob class.

通常,只有handle可以使用队列ID。如果__construct也需要使用它,您可以在__construct中调用$this->initializeInjectionId()来初始化它。

启用HTTP客户端请求日志

如果您希望在执行HTTP客户端请求时自动记录请求和响应,可以在env配置中将STAR_LOG_ENABLE_HTTP_CLIENT设置为true

'http' => [
    'enable' => env('STAR_LOG_ENABLE_HTTP_CLIENT', false),
],

// [2024-09-03 10:52:51.455935] 85234719.INFO[HttpClient@request:39]: GET[https://example.com] - 请求报文: [null] 
// [2024-09-03 10:52:51.787507] 85234719.INFO[HttpClient@response:37]: 耗时[0.325134s] - 200[https://example.com] - 响应报文: {"code":"success"}

对于您不希望记录在日志中的某些秘密信息字段,可以在secret_fields字段中添加相关的字段名称,系统将在记录数据之前自动将其替换为******。目前,我们已将current_passwordpasswordpassword_confirmation配置为秘密字段,如有必要可进行调整。

'http' => [
    'secret_fields' => [
        'current_password',
        'password',
        'password_confirmation',
    ],
],

启用SQL查询日志

如果您希望系统自动记录SQL查询,您可以在env配置中将STAR_LOG_ENABLE_SQL_QUERY设置为true

'query' => [
    'enable' => env('STAR_LOG_ENABLE_SQL_QUERY', false),
],

// [2024-09-03 10:49:41.908266] 81156302.INFO[System@db:46]: SQL Query: insert into "users" ("name", "email", "email_verified_at", "password", "remember_token", "updated_at", "created_at") values (?, ?, ?, ?, ?, ?, ?) | Bindings: ["Gilda Sawayn IV","jena36@example.net","2024-09-03 10:49:41","$2y$12$lxv6rkqo8DCGmWC.JviQe.rD0mytUTPUm2DnyanWM8gPcceRN7EmS","pn0TkAqvxW","2024-09-03 10:49:41","2024-09-03 10:49:41"] | Time: 0.69ms

如果您不想记录某些SQL查询,您可以在except中添加要排除的SQL。要排除的SQL语句不必完整,只要它是SQL的一部分即可。

默认情况下,我们将排除对Laravel基本表的SQL操作。如有必要,您可以按需调整。

在排除中,*关键字表示它在所有类方法中都有作用。如果您需要在类内限制限制,可以指定类名作为键,例如ExampleJob

'query' => [
    'except' => [
        ExampleJob::class => [
            'select * from "users"',
        ],
        
        '*' => [
            'insert into "sessions"',
            'insert into "cache"',
            'insert into "cache_locks"',
            'insert into "jobs"',
            'insert into "job_batches"',
            'insert into "failed_jobs"',

            'delete from "sessions"',
            'delete from "cache"',
            'delete from "cache_locks"',
            'delete from "jobs"',
            'delete from "job_batches"',
            'delete from "failed_jobs"',

            'update "sessions"',
            'update "cache"',
            'update "cache_locks"',
            'update "jobs"',
            'update "job_batches"',
            'update "failed_jobs"',

            'select * from "sessions"',
            'select * from "cache"',
            'select * from "cache_locks"',
            'select * from "jobs"',
            'select * from "job_batches"',
            'select * from "failed_jobs"',
        ],
    ],
],

辅助工具

我们提供了一些辅助工具,可以帮助您在不同场景下获取一些数据。

// Get current request id
StarLog::getRequestId();

// Get the most recent artisan id
StarLog::getArtisanId();

// Get the most recent queue id
StarLog::getQueueId();

// Get all injection id list
StarLog::getInjectionIds();

通常,在使用注入ID的类中,我们建议使用$this方法。

// Get current artisan or queue id
$this->getId();

// Get current request id
$this->getRequestId();

// Get current artisan id
$this->getArtisanId();

// Get current queue id
$this->getQueueId();

更新日志

有关最近更改的更多信息,请参阅更新日志

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件