SystemLogModel.php 为系统日志类,LogModel.php 为业务日志类。有一个全局自动根据路由写入日志(入参和响应等内容)的话更好。
php
<?php
namespace common\models\common;
use backend\helpers\AdminHelper;
use common\helpers\MessageHelper;
use common\models\BaseModel;
class SystemLogModel extends BaseModel
{
const MODULE_USER = '用户';
const MODULE_ROLE = '角色';
const MODULE_MENU = '菜单';
const MODULE_CONFIG = '配置';
const MODULE_QUEUE = '队列';
const MODULE_PUSH = '推送';
const MODULE_SUBJECT_MENU = '菜单';
const ACTION_LOGIN = '登录';
const ACTION_LOGOUT = '登出';
const ACTION_NEW = '新增';
const MODULE_OPTIONS = [
self::MODULE_USER,
self::MODULE_ROLE,
self::MODULE_MENU,
self::MODULE_QUEUE,
self::MODULE_CONFIG,
];
const ACTION_OPTIONS = [
self::ACTION_LOGIN,
self::ACTION_LOGOUT,
self::ACTION_NEW,
self::ACTION_EDIT,
self::ACTION_DELETE,
self::ACTION_UPDATE_STATUS,
self::ACTION_RE_PUSH,
self::ACTION_MARK_COMPLETED,
];
public static function tableName()
{
return 'xxx_log';
}
public static function log($module, $action, $data)
{
try {
unset($data['password']);
unset($data['confirm_password']);
$log = new static();
$log->module = $module;
$log->data = json_encode($data, JSON_FLAG);
$log->item_id = $data['item_id'] ?? '';
if (empty($log->item_id)) {
$log->item_id = $data['id'] ?? '';
}
$log->action = $action;
$log->username = AdminHelper::getSessionData('username');
if (empty($log->username)) {
$log->username = 'console';
}
$log->real_name = AdminHelper::getSessionData('real_name');
if (empty($log->real_name)) {
$log->real_name = '系统自动';
}
$log->save(false);
} catch (\Throwable $e) {
MessageHelper::send('保存后台日志异常:'.$e->getMessage().$e->getTraceAsString().',参数:'.json_encode([$module, $action, $data], JSON_FLAG));
}
}
}
```php
<?php
namespace common\models\common;
class LogModel extends SystemLogModel
{
const MODULE_GOODS = '商品';
const MODULE_PRIZE_ITEM = '奖品';
const MODULE_ADMIN = '后台';
const MODULE_INTEGRAL = '积分商品活动';
const MODULE_DAYS_PRICE = '每日价格';
const MODULE_ONLINE_CATE = '线上商品分类';
const MODULE_OPTIONS = [
self::MODULE_GOODS,
self::MODULE_PROMOTION,
self::MODULE_COUPON,
self::MODULE_GOODS_LISTING,
self::MODULE_CHANNEL,
self::MODULE_BRAND,
self::MODULE_COUNTER,
self::MODULE_CLIENT,
self::MODULE_ADMIN,
self::MODULE_PRIZE,
self::MODULE_PRIZE_ITEM,
self::MODULE_ASSISTANCE
];
const ACTION_INVALID = '作废';
const ACTION_GIFT = '赠送';
const ACTION_STOCK_RESTORE = '库存修复';
const ACTION_ADD_CLIENT_CODES = '批量新增渠道';
const ACTION_OPTIONS = [
self::ACTION_NEW,
self::ACTION_EDIT,
self::ACTION_DISABLED,
self::ACTION_UPDATE_STATUS,
self::ACTION_LISTING_UP,
self::ACTION_LISTING_DOWN,
self::ACTION_CHECK,
self::ACTION_INVALID,
self::ACTION_STOCK_RESTORE,
self::ACTION_ADD_CLIENT_CODES,
];
public static function tableName()
{
return 'kld_log';
}
}
使用示例:
```php
LogModel::log(LogModel::MODULE_ONLINE_CATE, LogModel::ACTION_EDIT,$params);
日志存到表后可在后台做页面,方便快速查询。