How to log messages to a file in Laravel?
Sep 21, 2025 am 06:04 AMLaravel uses Monolog to log messages via the Log facade, with default logs stored in storage/logs/laravel.log. Configure channels in config/logging.php to control output; the default stack channel aggregates multiple handlers like single, which writes to a file. Use Log::info(), Log::warning(), or Log::error() to record messages with context. Customize log paths by modifying the path option under the single channel or create new channels (e.g., payment) for separate files. For log rotation, switch the driver to daily and set retention days. Ensure the storage/logs directory is writable. Example: Log::channel('payment')->info('Payment processed') writes to payment.log if configured.
In Laravel, logging messages to a file is straightforward thanks to the built-in Monolog-based logging system. By default, Laravel logs messages to a file located at storage/logs/laravel.log. You can customize this behavior or write custom logs easily using Laravel's Log facade.
Using the Log Facade
Laravel provides a Log facade that allows you to write messages at different log levels such as debug, info, warning, error, etc.
- debug(): For debugging information
- info(): For general informational messages
- warning(): For non-critical warnings
- error(): For critical errors
Example usage in a controller or anywhere in your application:
use Illuminate\Support\Facades\Log; Log::info('User login attempt', ['user_id' => $userId]); Log::warning('Slow database query detected'); Log::error('Database connection failed', ['exception' => $exception]);
Configuring File Logging
The logging channel used by Laravel is defined in config/logging.php. The default channel is usually set to stack, which can aggregate multiple channels.
To ensure logs go to a file, check that your default channel uses the single driver (which logs to a file):
'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], ],
You can change the path value to log to a different file, for example:
'path' => storage_path('logs/custom.log'),
Creating Custom Log Files
If you want to log specific messages to a separate file (e.g., payment.log), define a new channel in config/logging.php:
'payment' => [ 'driver' => 'single', 'path' => storage_path('logs/payment.log'), 'level' => 'debug', ],
Then use it in your code:
Log::channel('payment')->info('Payment processed', ['amount' => $amount]);
Log Rotation and Maintenance
Laravel doesn’t handle log rotation by default, but you can use tools like logrotate on Linux or configure daily log files:
'single' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 14, // Keep logs for 14 days ],
This creates daily log files like laravel-2025-04-05.log.
Basically just use Log::method() with proper configuration, and Laravel handles the rest. Make sure the storage/logs directory is writable to avoid errors.
The above is the detailed content of How to log messages to a file in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6
