ubuntu

ubuntu上thinkphp日志管理技巧有哪些

小樊
40
2025-11-15 00:29:24
栏目: 编程语言

Ubuntu上 ThinkPHP 日志管理实用技巧

一 基础配置与目录规范

// config/log.php
return [
    'default' => env('log.channel', 'file'),
    'level'   => env('APP_DEBUG') ? 'debug' : 'info',
    'type'    => 'File',
    'path'    => runtime_path('logs'),
    'json'    => true,         // 单行 JSON,便于采集
    'max_files' => 30,         // 保留最近30个文件(自动清理)
];

说明:ThinkPHP 自 5.1.6 起支持按文件数量自动清理(max_files),自 5.1.15 起支持 JSON 格式日志。

二 分级存储与保留策略

// config/log.php
return [
    'default' => 'stack',
    'channels' => [
        'stack' => [
            'type' => 'stack',
            'channels' => ['daily', 'error_file', 'emergency'],
        ],
        'daily' => [
            'type' => 'file',
            'path' => runtime_path('logs/daily'),
            'level' => ['info','notice','warning'],
            'max_files' => 30,         // 保留30天
            'file_size' => 10485760,    // 10MB 分割
            'json' => false,
        ],
        'error_file' => [
            'type' => 'file',
            'path' => runtime_path('logs/error'),
            'level' => ['error','critical'],
            'max_files' => 90,         // 保留90天
            'apart_level' => true,     // 每个级别单独文件
            'file_size' => 20971520,    // 20MB 分割
            'json' => true,            // JSON 便于分析
        ],
        'emergency' => [
            'type' => 'file',
            'path' => runtime_path('logs/emergency'),
            'level' => ['emergency'],
            'max_files' => 365,        // 保留1年
        ],
    ],
];

要点:常规日志按天/大小滚动并保留较短周期;错误日志保留更久;紧急日志长期留存。

三 系统级日志轮转与清理

/path/to/project/runtime/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 640 www-data www-data
    sharedscripts
    postrotate
        # 如需要,可在此触发应用内刷新句柄(可选)
    endscript
}
# 每30分钟清理一次10天前的日志
*/30 * * * * find /path/to/project/runtime/logs -mtime +10 -name "*.log" -delete

提示:优先使用 logrotate;find 方案适合作为应急或特定目录的补充。

四 安全与合规要点

$context = array_filter($context, function($key) {
    return !in_array($key, ['password','token','credit_card']);
}, ARRAY_FILTER_USE_KEY);

五 集中化与扩展采集

use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Formatter\LineFormatter;

$logger = new Logger('app');
$handler = new RotatingFileHandler('/path/to/project/runtime/logs/app.log', 30, Logger::DEBUG);
$formatter = new LineFormatter("[%datetime%] [%channel%.%level_name%] %message% %context% %extra%\n", 'Y-m-d H:i:s', true, true);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);
$logger->error('Something went wrong', ['uid'=>123]);

0
看了该问题的人还看了