php發送log至syslog server

範例

<?php
function BSD_Syslog($msg,$severity=7, $program="php-test",$remote_ip='127.0.0.1',$remote_port=514){
  date_default_timezone_set('Asia/Taipei');
  $facility=5;
  $severity=7;
  $PRI = $facility*8+$severity;
  $HEADER=date('M d H:i:s ') . $program;
  $syslog_message = "<{$PRI}>{$HEADER} {$msg}";
  $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  socket_sendto($sock, $syslog_message, strlen($syslog_message), 0, $remote_ip, (int)$remote_port);
  socket_close($sock);
}
BSD_Syslog("test: ".rand()%10000);

其中facility的值如下:

         Code

          0             kernel messages
          1             user-level messages
          2             mail system
          3             system daemons
          4             security/authorization messages
          5             messages generated internally by syslogd
          6             line printer subsystem
          7             network news subsystem
          8             UUCP subsystem
          9             clock daemon
         10             security/authorization messages
         11             FTP daemon
         12             NTP subsystem
         13             log audit
         14             log alert
         15             clock daemon (note 2)
         16             local use 0  (local0)
         17             local use 1  (local1)
         18             local use 2  (local2)
         19             local use 3  (local3)
         20             local use 4  (local4)
         21             local use 5  (local5)
         22             local use 6  (local6)
         23             local use 7  (local7)

severity的值如下:


         Code
          0       Emergency: system is unusable
          1       Alert: action must be taken immediately
          2       Critical: critical conditions
          3       Error: error conditions
          4       Warning: warning conditions
          5       Notice: normal but significant condition
          6       Informational: informational messages
          7       Debug: debug-level messages

php 常用函式

mk_dir: 遞迴建立資料夾
ls: 遞迴取得所有檔案清單(不含目錄)

function mk_dir($dir, $mode = 0777){
  if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
  if (!mk_dir(dirname($dir),$mode)) return FALSE;
  return @mkdir($dir,$mode);
}

function ls($path,$loop=true){
  $items=[];
  $files=scandir($path);
  foreach($files as $item){
    if($item!="." && $item!=".."){
      $file="${path}/${item}";
      if(is_dir($file) && $loop){
        $items=array_merge($items,ls($file));
      }
      else if(is_file($file)){
        $items[]=($file); //realpath
      }
    }
  }
  return $items;
}

[code] post

function post($url, $post){
  $context = array();
  if (is_array($post)){
    ksort($post);
    $context['http'] = array(
      'method' => 'POST',
      'content' => http_build_query($post, '', '&')
    );
  }
  else{
    $context['http'] = array(
      'method' => 'POST',
      'content' => $post
    );
  }
  return @file_get_contents($url, false, stream_context_create($context));
}

MongoDB Replica Set高可用性的建置

  1. 建立三個MongoDB
echo "[info] 建立測試環境";
docker network create mongo-cluster >/dev/null 2>&1
docker rm -f mongo1 mongo2 mongo3 >/dev/null 2>&1
for i in 1 2 3
do
  echo "       mongo${i} 建立"
  docker run \
    -d \
    -p 3000$i:27017 \
    --name mongo$i \
    --net mongo-cluster \
    mongo mongod --replSet my-mongo-set >/dev/null 2>&1
done
  1. 接著設定三者關係,並強制設定electionTimeoutMillis為500ms.
echo "       設定mongo cluster"
docker exec -it mongo3 mongo --eval "config={\"_id\":\"my-mongo-set\",\"members\":[{\"_id\":0,\"host\":\"mongo1:27017\"},{\"_id\":1,\"host\":\"mongo2:27017\"},{\"_id\":2,\"host\":\"mongo3:27017\"}],\"settings\": { \"electionTimeoutMillis\": 500 }}; rs.initiate(config)"
  1. PHP測試
#https://github.com/mongodb/mongo-php-library
require_once __DIR__ . "/vendor/autoload.php";

