Log.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace app\common\model\user;
  3. use app\common\library\UserAuth as Auth;
  4. use think\Cookie;
  5. use think\Model;
  6. class Log extends Model
  7. {
  8. protected static $title = '';
  9. // 开启自动写入时间戳字段
  10. protected static $content = '';
  11. // 定义时间戳字段名
  12. protected $name = 'user_log';
  13. protected $autoWriteTimestamp = 'int';
  14. //自定义日志标题
  15. protected $createTime = 'createtime';
  16. //自定义日志内容
  17. protected $updateTime = '';
  18. public static function setTitle($title)
  19. {
  20. self::$title = $title;
  21. }
  22. public static function setContent($content)
  23. {
  24. self::$content = $content;
  25. }
  26. /*
  27. * 日志记录
  28. */
  29. public static function record($title = '')
  30. {
  31. $auth = Auth::instance();
  32. $token = request()->server('HTTP_TOKEN', request()->request('token', Cookie::get('token')));
  33. $auth->init($token);
  34. $user_id = $auth->isLogin() ? $auth->id : 0;
  35. $username = $auth->isLogin() ? $auth->username : __('Unknown');
  36. $content = self::$content;
  37. if (!$content) {
  38. $content = request()->param();
  39. foreach ($content as $k => $v) {
  40. if (is_string($v) && strlen($v) > 200 || stripos($k, 'password') !== false) {
  41. unset($content[$k]);
  42. }
  43. }
  44. }
  45. $title = self::$title;
  46. if (!$title) {
  47. $title = [];
  48. $breadcrumb = Auth::instance()->getBreadCrumb();
  49. if ($breadcrumb) {
  50. foreach ($breadcrumb as $k => $v) {
  51. $title[] = $v['title'];
  52. }
  53. }
  54. $title = implode(' ', $title);
  55. }
  56. self::create([
  57. 'title' => $title,
  58. 'content' => !is_scalar($content) ? json_encode($content) : $content,
  59. 'url' => request()->url(),
  60. 'user_id' => $user_id,
  61. 'username' => $username,
  62. 'useragent' => request()->server('HTTP_USER_AGENT'),
  63. 'ip' => request()->ip()
  64. ]);
  65. }
  66. }