Default create log files with 664 permissions - laravel

How can I configure my Laravel or Ubuntu server so my Laravel logger creates a log file with the 664 permissions? Right now it defaults to 644.

Open config\logging.php file and add permission key to your default log channel. Is seems that this feature is available from Laravel 5.6.10.
Example:
return [
'channels' => [
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'permission' => 0664, // this is the new key to add
],
],
];
Notes:
in this example the default log channel is single
make sure the permission key has the value without quotes and with leading zero. read more about this in php manual of chmod

Related

How to create multiple log files in laravel?

Like the state itself, I want to create multiple Log files for different processes.
I am using Laravel-8.
I have also created the 1 logging file with the help of logging.php in the config folder.
I want to keep track of my created commands with their own separate log file.
How can I create my separate log file for that commands?
I did this by having only a log for daily. "config/logging.php"
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
]...,
]
You should use config/logging.php to create custom channel for each command
e.g.
'CHANNEL_NAME' => [
'driver' => 'single',
'path' => storage_path('logs/LOG_FILE_NAME.log'),
'level' => 'DESIRED_LEVEL',
],
and change CHANNEL_NAME, LOG_FILE_NAME and DESIRED_LEVEL values as you want.
Note: 'level' => 'DESIRED_LEVEL' is optional. it can be single level or array of levels (laravel v8.x).
Then when you want to log anything in your command class, Log like following code
Usage:
Log::channel('CHANNEL_NAME')
->info('Something happened!');
Below code will generate custom log file.
try{
//Your code here
}catch(\Exception $e){
$cusLog = new Logger('stack');
$err_file_name = $task_id."_".time();
$syncHistory['file_name'] = $err_file_name;
$cusLog->pushHandler(new StreamHandler(storage_path('logs/'.$err_file_name.'.log')), Logger::INFO);
$cusLog->info('error', ['Exception'=>$e->getTraceAsString(),'message'=>$e->getMessage()]);
}
Hope this will be useful.

How do I make Laravel write a log showing my problem?