try{
  $client = new MongoDB\Client("mongodb://mongo1:27017,mongo2:27017,mongo3:27017",[],[
    'typeMap' => [
      'array' => 'array',
      'document' => 'array',
      'root' => 'array',
    ],
  ]);
  $db = $client->selectDatabase('test');
  $cursor = $db->command(['isMaster' => 1]);
  echo "[info] 成功連線至: {$cursor->toArray()[0]['primary']}\n";

} catch(Exception $e) {
  echo "[error] 無法線連\n";
  exit;
}

{  //若Collection:testA不存在則建立.
  if((iterator_count($db->listCollections([
    'filter'=>[
      'name'=>'testA'
    ]
  ])))==0) //當數量為0時,建立testA
    $db->createCollection('testA');
}

//連線至Collection:testA
$collection=$db->selectCollection('testA');

//若沒有任何資料,則建立100則隨機資料
if($collection->count()==0){
  for($i=0;$i<100;$i++){
    $insertOneResult = $collection->insertOne([
      'idx' => $i,
      'value' => "{$i}, rand: ".rand(0,9999),
    ]);
  }
}

//取得最後三筆資料
foreach($collection->find([],[
  'limit' => 3,
  'projection' => ['_id'=>0],
  'sort' => [
    'idx'=>-1
  ]
]) as $rs){
  echo "\tidx:{$rs['idx']}\tvalue:{$rs['value']}\n";
}

php.ini 常見設定

php.ini檔案位置/etc/php5/apache2/php.ini
php-fpm檔案位置/etc/php5/fpm/php.ini
而php cli位置應該是在 /etc/php5/cli/php.ini

sudo vim /etc/php5/apache2/php.ini
# or
sudo vim /etc/php5/fpm/php.ini
# or
sudo vim /etc/php5/cli/php.ini

可以用下列指令確認

php -i |grep php\.ini

我個人常用的設定為(for debug):

short_open_tag=On
memory_limit=2000M
error_reporting=E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_STRICT
display_error=On
post_max_size=20000M
upload_max_filesize=20000M
max_file_uploads=200

其中,memory_limit > post_max_size > upload_max_filesize

修改之後,得要重新啟動apache2

sudo /etc/init.d/apache2 restart
# or
sudo service apache2 restart

vim 快速修改方式:

#for apache2
sudo vim /etc/php5/apache2/php.ini
:1,$s/short_open_tag\ =\ Off/short_open_tag\ =\ On/g
:1,$s/memory_limit\ =\ 128M/memory_limit\ =\ 2000M/g
:1,$s/display_errors\ =\ Off/display_errors\ =\ On/g
:1,$s/post_max_size\ =\ 8M/post_max_size\ =\ 2000M/g
:1,$s/upload_max_filesize\ =\ 2M/upload_max_filesize\ =\ 2000M/g
:1,$s/max_file_uploads\ =\ 20/max_file_uploads\ =\ 200/g
/error_reporting
/
:1,$s/error_reporting\ =\ E_ALL\ &\ \~E_DEPRECATED\ &\ \~E_STRICT//g
aerror_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_STRICT
#for cli
sudo vim /etc/php5/cli/php.ini
:1,$s/short_open_tag\ =\ Off/short_open_tag\ =\ On/g
:1,$s/memory_limit\ =\ 128M/memory_limit\ =\ 2000M/g
:1,$s/display_errors\ =\ Off/display_errors\ =\ On/g
:1,$s/post_max_size\ =\ 8M/post_max_size\ =\ 2000M/g
:1,$s/upload_max_filesize\ =\ 2M/upload_max_filesize\ =\ 2000M/g
:1,$s/max_file_uploads\ =\ 20/max_file_uploads\ =\ 200/g
/error_reporting
/
:1,$s/error_reporting\ =\ E_ALL\ &\ \~E_DEPRECATED\ &\ \~E_STRICT//g
aerror_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_STRICT