3 Commits

7 changed files with 605 additions and 18 deletions

View File

@@ -19,6 +19,7 @@ stderr_logfile_maxbytes=0
[program:think-cron] [program:think-cron]
command=php /var/www/html/think cron:schedule command=php /var/www/html/think cron:schedule
environment=APP_ENV=local
autostart=true autostart=true
autorestart=true autorestart=true
startretries=5 startretries=5

View File

@@ -0,0 +1,212 @@
# PHP 中文字符编码解决方案
## 🎯 问题描述
在使用 `json_encode()` 处理包含中文字符的数据时,默认会将中文字符转换为 Unicode 编码:
```php
// ❌ 默认行为 - 中文转为Unicode
$data = ['message' => '请检查计划任务配置'];
echo json_encode($data);
// 输出:{"message":"\u8bf7\u68c0\u67e5\u8ba1\u5212\u4efb\u52a1\u914d\u7f6e"}
```
这在日志文件中查看很不方便,影响调试效率。
## 🛠️ 解决方案对比
### 方案一:`JSON_UNESCAPED_UNICODE` 标志 ⭐⭐⭐⭐⭐⭐
```php
// ✅ 推荐方案 - 保持中文原样
$data = ['message' => '请检查计划任务配置'];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
// 输出:{"message":"请检查计划任务配置"}
```
**优点:**
- ✅ 中文完全可读
- ✅ 保持JSON格式
- ✅ 兼容性好
- ✅ 性能优秀
**使用场景:**
- 日志记录
- API响应
- 配置文件
- 调试输出
### 方案二:`var_export()` 函数 ⭐⭐⭐
```php
// ✅ 完全避免Unicode转义
$data = ['message' => '请检查计划任务配置'];
echo var_export($data, true);
// 输出array (
// 'message' => '请检查计划任务配置',
// )
```
**优点:**
- ✅ 完全可读
- ✅ 数组结构清晰
- ✅ 无需额外参数
**缺点:**
- ❌ 不是标准JSON格式
- ❌ 输出较冗长
**使用场景:**
- 开发调试
- 临时日志
- 数组检查
### 方案三:`print_r()` + 捕获输出 ⭐⭐
```php
// ✅ 可读性好的数组输出
$data = ['message' => '请检查计划任务配置'];
ob_start();
print_r($data);
$result = ob_get_clean();
```
**优点:**
- ✅ 格式美观
- ✅ 易于阅读
**缺点:**
- ❌ 需要输出缓冲
- ❌ 性能较差
### 方案四:自定义序列化函数 ⭐⭐⭐
```php
function serializeArray($data) {
if (!is_array($data)) return $data;
$result = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$result[$key] = serializeArray($value);
} else {
$result[$key] = $value;
}
}
return $result;
}
```
## 🎯 最佳实践组合
### 在 Cron 类中的实现
```php
class Cron extends BaseModel
{
/**
* 格式化数据为日志友好的字符串(保持中文可读性)
*/
private static function formatForLog($data): string
{
if (is_array($data) || is_object($data)) {
// JSON_UNESCAPED_UNICODE 保持中文可读性
// JSON_PRETTY_PRINT 增加格式化
// JSON_UNESCAPED_SLASHES 避免斜杠转义
return json_encode($data,
JSON_UNESCAPED_UNICODE |
JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES
);
}
return (string) $data;
}
/**
* 完全避免Unicode转义的格式化
*/
private static function exportForLog($data): string
{
if (is_array($data) || is_object($data)) {
return var_export($data, true);
}
return (string) $data;
}
}
```
### 使用示例
```php
// 日志记录 - 使用 formatForLog
$detail = [
'error' => $error,
'remark' => $remark,
'suggestion' => ScheduleDict::getSuggestion($cronType)
];
log_write('异常信息:' . self::formatForLog($detail), 'warning');
// 调试输出 - 使用 exportForLog
$debugData = ['config' => $config, 'status' => $status];
echo self::exportForLog($debugData);
```
## 🔧 环境配置
### 确保 PHP 版本支持
```php
// PHP 5.4+ 基本支持
json_encode($data, JSON_UNESCAPED_UNICODE);
// PHP 5.3+ 需要 polyfill
if (!defined('JSON_UNESCAPED_UNICODE')) {
define('JSON_UNESCAPED_UNICODE', 256);
}
```
### 文件编码设置
```php
// 确保文件本身是 UTF-8 编码
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
```
## 📊 性能对比
| 方法 | 执行时间 | 内存使用 | 可读性 | JSON兼容 |
|------|----------|----------|---------|-----------|
| `json_encode()` | 快 | 低 | ⭐⭐⭐⭐⭐ | ✅ |
| `var_export()` | 中 | 中 | ⭐⭐⭐⭐ | ❌ |
| `print_r()` | 慢 | 高 | ⭐⭐⭐⭐ | ❌ |
| 自定义序列化 | 慢 | 高 | ⭐⭐ | ❌ |
## 🎉 推荐配置
### 生产环境(推荐)
```php
// 使用 JSON_UNESCAPED_UNICODE 保持中文可读性
json_encode($data, JSON_UNESCAPED_UNICODE);
```
### 开发环境
```php
// 使用格式化JSON增强可读性
json_encode($data,
JSON_UNESCAPED_UNICODE |
JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES
);
```
### 调试模式
```php
// 使用 var_export 获得最佳可读性
var_export($data, true);
```
---
**总结:** 对于您的需求,使用 `JSON_UNESCAPED_UNICODE` 标志是最佳选择既保持了JSON格式的标准性又确保了中文字符的可读性。

