ログ情報

log_message() メソッドを使うとローカルのログファイルにログを記録することができます。第1引数にはエラーの "レベル" を指定しなければなりません。メッセージの種類を表すものです(debug、error、など)。 第2引数はメッセージそのものです:

if ($some_var == '')
{
        log_message('error', 'some変数に値がありません。');
}

RFC 5424 に対応する8つのレベルが用意されています。次のものです:

  • debug - Detailed debug information.
  • info - Interesting events in your application, like a user logging in, logging SQL queries, etc.
  • notice - Normal, but significant events in your application.
  • warning - Exceptional occurrences that are not errors, like the use of deprecated APIs, poor use of an API, or other undesirable things that are not necessarily wrong.
  • error - Runtime errors that do not require immediate action but should typically be logged and monitored.
  • critical - Critical conditions, like an application component not available, or an unexpected exception.
  • alert - Action must be taken immediately, like when an entire website is down, the database unavailable, etc.
  • emergency - The system is unusable.

ログ記録の仕組みはシステム管理者またはサイト管理者へのイベント発生時緊急通知の方法を提供するものではありません。ただただログを記録するだけです。上記に説明したような critical レベル以上のイベントの多くは Error Handler により発生します。

設定

You can modify which levels are actually logged, as well as assign different Loggers to handle different levels, within the /app/Config/Logger.php configuration file.

設定ファイルの threshold 値(しきい値)はアプリケーションでログ記録するレベルを決定します。アプリケーションでどのようなレベルのログを要求しようとも、しきい値を超えていなければ無視されます。これの一番単純な使い方は、ログ記録したい最小レベルの値を設定することです。例えば、debug メッセージを記録したく、info メッセージを記録したくない場合、threshold は 5 に設定します[訳注: RFC 5424に定義されているseverityとここで定義しているレベル値は異なるものです。レベル定義は設定ファイルのコメントをご覧ください]。Any log requests with a level of 5 or less (which includes runtime errors, system errors, etc) would be logged and info, notices, and warnings would be ignored:

public $threshold = 5;

A complete list of levels and their corresponding threshold value is in the configuration file for your reference.

You can pick and choose the specific levels that you would like logged by assigning an array of log level numbers to the threshold value:

// Log only debug and info type messages
public $threshold = [5, 8];

Using Multiple Log Handlers

The logging system can support multiple methods of handling logging running at the same time. Each handler can be set to handle specific levels and ignore the rest. Currently, two handlers come with a default install:

  • File Handler is the default handler and will create a single file for every day locally. This is the recommended method of logging.
  • ChromeLogger Handler If you have the ChromeLogger extension installed in the Chrome web browser, you can use this handler to display the log information in Chrome's console window.

The handlers are configured in the main configuration file, in the $handlers property, which is simply an array of handlers and their configuration. Each handler is specified with the key being the fully name-spaced class name. The value will be an array of varying properties, specific to each handler. Each handler's section will have one property in common: handles, which is an array of log level names that the handler will log information for.

public $handlers = [

        //--------------------------------------------------------------------
        // File Handler
        //--------------------------------------------------------------------

        'CodeIgniter\Log\Handlers\FileHandler' => [

                'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
        ]
];

Modifying the Message With Context

You will often want to modify the details of your message based on the context of the event being logged. You might need to log a user id, an IP address, the current POST variables, etc. You can do this by use placeholders in your message. Each placeholder must be wrapped in curly braces. In the third parameter, you must provide an array of placeholder names (without the braces) and their values. These will be inserted into the message string:

// Generates a message like: User 123 logged into the system from 127.0.0.1
$info = [
        'id' => $user->id,
        'ip_address' => $this->request->ip_address()
];

log_message('info', 'User {id} logged into the system from {ip_address}', $info);

If you want to log an Exception or an Error, you can use the key of 'exception', and the value being the Exception or Error itself. A string will be generated from that object containing the error message, the file name and line number. You must still provide the exception placeholder in the message:

try
{
        ... Something throws error here
}
catch (\Exception $e)
{
        log_message('error', '[ERROR] {exception}', ['exception' => $e]);
}

Several core placeholders exist that will be automatically expanded for you based on the current page request:

Placeholder Inserted value
{post_vars} $_POST variables
{get_vars} $_GET variables
{session_vars} $_SESSION variables
{env} Current environment name, i.e. development
{file} The name of file calling the logger
{line} The line in {file} where the logger was called
{env:foo} The value of 'foo' in $_ENV

Using Third-Party Loggers

You can use any other logger that you might like as long as it extends from either Psr\Log\LoggerInterface and is PSR3 compatible. This means that you can easily drop in use for any PSR3-compatible logger, or create your own.

You must ensure that the third-party logger can be found by the system, by adding it to either the /app/Config/Autoload.php configuration file, or through another autoloader, like Composer. Next, you should modify /app/Config/Services.php to point the logger alias to your new class name.

Now, any call that is done through the log_message() function will use your library instead.

LoggerAware Trait

If you would like to implement your libraries in a framework-agnostic method, you can use the CodeIgniter\Log\LoggerAwareTrait which implements the setLogger() method for you. Then, when you use your library under different environments for frameworks, your library should still be able to log as it would expect, as long as it can find a PSR3 compatible logger.