V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
chen1367784103
V2EX  ›  PHP

一个简单的一批的 PHP 日志方法,带所有详细参数,带文件位置和行号,欢迎拍砖

  •  
  •   chen1367784103 · 2018-11-12 11:24:04 +08:00 · 3062 次点击
    这是一个创建于 2211 天前的主题,其中的信息可能已经有所发展或是发生改变。

    封装了一个好用的 PHP 记录日志的方法; 日志位置已经制定到项目根目录下的 runtime/logs

       /**
         * @author chenjianhua https://dyoung.unnnnn.com
         * @param string $text
         * @param string $type
         * @param string $fileDir
         * @param string $inFile
         * @param int $inLine
         */
        function GlobalLog($text = '', $type = 'info', $fileDir = '/runtime/logs', $inFile = __FILE__, $inLine = __LINE__)
        {
            function getClientIp($type = 0)
            {
                $type = $type ? 1 : 0;
                static $ip = null;
                if (null !== $ip) {
                    return $ip[$type];
                }
    
                if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                    $pos = array_search('unknown', $arr);
                    if (false !== $pos) {
                        unset($arr[$pos]);
                    }
    
                    $ip = trim($arr[0]);
                } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                    $ip = $_SERVER['REMOTE_ADDR'];
                }
                // IP 地址合法验证
                $long = sprintf("%u", ip2long($ip));
                $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
                return $ip[$type];
            }
    
            $rootDir = realpath($_SERVER['DOCUMENT_ROOT'] . '/../');
            $fileDir = $rootDir . $fileDir;
            if (!file_exists($fileDir)) {
                mkdir($fileDir, 755);
            }
            $userIp = getClientIp(0);
            $message = date('Y-m-d H:i:s') . "[$userIp][$type]" . $text . ' in ' . $inFile . ':' . $inLine . PHP_EOL;
            $message .= '\'参数 $_GET:\'' . json_encode($_GET, 256) .
                '\'$_POST:\'' . json_encode($_POST) .
                '\'$_FILES\'' . json_encode($_FILES, 256) .
                '\'$_COOKIE\'' . json_encode($_COOKIE, 256) .
                '\'$_SESSION\'' . json_encode($_SESSION, 256) .
                '\'$_SERVER\'' . json_encode($_SERVER, 256);
            $message .= PHP_EOL;
            $fileName = $fileDir . '/' . date('Y-m-d') . '-' . $type . '.log';
            file_put_contents($fileName, $message, FILE_APPEND);
        }
    
    

    直接调用方法即可 例如:

    GlobalLog("调试信息!!");
    

    文件中的内容是

    2018-11-12 11:18:54[127.0.0.1][info]调试信息!! in D:\phpStudy\PHPTutorial\WWW\matchu-wms\common\Tools.php:450
    '参数 $_GET:'[]'$_POST:'[]'$_FILES'[]'$_COOKIE'{"__guid":"96992031.495941022341931140.1540295539495.9597","PHPSESSID":"tuqcu84olgs7jhf1anoil1iquo","_csrf":"08ed0c7dc6d0ac8bbd9a2301d7db90015fdd389ee5213ecb6fff2fd65be2ac63a:2:{i:0;s:5:\"_csrf\";i:1;s:32:\"znLFW8ooN2BC-zEeG1wAMP4-ZJqyQwQZ\";}","monitor_count":"42"}'$_SESSION'{"__flash":[]}'$_SERVER'{"ALLUSERSPROFILE":"C:\\ProgramData","APPDATA":"C:\\Users\\Administrator\\AppData\\Roaming","asl_log":"Destination=file","CommonProgramFiles":"C:\\Program Files (x86)\\Common Files","CommonProgramFiles(x86)":"C:\\Program Files (x86)\\Common Files","CommonProgramW6432":"C:\\Program Files\\Common Files","COMPUTERNAME":"X7V0YTI6M4WWWYL","ComSpec":"C:\\Windows\\system32\\cmd.exe","FP_NO_HOST_CHECK":"NO","HOMEDRIVE":"C:","HOMEPATH":"\\Users\\Administrator","LOCALAPPDATA":"C:\\Users\\Administrator\\AppData\\Local","LOGONSERVER":"\\\\X7V0YTI6M4WWWYL","NUMBER_OF_PROCESSORS":"4","OS":"Windows_NT","Path":"C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\TortoiseGit\\bin;D:\\php_study\\PHPTutorial\\php\\php-5.6.27-nts;D:\\compose;C:\\Python27;D:\\phpStudy\\PHPTutorial\\php\\php-7.2.1-nts;D:\\phpStudy\\PHPTutorial\\MySQL\\bin;C:\\Program Files\\nodejs\\;C:\\Program Files\\MySQL\\MySQL Utilities 1.6\\;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Redis\\;C:\\bin;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Administrator\\AppData\\Roaming\\Composer\\vendor\\bin;C:\\Users\\Administrator\\AppData\\Roaming\\npm;C:\\bin","PATHEXT":".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC","PROCESSOR_ARCHITECTURE":"x86","PROCESSOR_ARCHITEW6432":"AMD64","PROCESSOR_IDENTIFIER":"Intel64 Family 6 Model 158 Stepping 9, GenuineIntel","PROCESSOR_LEVEL":"6","PROCESSOR_REVISION":"9e09","ProgramData":"C:\\ProgramData","ProgramFiles":"C:\\Program Files (x86)","ProgramFiles(x86)":"C:\\Program Files (x86)","ProgramW6432":"C:\\Program Files","PROMPT":"$P$G","PSModulePath":"C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\","PUBLIC":"C:\\Users\\Public","SESSIONNAME":"Console","SystemDrive":"C:","SystemRoot":"C:\\Windows","TEMP":"C:\\Users\\ADMINI~1\\AppData\\Local\\Temp","TMP":"C:\\Users\\ADMINI~1\\AppData\\Local\\Temp","USERDOMAIN":"X7V0YTI6M4WWWYL","USERNAME":"Administrator","USERPROFILE":"C:\\Users\\Administrator","WEBKIT_IGNORE_SSL_ERRORS":"1","windir":"C:\\Windows","windows_tracing_flags":"3","windows_tracing_logfile":"C:\\BVTBin\\Tests\\installpackage\\csilogfile.log","_DFX_INSTALL_UNSIGNED_DRIVER":"1","HTTP_COOKIE":"__guid=96992031.495941022341931140.1540295539495.9597; PHPSESSID=tuqcu84olgs7jhf1anoil1iquo; _csrf=08ed0c7dc6d0ac8bbd9a2301d7db90015fdd389ee5213ecb6fff2fd65be2ac63a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22znLFW8ooN2BC-zEeG1wAMP4-ZJqyQwQZ%22%3B%7D; monitor_count=42","HTTP_ACCEPT_LANGUAGE":"zh-CN,zh;q=0.9","HTTP_ACCEPT_ENCODING":"gzip, deflate, br","HTTP_DNT":"1","HTTP_ACCEPT":"text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8","HTTP_USER_AGENT":"Mozilla\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/63.0.3239.132 Safari\/537.36","HTTP_UPGRADE_INSECURE_REQUESTS":"1","HTTP_CACHE_CONTROL":"max-age=0","HTTP_CONNECTION":"keep-alive","HTTP_HOST":"127.0.0.1:8081","REDIRECT_STATUS":"200","SERVER_NAME":"127.0.0.1","SERVER_PORT":"8081","SERVER_ADDR":"127.0.0.1","REMOTE_PORT":"53792","REMOTE_ADDR":"127.0.0.1","SERVER_SOFTWARE":"nginx\/1.11.5","GATEWAY_INTERFACE":"CGI\/1.1","SERVER_PROTOCOL":"HTTP\/1.1","DOCUMENT_ROOT":"D:\\phpStudy\\PHPTutorial\\WWW\\matchu-wms\\web","DOCUMENT_URI":"\/index.php","REQUEST_URI":"\/test\/log","SCRIPT_NAME":"\/index.php","CONTENT_LENGTH":"","CONTENT_TYPE":"","REQUEST_METHOD":"GET","QUERY_STRING":"","PATH_TRANSLATED":"D:\\phpStudy\\PHPTutorial\\WWW\\matchu-wms\\web","PATH_INFO":"","SCRIPT_FILENAME":"D:\\phpStudy\\PHPTutorial\\WWW\\matchu-wms\\web\/index.php","FCGI_ROLE":"RESPONDER","PHP_SELF":"\/index.php","REQUEST_TIME_FLOAT":1541992734.9089999,"REQUEST_TIME":1541992734}
    
    

    日志文件存在于 你的项目根目录下的 runtime/log/2018-11-12-info.logs 默认你的部署文件入口在项目文件夹 /web 或者在项目文件夹 /public

    6 条回复    2018-11-12 17:38:07 +08:00
    lihongjie0209
        1
    lihongjie0209  
       2018-11-12 12:00:18 +08:00
    so, PHP 都没有日志需要自己封装?
    ben1024
        2
    ben1024  
       2018-11-12 12:29:02 +08:00
    这个写法很像 ThinkPHP,ThinkPHP 有自己的日志的。
    推荐下 monolog/monolog
    zn
        3
    zn  
       2018-11-12 12:33:11 +08:00 via iPhone
    简单粗暴,但是并不好用。
    8355
        4
    8355  
       2018-11-12 15:16:59 +08:00
    @lihongjie0209 #1 大哥求别喷 php
    hefish
        5
    hefish  
       2018-11-12 15:17:13 +08:00
    感觉还是 monolog 好些。 我喜欢他的 RotateFileLog。按日期存放的日志文件。
    另外很多时候,要日志的并非是_POST, _GET 之类的参数,所以没必要把每次的请求都记录下来。还是作为可选参数的好些。
    chen1367784103
        6
    chen1367784103  
    OP
       2018-11-12 17:38:07 +08:00
    @lihongjie0209 大钢筋!!!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   999 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 22:57 · PVG 06:57 · LAX 14:57 · JFK 17:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.