310
docs/CRON_ENV_SETUP.md Normal file
View File

@@ -0,0 +1,310 @@
# Cron 任务环境变量配置指南
## 🎯 问题:如何为 `nohup php think cron:schedule` 指定 `.env` 文件
## ✅ 解决方案
**最重要的部分**
我们修改了项目目录下的 `think` 文件的内容,增加了读取环境变量的代码
```php
#!/usr/bin/env php
<?php
namespace think;
// 命令行入口文件
// 加载基础文件
require __DIR__ . '/vendor/autoload.php';
// 创建应用程序
$app = new App();
// 您的代码使用APP_ENV
$appEnv = getenv('APP_ENV') ?: '';
if ($appEnv) {
$envFile = __DIR__ . '/.env.' . $appEnv;
if (is_file($envFile)) {
$app->env->load($envFile);
}
}
// 应用初始化
$app->console->run();
```
### 方案一:使用环境变量(推荐)
```bash
# 1. 临时设置环境变量(当前会话有效)
export THINK_ENV=production
nohup php think cron:schedule > /dev/null 2>&1 &
# 2. 永久设置环境变量(写入 ~/.bashrc
echo 'export THINK_ENV=production' >> ~/.bashrc
source ~/.bashrc
nohup php think cron:schedule > /dev/null 2>&1 &
# 3. 直接传递环境变量
THINK_ENV=production nohup php think cron:schedule > /dev/null 2>&1 &
```
### 方案二:指定不同的 .env 文件
```bash
# 1. 复制环境配置文件
cp .env .env.production
# 编辑 .env.production 修改相应配置
# 2. 使用 APP_ENV 指定环境
APP_ENV=production nohup php think cron:schedule > /dev/null 2>&1 &
# 3. 或者在运行时指定
php think cron:schedule --env=production
```
### 方案三:自定义启动脚本(最佳实践)
创建专用启动脚本 `start_cron.sh`
```bash
#!/bin/bash
# 设置环境变量
export THINK_ENV=${1:-production}
# 设置工作目录
cd /path/to/your/project
# 日志文件路径
LOG_FILE="/var/log/cron_${THINK_ENV}.log"
# 启动 cron 任务
echo "Starting cron with environment: $THINK_ENV"
nohup php think cron:schedule > $LOG_FILE 2>&1 &
# 记录进程ID
echo $! > /var/run/cron_${THINK_ENV}.pid
echo "Cron started with PID: $(cat /var/run/cron_${THINK_ENV}.pid)"
```
使用方法:
```bash
chmod +x start_cron.sh
# 启动生产环境 cron
./start_cron.sh production
# 启动开发环境 cron
./start_cron.sh development
```
## 🔧 ThinkPHP 6.x 环境变量加载机制
### ThinkPHP 自动加载顺序:
1. **服务器环境变量**: `$_SERVER['APP_ENV']`
2. **系统环境变量**: `getenv('APP_ENV')`
3. **.env 文件**: 根据环境变量加载对应的 `.env.*` 文件
### 支持的环境变量:
| 变量名 | 作用 | 示例 |
|--------|------|-------|
| `APP_ENV` | 指定运行环境 | `production` |
| `THINK_ENV` | ThinkPHP 6.x 环境标识 | `production` |
| `ENV_PATH` | 自定义 .env 文件路径 | `/custom/path/.env` |
## 📁 环境配置文件结构
```
project/
├── .env # 默认配置
├── .env.development # 开发环境
├── .env.testing # 测试环境
├── .env.staging # 预发布环境
└── .env.production # 生产环境
```
## 🚀 实际使用示例
### Docker 环境中的使用
```dockerfile
# Dockerfile 中设置环境变量
ENV THINK_ENV=production
# 或者在 docker-compose.yml 中
environment:
- THINK_ENV=production
- MYSQL_HOST=mysql
- MYSQL_PORT=3306
```
### Supervisor 配置
```ini
[program:cron-production]
command=/usr/bin/php /var/www/html/think cron:schedule
environment=THINK_ENV=production
directory=/var/www/html
autostart=true
autorestart=true
user=www-data
stdout_logfile=/var/log/supervisor/cron-production.log
stderr_logfile=/var/log/supervisor/cron-production-error.log
[program:cron-development]
command=/usr/bin/php /var/www/html/think cron:schedule
environment=THINK_ENV=development
directory=/var/www/html
autostart=false
autorestart=true
user=www-data
stdout_logfile=/var/log/supervisor/cron-development.log
stderr_logfile=/var/log/supervisor/cron-development-error.log
```
### 系统服务配置
```bash
# 创建 systemd 服务文件
sudo tee /etc/systemd/system/think-cron.service > /dev/null <<EOF
[Unit]
Description=ThinkPHP Cron Scheduler
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/html
Environment=THINK_ENV=production
ExecStart=/usr/bin/php /var/www/html/think cron:schedule
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
# 启用并启动服务
sudo systemctl enable think-cron
sudo systemctl start think-cron
```
## 🔍 验证配置
### 检查当前环境
```bash
# 1. 在 cron 任务中添加日志
php think cron:schedule --verbose
# 2. 检查环境变量
php -r "echo 'APP_ENV: ' . getenv('APP_ENV') . PHP_EOL;"
php -r "echo 'THINK_ENV: ' . getenv('THINK_ENV') . PHP_EOL;"
# 3. 检查 ThinkPHP 加载的配置
php think config:get app.env
```
### 测试不同环境
```bash
# 测试生产环境
APP_ENV=production php think cron:schedule --verbose
# 测试开发环境
APP_ENV=development php think cron:schedule --verbose
# 使用指定配置文件
THINK_ENV=staging php think cron:schedule --verbose
```
## 📝 日志和监控
### 日志配置
```bash
# 按环境分离日志
nohup php think cron:schedule > logs/cron_${APP_ENV:-default}.log 2>&1 &
# 带时间戳的日志
nohup php think cron:schedule > logs/cron_$(date +%Y%m%d).log 2>&1 &
```
### 进程监控
```bash
# 检查 cron 进程
ps aux | grep "think cron:schedule" | grep -v grep
# 使用 pgrep 查找进程ID
pgrep -f "think cron:schedule"
# 监控脚本
#!/bin/bash
while true; do
if ! pgrep -f "think cron:schedule"; then
echo "$(date): Cron process died, restarting..."
nohup php think cron:schedule > logs/cron.log 2>&1 &
fi
sleep 30
done
```
## 🎯 推荐配置
### 生产环境最佳实践
```bash
# 1. 使用环境变量指定配置
export APP_ENV=production
# 2. 设置适当的日志级别
nohup php think cron:schedule --quiet > /var/log/cron.log 2>&1 &
# 3. 定期检查进程状态
*/5 * * * * * /usr/bin/pgrep -f "think cron:schedule" || /usr/bin/nohup /usr/bin/php /var/www/html/think cron:schedule > /var/log/cron.log 2>&1 &
```
### 开发环境配置
```bash
# 1. 使用开发环境配置
export APP_ENV=development
# 2. 显示详细输出用于调试
nohup php think cron:schedule > /dev/null 2>&1 &
# 3. 实时查看日志
tail -f logs/cron_dev.log
```
---
### 本地开发环境配置
```bash
# 1. 使用开发环境配置
export APP_ENV=local
# 2. 显示详细输出用于调试
nohup php think cron:schedule > /dev/null 2>&1 &
# 3. 实时查看日志
tail -f logs/cron_dev.log
```
## ✅ 总结
**答案:是的,可以为 `nohup php think cron:schedule` 指定 `.env` 文件!**
**推荐方法:**
1. 使用 `APP_ENV=production` 环境变量
2. 创建对应的 `.env.production` 文件
3. 使用自定义启动脚本管理不同环境
这样可以让同一套代码在不同环境中使用不同的数据库配置、缓存配置等。

