Home >php教程 >php手册 >一定并发量下,在硬盘上写入文件

一定并发量下,在硬盘上写入文件

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 19:39:541407browse

参考了http://www.phpernote.com/php-function/929.html这篇文章的一些东西。 主要是应对,在有一定并发量的情况下,日志文件向磁盘上写入的问题。 其实fopen或fclose也会偶尔存在失败的情况,但这里没有对这个操作进行异常处理。 ?php/** * Created by PhpS

参考了http://www.phpernote.com/php-function/929.html这篇文章的一些东西。
主要是应对,在有一定并发量的情况下,日志文件向磁盘上写入的问题。
其实fopen或fclose也会偶尔存在失败的情况,但这里没有对这个操作进行异常处理。

<?php
/**
 * Created by PhpStorm.
 * User: 20779182@qq.com
 * Date: 15/10/22
 * Time: 下午5:12
 */

function write_log($log_content)
{
    $log_file = '/logs/error.log';

    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 = '/logs/error_' . date('YmdHis') . '.log';
            rename($log_file, $new_log_file);
        }
    }

    $fp=fopen($log_file,'a+');
    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('Y-m-d H:i:s') . ' ' . $log_content . "\r\n";
            fwrite($fp,$content);
        }
        fclose($fp);
    }
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn