file_put_contents锁的问题

记一次线上生产file_put_contents锁的问题

php项目,很多地方加了日志记录,方法为

复制代码
function logstr($name='log',$str="",$type="Ymd"){
    $file = date("$type").'_'.$name.'.log';
    $add = __DIR__.'/../runtime/cuslog/'.date("Ym").'/';
    if(!is_dir($add)){
        mkdir(iconv("UTF-8", "GBK", $add),0777,true);
    }
    $file  = $add.$file;
    $content=[
        'name'=>$name,
        'premsg'=>'',
        'time'=> date('Y-m-d H:i:s'),
        'content'=>$str
    ];

    file_put_contents($file, json_encode($content,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES).PHP_EOL,FILE_APPEND);
}

忽然有天查日志,发现日志有丢失问题,在并发情况下,有些日志没有没记录下来

所以加了下锁 LOCK_EX

变为

复制代码
file_put_contents($file, json_encode($content,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES).PHP_EOL,FILE_APPEND|LOCK_EX);

这样的确不会出现丢日志的问题

但问题来了,在并发下,导致接口响应速度极慢

所以又删了

慎用

相关推荐
小虎哥-技术博客20 小时前
ThinkPHP 5.x 到 8.x 行为扩展迁移指南
php
小虎哥-技术博客1 天前
ThinkPHP 5 到 ThinkPHP 8 路由迁移完整指南
php
yangSnowy1 天前
PHP的运行模式
开发语言·php
YJlio1 天前
网络与通信具总览(14.0):从 PsPing 到 TCPView / Whois 的联合作战
开发语言·网络·php
iCheney!1 天前
php生成赛博像素风头像
开发语言·php
小虎哥-技术博客1 天前
ThinkPHP 5.0.24 到 ThinkPHP 8.x 迁移学习指南
php
m0_738120721 天前
渗透测试——靶机DC-6详细横向过程(Wordpress渗透)
服务器·网络·python·web安全·ssh·php
傻啦嘿哟1 天前
实战:用GraphQL接口高效采集数据
开发语言·驱动开发·php
BingoGo1 天前
CatchAdmin 2025 年终总结 模块化架构的进化之路
后端·开源·php
qq_117179071 天前
海康威视球机萤石云不在线问题解决方案
开发语言·智能路由器·php