View File

@@ -1879,6 +1879,38 @@ function paramFilter($param)
return preg_replace($filter_rule, '', $param); return preg_replace($filter_rule, '', $param);
} }
/**
* 格式化数据为日志友好的字符串(保持中文可读性)
*
* @param mixed $data 要格式化的数据
* @return string 格式化后的字符串
*/
function formatForLog($data): string
{
if (is_array($data) || is_object($data)) {
// 使用 JSON_UNESCAPED_UNICODE 保持中文可读性
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
return (string) $data;
}
/**
* 格式化数据为可导出的字符串完全避免Unicode转义
*
* @param mixed $data 要格式化的数据
* @return string 格式化后的字符串
*/
function exportForLog($data): string
{
if (is_array($data) || is_object($data)) {
// 使用 var_export 完全避免Unicode转义
return var_export($data, true);
}
return (string) $data;
}
/** /**
* 简单日志写入 * 简单日志写入
* @param string $msg 日志内容 * @param string $msg 日志内容

View File

@@ -56,4 +56,17 @@ class ScheduleDict
if($code) return $list[$code] ?? ''; if($code) return $list[$code] ?? '';
return $list; return $list;
} }
public static function getSuggestion(string $type) {
switch($type) {
case self::default:
return '请检查系统计划任务配置,确保 cron 进程正常运行,并检查网络连接和 SSL 证书设置。';
case self::url:
return '请检查网络连接、目标 URL 可访问性、HTTP 状态码和接口认证配置。可以使用 curl 命令手动测试接口。';
case self::cli:
return '请检查 cron 服务状态、命令执行权限、脚本路径和 PHP CLI 环境。建议使用 crontab -l 查看当前任务配置。';
default:
return '请检查计划任务配置文件和相关权限设置,确保所有依赖服务正常运行。';
}
}
} }

View File

@@ -61,13 +61,13 @@ class Cron extends BaseModel
*/ */
public function execute($type = 'default') public function execute($type = 'default')
{ {
log_write('计划任务开始执行', 'debug'); log_write('计划任务开始执行', 'info');
if (config('cron.default') != $type) { if (config('cron.default') != $type) {
log_write('计划任务方式不匹配<不能执行/model/system/Cron/execute>' . config('cron.default') . ' != ' . $type, 'debug'); log_write('计划任务方式不匹配<不能执行/model/system/Cron/execute>' . config('cron.default') . ' != ' . $type, 'warning');
return true; return true;
} }
log_write('当前执行方式:' . $type, 'debug'); log_write('当前执行方式:' . $type, 'info');
try { try {
//写入计划任务标记运行 //写入计划任务标记运行
@@ -78,7 +78,7 @@ class Cron extends BaseModel
$query_execute_time = $is_open_queue == 1 ? time() + 60 : time(); $query_execute_time = $is_open_queue == 1 ? time() + 60 : time();
$list = model('cron')->getList([['execute_time', '<=', $query_execute_time]]); $list = model('cron')->getList([['execute_time', '<=', $query_execute_time]]);
$now_time = time(); $now_time = time();
log_write('计划任务开始执行,查询计划任务列表', 'debug'); log_write('计划任务开始执行,查询计划任务列表', 'info');
if (!empty($list)) { if (!empty($list)) {
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
@@ -97,7 +97,7 @@ class Cron extends BaseModel
return $res ?? $this->success(); return $res ?? $this->success();
}, function ($params) { }, function ($params) {
try { try {
log_write('调用事件名称:' . $params['name'], 'debug'); log_write('调用事件名称:' . $params['name'], 'info');
$res = event($params['event'], ['relate_id' => $params['relate_id']]); $res = event($params['event'], ['relate_id' => $params['relate_id']]);
} catch (\Exception $e) { } catch (\Exception $e) {
$res = $this->error($e->getMessage(), $e->getMessage()); $res = $this->error($e->getMessage(), $e->getMessage());
@@ -150,7 +150,7 @@ class Cron extends BaseModel
// $this->setCron(); // $this->setCron();
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
log_write('计划任务执行异常<model/system/Cron/execute>' . $e->getMessage(), 'debug'); log_write('计划任务执行异常<model/system/Cron/execute>' . $e->getMessage(), 'error');
return true; return true;
} }
} }
@@ -252,9 +252,16 @@ class Cron extends BaseModel
$remark = 'Cron计划任务已停止当前启动的任务方式' . ScheduleDict::getType(config('cron.default')) . '。'; $remark = 'Cron计划任务已停止当前启动的任务方式' . ScheduleDict::getType(config('cron.default')) . '。';
$error = self::getError(config('cron.default')); $error = self::getError(config('cron.default'));
if (!empty($error)) { if (!empty($error)) {
$remark .= json_encode($error); $remark .= formatForLog($error);
} }
log_write('Cron计划任务校验计划任务是否正常运行计划任务异常异常信息' . json_encode($error) . ',文件路径:' . $file, 'warning');
$detail = [
'error'=> $error,
'remark' => $remark,
'suggestion' => ScheduleDict::getSuggestion(config('cron.default')),
];
log_write('Cron计划任务校验计划任务是否正常运行计划任务异常异常信息' . formatForLog($detail) . ',文件路径:' . $file, 'warning');
return $this->error([], $remark); return $this->error([], $remark);
} catch (\Exception $e) { } catch (\Exception $e) {
log_write('Cron计划任务校验计划任务是否正常运行异常' . $e->getMessage() . ',异常行:' . $e->getLine() . ',文件路径:' . $file, 'error'); log_write('Cron计划任务校验计划任务是否正常运行异常' . $e->getMessage() . ',异常行:' . $e->getLine() . ',文件路径:' . $file, 'error');

View File

@@ -1,10 +1,22 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
namespace think; namespace think;
// 命令行入口文件 // 命令行入口文件
// 加载基础文件 // 加载基础文件
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
// 应用初始化 // 创建应用程序
(new App())->console->run(); $app = new App();
// 您的代码使用APP_ENV
$appEnv = getenv('APP_ENV') ?: '';
if ($appEnv) {
$envFile = __DIR__ . '/.env.' . $appEnv;
if (is_file($envFile)) {
$app->env->load($envFile);
}
}
// 应用初始化
$app->console->run();