I'm writing my first Laravel app that also includes Vue. I'm pretty new to both Laravel and Vue so please be gentle ;-) I'm using Laravel 8.4.x and Vue 2.6.12 on Windows 10.
In my very first axios invocation, I'm trying to write of a single record to a database table in a submit method of my Vue component, I'm getting Http status code 500, internal server error. The response in the console says that Laravel doesn't see a controller with the name ToDoController. I have no idea why that would be since I created it properly with php artisan and I can see it in VS Code.
In looking at other posts to try to understand this problem, I see that people recommend looking in the server logs to find out more information. I'm not sure if the logs will have information not found in the response situated in the browser console but I won't know until I look at it. The problem is that I don't know where to look for my log.
According to the Laravel docs, logging is governed by config/logging.php and that file says:
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
If I'm understanding this correctly, that means that errors at DEBUG or above are being written to logs/laravel.log, which I should be seeing in VS Code. But I do not even have a logs directory, let alone a laravel.log file.
Do I need to do something to create these logs in the first place as part of creating a new project? If so, what? If not, why don't I see my log? A server error is significant enough to get written into the log, right?
Also, while we're on the subject of logs, I have a chicken and egg question: does the value of LOG_CHANNEL in the logging.php file get set from the .env file or does the .env file get the value in the logging.php file? In other words, if I want to change my logging behaviour, which one do I alter?
The logs directory is located in the storage directory. So it's storage/logs/laravel.log.
Also, you can choose to log anything you want to using the Log facade. See laravel writing log messages [https://laravel.com/docs/8.x/logging#writing-log-messages]. Anything that is wrapped in the env() function is being pulled from the env file. The second param allows you to set a default if that value is not set or available in the env file. 1
#Donkarnash - I strongly suspect you've identified the problem. I'm not up on the new features of Laravel 8. What would my Route look like if I have a FQCN for the controller? I've tried all the variations I can think of but nothing works, including url('app/Http/Controllers/ToDoController')
Since Laravel 8 the default namespace App\Http\Controllers is not set in the RouteServiceProvider - which is a welcome change.
So now when defining routes in routes files say routes/web.php FQCN of the controller must be used
use App\Http\Controllers\ToDoController;
Route::get('/todos', [ToDoController::class, 'index']);
//OR without importing the use statement
Route::get('/todos', [\App\Http\Controllers\ToDoController::class, 'index']);
If you want you can also use namespace method for route groups
Route::namespace('App\Http\Controllers')
->group(function(){
Route::get('/todos', 'ToDoController#index');
Route::get('/todos/{todo}', 'ToDoController#show');
});
Using FQCN as in either importing use statement or inline also provides benefits of easy navigation and code suggestions in IDE's
To revert back to the old convention and set default namespace you should declare
$namespace in RouteServiceProvider
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* #var string|null
*/
protected $namespace = 'App\\Http\\Controllers';

Laravel store files with permissions 774

Im loosing mind. I upload files via laravel API, they are stored in folder and file always get permission 644, is there any way how to store files as 775 ?
can i somehow add this to my function ?
(0755, true, true)
function for store files:
$result=$request->file('file_path')->store('apiFiles/'.$idParameter);
thanks for any help
In laravel you can use 'public' or 'private' disks and set the permissions options in the config file filesystems.php
https://laravel.com/docs/8.x/filesystem#permissions
The public visibility translates to 0755 for directories and 0644 for files. You can modify the permissions mappings in your filesystems configuration file:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'permissions' => [
'file' => [
'public' => 0664,
'private' => 0600,
],
'dir' => [
'public' => 0775,
'private' => 0700,
],
],
],
You can then store files with specific visibility like it suggests here https://laravel.com/docs/8.x/filesystem#file-visibility
Or you can use the built in php function chmod()
https://www.php.net/manual/en/function.chmod.php
you can change permission of file after creating them by chmod command like this:
$result=$request->file('file_path')->store('apiFiles/'.$idParameter);
chmod('file path',0775);

Laravel upload via FTP prevent overriding live logs

I am updating my laravel project via FTP.
I set override all files, where edit date changed.
Problem:
It overrides the live logs with the dev logs, because the name of the log file is the same.
I wanted to change log names (could save it in .env, because live project has its own .env), but I have not found a way to do it.
Any other ideas?
Just exclude logs file/dir when copying files instead of overriding it?
Here is my solution.
Go to logging.php and edit this condig:
'single' => [
'driver' => 'single',
//'path' => storage_path('logs/laravel.log'),
'path' => storage_path(env('LOG_PATH')),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
//'path' => storage_path('logs/laravel.log'),
'path' => storage_path(env('LOG_PATH')),
'level' => 'debug',
'days' => 14,
]
Because the live project has a different .env, you can define a different folder or filename and it will work.

Laravel Storage SFTP and uploaded files permissions

