PHP code example of trd-rdm / stack-logger
1. Go to this page and download the library: Download trd-rdm/stack-logger library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
trd-rdm / stack-logger example snippets
'providers' => [
/*
* Package Service Providers...
*/
RDM\StackLogger\StackLoggerServiceProvider::class,
]
return [
'channels' => [
/**
* Log Facade
* 主要 logger , 以 stack driver 結合多個 custom log 同時呼叫
* 加入 channels 的 driver 可以在 GCPLog 中呼叫
*/
'stack_logger' => [
'driver' => 'stack',
'channels' => ['console', 'file'], // 指定多種 log 頻道, 可以自由添加移除 (可添加選項 : ['console', 'file', 'storage', 'stackdriver', 'telegram'])
'ignore_exceptions' => false,
],
/**
* 1. 螢幕輸出: 彩色字體
*/
'console' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'), // The minimum logging level at which this handler will be triggered
'handler' => RDM\StackLogger\Handlers\ConsoleLogger::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
],
],
/**
* 2. 文件檔案 : 需要指定寫入檔案路徑
*/
'file' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => RDM\StackLogger\Handlers\FileLogger::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
// handler constructor 額外參數
'default_path' => storage_path('default.log'), // 預設檔案路徑
'permission' => 0775, // The log file's permissions
'locking' => false, // Attempt to lock the log file before writing to it
],
],
/**
* 3. GCP Storage 儲存空間 : 需要指定本地上傳檔案路徑 與 storage 路徑
*
* 結果請至 GCP Cloud Storage - Browser查看
*
* @link https://console.cloud.google.com/storage/browser
*/
'storage' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => RDM\StackLogger\Handlers\GcpStorageLogger::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'gcp_project_id' => 'your-gcp-project', // GCP Project
'credential_path' => 'your-local-credential-file-path', // 憑證路徑 (專案根目錄為 root)
'bucket_id' => 'your-storage-bucket-id', // GCP Storage bucket 名稱
'bucket_folder' => 'bucket-folder1/folder2', // 此 logger 在 bucket id 底下的 root 路徑
'bucket_path' => '', // bucket_folder 底下的檔案路徑, 需要使用者用 setPath() 設置後才能寫入
'ignore_exceptions' => false, // 上傳失敗時不要拋出例外
],
],
/**
* 4. GCP Stackdriver : 需要指定 log 名稱
*
* 輸出結果請至 Google Console 查詢 Log
*
* @link https://console.cloud.google.com/logs
*/
'stackdriver' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => RDM\StackLogger\Handlers\StackdriverLogger::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'name' => 'your-stackdriver-logging-name', // log 名稱 (在 google console 查詢過濾條件 logName 的值)
'gcp_project_id' => 'rdm-bbos',
'credential_path' => '/rdm-bbos.json', // 憑證路徑 (專案根目錄為 root)
'batch_enabled' => true, // 允許批次送出多筆 log 紀錄, 避免每次送出產生高延遲
],
],
/**
* 5. Telegram 通知 : 需要指定 接收者 chat_id 與 api_key 機器人群組
*/
'telegram' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'), // The minimum logging level at which this handler will be triggered
'handler' => RDM\StackLogger\Handlers\TelegramLogger::class,
'formatter' => env('LOG_STDOUT_FORMATTER'),
'with' => [
'chat_ids' => ['1378441015'], // 收信者
'disable_notification' => false, // 關閉通知提示音
'api_key' => (env('APP_ENV') === 'prod')
? env('TELEGRAM_BOT_TOKEN', 'xxxxx') // 正式 Bot
: env('TELEGRAM_BOT_TOKEN', 'xxxxx'), // 測試 Bot
],
],
]
];
Log::channel('stack_logger')->info('info message');
Log::channel('console')->info('info message');
Log::channel('file')->info('info message');
Log::channel('storage')->info('info message');
Log::channel('stackdriver')->info('info message');
Log::channel('telegram')->info('info message');
use RDM\StackLogger\Facades\GCPLog;
use \Psr\Log\LogLevel;
// 成功訊息
GCPLog::info('success');
// 同上成功訊息
GCPLog::log(LogLevel::INFO, 'success', ['success' => true, 'result' => []]);
try {
// ...
} catch (\Exception $exception) {
// 錯誤訊息
GCPLog::error('something wrong');
// 印出漂亮格式的錯誤訊息
GCPLog::renderException($exception);
// 匯出例外訊息成 HTML 檔
GCPLog:dumpExceptionPrettyPage($exception, storage_path('exception.html'));
}
use RDM\StackLogger\Facades\GCPLog;
// 設置路徑參數
GCPLog::setLocalLogPath(storage_path('logs/err.log')) // 設置 log 檔案參數
->setStackDriverLogName('stack-driver-log-name'); // 設置 stackdriver log 名稱
GCPLog::info("message");
// 讀取路徑參數
fprintf("All messages are written at file %s", GCPLog::getLocalLogPath()); // 取得 log 檔案路徑
fprintf("All messages are export to stackdriver: %s", GCPLog::getStackDriverLink()); // 取得 stackdriver log 存取連結
use RDM\StackLogger\Facades\GCPLog;
try {
$john_user_id = '12345';
GCPLog::setTelegramChatIds([$john_user_id]) // 設置收訊者
->disableTelegramNotification(); // 關閉通知聲響
GCPLog::info('<b>TITLE</b> message'); // 送出通知 (支援 html 格式,若要避免請使用 `htmlspecialchars()` 跳脫或是 <pre> 包覆)
} catch (\Throwable $e) {
// html tag 限制 https://core.telegram.org/api/entities#allowed-entities
// 最大文字長度 : 4096 字元
dump($e);
}
GCPLog::telegram()->info('<b>TITLE</b> message');
use RDM\StackLogger\Facades\GCPLog;
GCPLog::watch(); // 開始計時
/*
* Code Block 1
*/
GCPLog::timing('執行 Code Block 1');
/*
* Code Block 2
*/
GCPLog::timing('執行 Code Block 2');
/**
範例輸出結果:
執行 Code Block 1 1.500 sec
執行 Code Block 2 1.500 sec
*/
use RDM\StackLogger\Facades\GCPLog;
$timer = GCPLog::createTimer();
$timer->setDescription('執行 Code Block 1');
for($i = 5; $i > 0; $i--) {
$timer->start();
sleep(1);
$timer->stop();
sleep(2);
}
echo (string)$timer;
/**
範例輸出結果:
執行 Code Block 1 花費 : 5.01 秒
*/
use RDM\StackLogger\Facades\GCPLog;
use Illuminate\Support\Facades\DB;
$connection = 'mysql';
GCPLog::enableMysqlGeneralLog($connection); // 啟用 mysql general log
DB::connection($connection)->table('users')->get(); // send query
GCPLog::disableMysqlGeneralLog($connection); // 停用 mysql general log
use RDM\StackLogger\Facades\GCPLog;
use Illuminate\Support\Facades\DB;
// 選取 GCPLog 中的特定 logger, 執行其內部函式
GCPLog::file()->setPath(storage_path('laravel.log'));
GCPLog::console()->info('message');
GCPLog::telegram()->info('<b>TITLE</b> message');