Files
superlink/api/common/logger.php
T

76 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 操作日志写入函数
* 所有写类接口(add/update/delete/import/export/audit/convert/login/logout)必须调用 logAction()。
*/
require_once __DIR__ . '/db.php';
/**
* 写入操作日志
* @param int|null $userId 操作人ID
* @param string|null $username 操作人账号
* @param string $action 操作类型
* @param string $module 操作模块
* @param string|null $targetTable 操作对象表名
* @param int|null $targetId 操作对象记录ID
* @param mixed $content 操作内容(数组,自动JSON编码)
* @return bool
*/
function logAction($userId, $username, $action, $module, $targetTable = null, $targetId = null, $content = null)
{
try {
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$pdo = DB::getInstance()->getPdo();
$stmt = $pdo->prepare(
"INSERT INTO system_logs (user_id, username, action, module, target_table, target_id, content, ip)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$contentJson = ($content !== null && $content !== '')
? json_encode($content, JSON_UNESCAPED_UNICODE)
: null;
return $stmt->execute([$userId, $username, $action, $module, $targetTable, $targetId, $contentJson, $ip]);
} catch (Exception $e) {
// 日志失败不影响主流程
return false;
}
}
/**
* 基于当前 Session 用户写入日志(便捷函数)
* @param string $action
* @param string $module
* @param string|null $targetTable
* @param int|null $targetId
* @param mixed $content
*/
function logCurrent($action, $module, $targetTable = null, $targetId = null, $content = null)
{
return logAction(
$_SESSION['user_id'] ?? null,
$_SESSION['username'] ?? null,
$action,
$module,
$targetTable,
$targetId,
$content
);
}
/**
* 技术异常日志(批次1 REV-ARCH-3):写入 runtime/logs/error-YYYYMM.log
* 业务审计走 system_logs(logAction/logCurrent),技术异常走此文件。
* @param string $message
* @param mixed $context 上下文数组,自动 JSON 编码
*/
function logError($message, $context = null)
{
$dir = __DIR__ . '/../../runtime/logs';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$line = '[' . date('Y-m-d H:i:s') . '] ' . $message
. ($context !== null ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '')
. PHP_EOL;
@file_put_contents($dir . '/error-' . date('Ym') . '.log', $line, FILE_APPEND);
}