How to create rotating log file with Laravel and Monlog

北城以北 提交于 2019-12-12 18:01:37

问题


I'm trying to create my own rotating log file in Laravel using Monolog, however, the file rotation is not working and I don't know why.

I've created an artisan command that runs once per day, and keeps a log of it's activity. I want old versions of this file to be deleted after 2 days. In other words only the log of today's run, as well as yesterday's run should exist.

At the beginning of my artisan command, I have the following code:

$log = new Logger('MyCustomLog');
$log->pushHandler(new RotatingFileHandler(storage_path().'/logs/mycustomlog.log'), 2);

Then, throughout the command, I log information to it:

$log->addInfo('Info to log');

It seemed pretty straightforward to me, but it's simply not working. The log files are being generated correctly, but they are never getting deleted. I see the following in my app/storage/logs folder:

mycustomlog-2015-01-30.log
mycustomlog-2015-01-31.log
mycustomlog-2015-02-01.log
mycustomlog-2015-02-02.log
mycustomlog-2015-02-03.log

I would expect to see only the last 2 files. What am I doing wrong here?


回答1:


One of your bracket did get a bit out of place. You have to pass the number of log files to the constructor of RotatingFileHandler and not as second argument to pushHandler():

$log->pushHandler(new RotatingFileHandler(storage_path().'/logs/mycustomlog.log', 2));
//                                                                                ^


来源:https://stackoverflow.com/questions/28315352/how-to-create-rotating-log-file-with-laravel-and-monlog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!