Files
superlink/api/common/logger.php
T
nanguaboss 71c6e8d9c1 v1.0.10
2026-08-03 00:07:01 +08:00

58 lines
1.9 KiB
PHP

<?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
);
}