Home php教程 PHP源码 Write files on the hard disk under a certain amount of concurrency

Write files on the hard disk under a certain amount of concurrency

Nov 09, 2016 am 10:11 AM

<?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);
    }
}
Copy after login

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)