クリエイターブログ/システム開発

システム開発

【CodeIgniter】ログの分割

経緯

ログファイルはlog-2018-01-01.phpのような固定になってしまいますが、任意のファイル名に変更する方法を紹介します。
標準では日毎の出力となりますが、月毎への変更やアクセスログ用、エラーログ用などで出力ファイルを分けるなどができます。

CodeIgniterのバージョンは 3.1.6 をもとにしています。

CI_Logを継承しMY_Logの作成

CI_Logを継承して下記のMY_Logをapplication/core内に作成します。
「~ 省略 ~」部分はCI_Logのwrite_log関数からコピーをしてください。

application/core/MY_Log.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Log extends CI_Log
{
    protected $_log_basename = NULL;

    public function __construct()
    {
        parent::__construct();
        isset($this->_log_basename) OR $this->_log_basename = 'log-'.date('Y-m-d');
    }

    public function write_log($level, $msg)
    {

        ~ 省略 ~

        $filepath = $this->_log_path.$this->_log_basename.'.'.$this->_file_ext;
        $message = '';

        ~ 省略 ~

    }
}

Access_logの作成

例として、アクセスログを記録するクラスを紹介します。
先ほど作成したMY_Logを継承した、下記のAccess_logをapplication/core内に作成します。

$this->_log_basenameに設定したファイル名で出力されるようになり、下記の例では access-log-2018-01-01.phpのようなファイル名となります。
‘access-log-‘.date(‘Y-m’)とすることで、月毎への出力へ変更することもできます。

application/core/MY_Access_log.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH.'core/MY_Log.php';

class MY_Access_log extends MY_Log
{
    public function __construct()
    {
        parent::__construct();
        $this->_log_basename = 'access-'.$this->_log_basename;
        $this->_threshold = 3;
    }

    public function write_access()
    {
        $this->ci =& get_instance();

        // IPアドレス
        $ip = $this->ci->input->ip_address();

        // リクエストメソッド
        $request_method = $this->ci->input->method();

        // URI
        $uri_string = $this->ci->uri->uri_string();

        $log = sprintf('%15s %4s %s', $ip, $request_method, $uri_string);

        parent::write_log('info', $log, FALSE);
    }
}

Access_logの利用

アクセスログの取得方法は下記のように利用することができます。


$access_log =& load_class('Access_log', 'core');
$access_log->write_access();

まとめ

ログファイルについては日毎で出力しておき、サーバーサイドで月毎にまとめるといったことをすることも可能ですが、紹介した方法では比較的簡単にできるので楽に済ませたい場合におすすめです。

最新記事

クリエイターブログの関連リンク