php 如何在php中创建日志文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19898688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:12:31  来源:igfitidea点击:

how to create a logfile in php?

phplogfile

提问by maecy m

I want to create a logfile for my system to register/log every action they do inside the system. But I have no idea how to do it.

我想为我的系统创建一个日志文件来注册/记录他们在系统内执行的每个操作。但我不知道该怎么做。

For example, I have this php code that does the login function.

例如,我有这个执行登录功能的 php 代码。

public function hasAccess($username,$password){
    $form = array();
    $form['username'] = $username;
    $form['password'] = $password;


    $securityDAO = $this->getDAO('SecurityDAO');
    $result = $securityDAO->hasAccess($form);
    //var_dump($form);
    //var_dump($result);
    if($result[0]['success']=='1'){
        $this->Session->add('user_id', $result[0]['id']);
        //$this->Session->add('username', $result[0]['username']);
        //$this->Session->add('roleid', $result[0]['roleid']);
        return $this->status(0,true,'auth.success',$result);
    }else{
        return $this->status(0,false,'auth.failed',$result);
    }
}

now I want to create a logfile entitled 'the date today', then when that functions is used for loging in, it will write that user has logged in, the same with other functions. But I only want a single file for every day.

现在我想创建一个名为“今天的日期”的日志文件,然后当该功能用于登录时,它将写入该用户已登录,与其他功能相同。但我每天只想要一个文件。

Could anyone be kind enough to guide and teach me how I should do my codes?

任何人都可以指导和教我如何编写代码吗?

回答by Lawrence Cherone

To write to a log file and make a new one each day, you could use date("j.n.Y")as part of the filename.

要写入日志文件并每天创建一个新文件,您可以将其date("j.n.Y")用作文件名的一部分。

//Something to write to txt log
$log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
        "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
        "User: ".$username.PHP_EOL.
        "-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

So you would place that within your hasAccess()method.

所以你会把它放在你的hasAccess()方法中。

public function hasAccess($username,$password){
    $form = array();
    $form['username'] = $username;
    $form['password'] = $password;

    $securityDAO = $this->getDAO('SecurityDAO');
    $result = $securityDAO->hasAccess($form);

    //Write action to txt log
    $log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
            "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
            "User: ".$username.PHP_EOL.
            "-------------------------".PHP_EOL;
    //-
    file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND);

    if($result[0]['success']=='1'){
        $this->Session->add('user_id', $result[0]['id']);
        //$this->Session->add('username', $result[0]['username']);
        //$this->Session->add('roleid', $result[0]['roleid']);
        return $this->status(0,true,'auth.success',$result);
    }else{
        return $this->status(0,false,'auth.failed',$result);
    }
}

回答by JON

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

在 php 中创建一个日志文件,为此您需要传递有关函数的数据,它会为您创建日志文件。

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
} 
// call to function
wh_log("this is my log message");

回答by Surabhil Sergy

Please check with this documentation.

请检查此文档。

http://php.net/manual/en/function.error-log.php

http://php.net/manual/en/function.error-log.php

Example:

例子:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "[email protected]");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

回答by Paulo Freitas

You could use built-in function trigger_error()to trigger user errors/warnings/notices and set_error_handler()to handle them. Inside your error handler you might want to use error_log()or file_put_contents()to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d'))as filename. And now you should know where to start... :)

您可以使用内置函数trigger_error()来触发用户错误/警告/通知并set_error_handler()处理它们。在您的错误处理程序中,您可能想要使用error_log()file_put_contents()将所有记录存储在文件中。要每天使用一个文件,只需使用诸如sprintf('%s.log', date('Y-m-d'))文件名之类的内容。现在你应该知道从哪里开始...... :)

回答by Pasupathi Thangavel

Please check this code, it works fine for me.

请检查此代码,它对我来说很好用。

$data = array('shopid'=>3,'version'=> 1,'value=>1');  //here $data is dummy varaible

error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log");

//In $data we can mention the error messege and create the log

回答by Manish

Agree with the @jon answer. Just added modified the path to create the logdirectory inside the root

同意@jon 的回答。刚刚添加修改了路径,在log里面创建目录root

 function wh_log($log_msg) {
    $log_filename = $_SERVER['DOCUMENT_ROOT']."/log";
    if (!file_exists($log_filename))
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}

just added $_SERVER['DOCUMENT_ROOT']

刚刚添加 $_SERVER['DOCUMENT_ROOT']

回答by Ashwani Panwar

For printing log use this function, this will create log file in logfolder. Create log folder if its not exists .

打印日志使用此功能,这将在log文件夹中创建日志文件。如果日志文件夹不存在,则创建它。

logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");


function logger($logMsg="logger", $filename="logger", $logData=""){     
            $log  = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .                  
            "-------------------------".PHP_EOL;
            file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);                      
    }

回答by xinthose

This is my working code. Thanks to Paulofor the links. You create a custom error handler and call the trigger_errorfunction with the correct $errnoexception, even if it's not an error. Make sure you can write to the log file directory without administrator access.

这是我的工作代码。感谢Paulo提供的链接。您创建一个自定义错误处理程序并trigger_error使用正确的$errno异常调用该函数,即使它不是错误。确保您可以在没有管理员访问权限的情况下写入日志文件目录。

<?php
    $logfile_dir = "C:\workspace\logs\";   // or "/var/log/" for Linux
    $logfile = $logfile_dir . "php_" . date("y-m-d") . ".log";
    $logfile_delete_days = 30;

    function error_handler($errno, $errstr, $errfile, $errline)
    {
        global $logfile_dir, $logfile, $logfile_delete_days;

        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting, so let it fall
            // through to the standard PHP error handler
            return false;
        }

        $filename = basename($errfile);

        switch ($errno) {
            case E_USER_ERROR:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX);
                exit(1);
                break;

            case E_USER_WARNING:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            case E_USER_NOTICE:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            default:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;
        }

        // delete any files older than 30 days
        $files = glob($logfile_dir . "*");
        $now   = time();

        foreach ($files as $file)
            if (is_file($file))
                if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days)
                    unlink($file);

        return true;    // Don't execute PHP internal error handler
    }

    set_error_handler("error_handler");

    trigger_error("testing 1,2,3", E_USER_NOTICE);
?>

回答by vritika

Use below function

使用以下功能

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

以上函数将创建一个带有正确描述的登录文件 php_error 并发送电子邮件。