thinkphp项目中日志记录实现代码

发布时间:2019-12-09编辑:脚本学堂
在thinkphp项目开发中实现日志记录功能,有关thinkphp项目中日志表的建立与数据库操作方法,感兴趣的朋友参考下。

thinkphp日志记录用法

1、建立日志表
 

复制代码 代码示例:
CREATE TABLE `logs` ( 
  `id` int(11) NOT NULL auto_increment, 
  `guid` varchar(100) character set utf8 NOT NULL, 
  `addtime` timestamp NOT NULL default CURRENT_TIMESTAMP, 
  `account` varchar(100) character set utf8 NOT NULL, 
  `nickname` varchar(100) character set utf8 NOT NULL, 
  `app` varchar(100) character set utf8 NOT NULL, 
  `action` varchar(100) character set utf8 NOT NULL, 
  `method` varchar(100) character set utf8 NOT NULL, 
  `query_string` text character set utf8 NOT NULL, 
  `is_desc` varchar(100) character set utf8 NOT NULL, 
  `desc` varchar(100) character set utf8 NOT NULL, 
  `ipaddr` varchar(100) character set utf8 NOT NULL, 
  `unique_flag` varchar(100) character set utf8 NOT NULL, 
  PRIMARY KEY  (`id`) 
) ENGINE=innodb  DEFAULT CHARSET=utf8 ;

2、Common/common.php中方法定义:
 

复制代码 代码示例:
function getGlobalSkypeLogDbConfig() { 
 $global_skype_db_config = array( 
     'dbms'          => C('DB_TYPE'), 
     'username' => C('DB_USER'), 
     'password' => C('DB_PWD'), 
     'hostname' => C('DB_HOST'), 
     'database'   => C('DB_NAME'), 
 ); 
 return $global_skype_db_config; 

 
function addOperationLog($desc=NULL, $unique_flag='system', $app=APP_NAME, $action=MODULE_NAME, $method=ACTION_NAME) { 
 $global_skype_db_config = getGlobalSkypeLogDbConfig(); 
 static $global_skype_log_db_conn; 
 if (!$global_skype_log_db_conn) { 
  $global_skype_log_db_conn = mysql_connect($global_skype_db_config['hostname'], $global_skype_db_config['username'], $global_skype_db_config['password']); 
 } 
 if (!$global_skype_log_db_conn) { 
  die('Mysql_Error:' . __FILE__ . '|' . __LINE__ . '|' . mysql_error()); 
 } 
 mysql_query('use ' . $global_skype_db_config['database'], $global_skype_log_db_conn); 
 mysql_query('set names utf8 ', $global_skype_log_db_conn); 
 
 $account = getAdminAccount(); 
 $nickname = getAdminNickname(); 
 $user_id = getAdminUserId(); 
 $ipaddr = get_client_ip(); 
 $query_string = print_r(array_merge($_GET, $_POST), true); 
 
 $desc = $desc; 
 $is_desc = 0; 
 $unique_flag = $unique_flag; 
 if ($desc) { 
  $is_desc = 1; 
 } 
 
 $insert_time = date('Y-m-d H:i:s'); 
 
 $query = "INSERT INTO `" . C('LOG_DB_TABLE') . "` (`guid`,`account`,`nickname`,`addtime`,`app`,`action`, 
    `method`,`query_string`,`is_desc`,`desc`,`ipaddr`,`unique_flag`) VALUES ('$user_id','$account','$nickname','$insert_time','$app', 
    '$action','$method','$query_string','$is_desc','$desc','$ipaddr','$unique_flag');"; 
 
 return mysql_query($query, $global_skype_log_db_conn); 

 
function getAdminAccount() { 
 return $_SESSION['loginAccount']; 

 
function getAdminNickname() { 
 return $_SESSION['loginUserName']; 

 
function getAdminUserId() { 
 return $_SESSION[C('USER_AUTH_KEY')]; 
}

在其它操作类中调用addOperationLog();就可以了。