Asaf
Asaf

Reputation: 8206

YII log separate file name for every class

I want to be able to have for every class its own .log file.
I don't want to do this manually in the config/main.php file but to somehow
send it to the log function with another parameter, is that possible (perhaps inherit it somehow)?

Upvotes: 0

Views: 1038

Answers (2)

Jon
Jon

Reputation: 437424

You can do that, but you will need to write some code. Specifically, you will have to:

Create your own implementation of CLogRoute

The standard CFileLogRoute writes log messages to a single file. It shouldn't be difficult to adapt the code and write your own e.g. OneFilePerClassLogRoute that does what you need. For example, the implementation of the processLogs method starts with

protected function processLogs($logs)
{
    $logFile=$this->getLogPath().DIRECTORY_SEPARATOR.$this->getLogFile();
    // ...
{

The parameter $logs is an array; each item is an array that contains four pieces of information (you can see what they are if you look at formatLogMessage). One of these is the "category" of each message. You can use class names for categories and make processLogs write each message to a separate file based on its category (i.e. which class it is related to).

Pass the necessary information to the logger

Of course to do that, you need to pass the current class name as the category for each log message. Luckily, this is very easy using the __CLASS__ magic constant:

Yii::log($message, $level, __CLASS__);

Configure Yii to use your log route

Finally, don't forget to configure Yii with your custom log route as shown in the documentation. Depending on how you write your log route class, it might look something like this:

'log'=>array(
    'class'=>'CLogRouter',
    'routes'=>array(
        array(
            'class'=>'MyCustomLogRoute',
            'logPath'=>'where_your_logs_will_be_saved',
            //...other options for your custom route here...
        ),
        // ...other routes here...
    ),
),

Upvotes: 1

Samuel Liew
Samuel Liew

Reputation: 79042

The closest you can get is to extend CLogFilter to add in additional information about the current class/file name into the log.

http://www.yiiframework.com/doc/guide/1.1/en/topics.logging#logging-context-information

Upvotes: 0

Related Questions