Home > Backend Development > PHP Tutorial > A simple example of log output to file and database in yii2

A simple example of log output to file and database in yii2

黄舟
Release: 2023-03-15 14:20:01
Original
1287 people have browsed it

Edit config/web.php

First the log must be enabled


    'bootstrap' => [
        'log'
    ],
Copy after login

[file]


##

    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'exportInterval' => 1,
                ],
            ],
        ],
Copy after login

The default output is to runtime/logs/app.log

Note that the webserver or console user must have permission to write to the file

[database]


        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\DbTarget',
                    'levels' => ['error', 'warning', 'trace'],
                ]
            ]
        ],
Copy after login

The default output is the {{%log}} table under the database corresponding to the db component

Run the following command in the yii2 root directory to generate the corresponding table schema


./yii migrate --migrationPath=@yii/log/migrations/
Copy after login

Note that config/console.php must also have the same configuration as web.php, otherwise the command execution will not be successful.

You can also configure different log modes according to different environments


    'components' => [
        'log' => [
            'traceLevel' => YII_ENV == 'dev' ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\DbTarget',
                    'levels' => YII_DEBUG ? ['error', 'warning', 'trace'] : ['error'],
                ],
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => YII_DEBUG ? ['error', 'warning', 'trace'] : ['error', 'warning'],
                ],
            ],
        ],
    ],
Copy after login

The above is the detailed content of A simple example of log output to file and database in yii2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template