I'm using Storage:SFTP (league/flysystem-sftp) to upload some files to an external server. Everything goes fine with a small issue: the files are uploaded with a 0644 (-rw-r--r--) permission. I've tried to use 'public' option on the put method as the example from docs, like
Storage::disk('remote-sftp')->put($filename, $contents, 'public');
but if fails returning FALSE and doesn't uploads the file.
If I remove the 'public' parameter, everything goes well but with the wrong permissions for file.
Is there any way to set the uploaded file permissions to something like 0666?
Finally the solution was a combination of Alpy's answer and configuration.
Calling setVisibility() went without failure, but keep permissions in 0644. Digging into the FTP/SFTP driver found that the 'public' permission has a pattern that can be assigned in config using 'permPublic' key, so writting in config/filesystems.php the desired octal permission it worked as spected.
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
'remote-sftp' => [
'driver' => 'sftp',
'host' => '222.222.222.222',
'username' => 'myuser',
'password' => 'mypassword',
'visibility' => 'public',
'permPublic' => 0766, /// <- this one did the trick
// 'port' => 22,
'root' => '/home',
// 'timeout' => 30,
],
],
];
File permissions are based on two factors. Visibility and Permissions. You can set these two options in the driver config as such:
'remote' => [
'driver' => 'sftp',
'host' => 'hostname',
'root' => '/',
'username' => 'user',
'password' => env('SYSTEM_PASS'),
'visibility' => 'public', // defaults to 'private'
'permPublic' => 0775
]
The permissions are set based on the visibility. So if you set 'permPublic' and don't set 'visibility' nothing will change as, the setVisibility() function uses 'visibility' to get the permissions.
vendor/league/flysystem-sftp/src/SftpAdapter.php
public function setVisibility($path, $visibility)
{
$visibility = ucfirst($visibility);
// We're looking for either permPublic or permPrivate
if (! isset($this->{'perm'.$visibility})) {
throw new InvalidArgumentException('Unknown visibility: '.$visibility);
}
$connection = $this->getConnection();
return $connection->chmod($this->{'perm'.$visibility}, $path);
}
The public default is 0755.
The private default is 0700.
umask
If 'visibility' is not set, I believe the permissions are set based on the remote system user's umask. You are able to modify this on the remote system, if you so choose. set umask for user
Directories
One thing to note while working with permissions is that this will only affect created files. To set the permissions on created directories, use the 'directoryPerm' attribute in your config.
This defaults to 0744
Here is a more global and efficient solution. I needed to control permission on Files and also directories when saving a file under recursive directories.
League SftpAdapter is creating the directories recursively if not exist yet. But the main problem is that, it won't add the permPublic => 0755 for directories, but only files, hence www-data user end up to have no access to the file if it's inside of a newly created directory. The solution is to dive in the code to see what's happening:
'disks' => [
'remote-sftp' => [
'driver' => 'sftp',
'host' => '222.222.222.222',
'port' => 22,
'username' => 'user',
'password' => 'password',
'visibility' => 'public', // set to public to use permPublic, or private to use permPrivate
'permPublic' => 0755, // whatever you want the public permission is, avoid 0777
'root' => '/path/to/web/directory',
'timeout' => 30,
'directoryPerm' => 0755, // whatever you want
],
],
In League\Flysystem\Sftp\StfpAdapter, there is 2 important attributes to see clearly:
/**
* #var array
*/
protected $configurable = ['host', 'hostFingerprint', 'port', 'username', 'password', 'useAgent', 'agent', 'timeout', 'root', 'privateKey', 'passphrase', 'permPrivate', 'permPublic', 'directoryPerm', 'NetSftpConnection'];
/**
* #var int
*/
protected $directoryPerm = 0744;
The $configurable is all possible keys to configure filesystem sftp driver above. You can change directoryPerm from 0744 to 0755 in config file:
'directoryPerm' => 0755,
HOWEVER, because there is kind a like a Bug in StfpAdapter https://github.com/thephpleague/flysystem-sftp/issues/81 that won't use the $config parameter on createDir:
$filesystem = Storage::disk('remote-sftp');
$filesystem->getDriver()->getAdapter()->setDirectoryPerm(0755);
$filesystem->put('dir1/dir2/'.$filename, $contents);
Or set it with public in purpose:
$filesystem->put('dir1/dir2/'.$filename, $contents, 'public');
I found this while looking for a solution and I think I've found what works in Laravel 9 after digging through the flysystem code.
Adding the following settings to my config looks to have done the trick.
'visibility' => 'public',
'permissions' => [
'file' => [
'public' => 0664,
'private' => 0664,
],
'dir' => [
'public' => 0775,
'private' => 0775,
],
],
Please try this:
Storage::disk('remote-sftp')->put($filename, $contents)->setVisibility( $filename, 'public');
assuming the filename is also having the path..
Storage::disk('sftp')->download(...

Resources