> php教程 > PHP源码 > 본문

특정 양의 동시성으로 하드 디스크에 파일 쓰기

大家讲道理
풀어 주다: 2016-11-09 10:11:55
원래의
1296명이 탐색했습니다.

<?php
 
function write_log($log_content)
{
    $log_file = &#39;/logs/error.log&#39;;
 
    if(is_file($log_file)) {
        // 检测log文件大小,将每个log文件控制在2m以内
        $log_filesize = filesize($log_file);
        $max_size = 2 * 1024 * 1024; // 可以接受的最大的文件大小
        if($log_filesize >= $max_size) {
            $new_log_file = &#39;/logs/error_&#39; . date(&#39;YmdHis&#39;) . &#39;.log&#39;;
            rename($log_file, $new_log_file);
        }
    }
 
    $fp=fopen($log_file,&#39;a+&#39;);
    if($fp){
        $startTime=microtime();
        do{
            // 这个循环可以保证进程在尝试1m后,如果未能锁定文件,则放弃写入日志的操作
            $canWrite=flock($fp,LOCK_EX);
            if(!$canWrite){
                usleep(round(rand(0,100)*1000));
            }
        }while((!$canWrite)&&((microtime()-$startTime)<1000));
        if($canWrite){
            $content = date(&#39;Y-m-d H:i:s&#39;) . &#39; &#39; . $log_content . "\r\n";
            fwrite($fp,$content);
        }
        fclose($fp);
    }
}
로그인 후 복사

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!