I want to add to my Lumen project a daily Log.
I try this in the app.php (Folder Bootstrap/)
$logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
But this set me that error
Call to undefined method Monolog\logger::useDailyFiles()
Any help I appreciate...Thanks
If you look at the framework source code here you can see that it will not do daily logs, but rather write to a single log file lumen.log. There is a public method available configureMonologUsing seen here and referenced here that you can use to override the default behavior without extending the Application.
Lumen just sets a handler to monolog, so another good solution is you could do this:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
class LogServiceProvider extends ServiceProvider
{
/**
* Configure logging on boot.
*
* #return void
*/
public function boot()
{
$maxFiles = 5;
$handlers[] = (new RotatingFileHandler(storage_path("logs/lumen.log"), $maxFiles))
->setFormatter(new LineFormatter(null, null, true, true));
$this->app['log']->setHandlers($handlers);
}
/**
* Register the log service.
*
* #return void
*/
public function register()
{
// Log binding already registered in vendor/laravel/lumen-framework/src/Application.php.
}
}
Then don't forget to add the service provider to your Lumen bootstrap/app.php:
$app->register(\App\Providers\LogServiceProvider::class);
In Lumen 5.6 better way is to configure your default setting in .env as LOG_CHANNEL=daily
By default the setting is LOG_CHANNEL=stack which use single file for logging.
Starting from version 5.6, configuring the logging system is much easier:
Create directory config in your project if it doesn't exist
Copy the logging config file from
vendor/laravel/lumen-framework/config/logging.php to your project config dir
Edit file config/logging.php and adjust the channels property to your liking.
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
],
Related
I want to add new custom service provider to set session_lifetime. The value for it, I got it from database. For do this thing I create service provider. But after the service provider registered. I got and error like this : Undefined index: path.
This is my new service provider code :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Config;
use Illuminate\Support\Facades\DB;
class ParameterSettingServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
}
/**
* Register services.
*
* #return void
*/
public function register()
{
if (\Schema::hasTable('parameter_settings')) {
$settings = DB::table('parameter_settings')->first();
if ($settings) //checking if table is not empty
{
$config = array(
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', $settings->session_expired),
'expire_on_close' => true,
);
Config::set('session', $config);
}
}
}
}
And this is my config/app.php to register the service provider :
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\ParameterSettingServiceProvider::class,
How to fix this error?
You should be using the boot method of the Service Provider not the register method. The boot method of the Provider will run after all other Service Provider's register methods have ran.
If you only want to set 1 single configuration value, you can do that. You don't need to overwrite the entire session config key (which holds 15 vars, check your config/session.php file). This is why you will keep getting errors about undefined indexes because these configuration variables need to exist.
The documentation's example for setting a config value at run time is how you set a single key by name (using the "dot" syntax):
Config::set('session.lifetime', $settings->session_expired);
Laravel 5.8 Docs - Configuration - Accessing Configuration Values
I have installed this github Laravel 5 Saml2 package:
https://github.com/aacotroneo/laravel-saml2
I've got the login working, authentication is happening and the data is being passed back correctly. I have a LoginListener that is successfully catching the correct user information and returning a valid user from the database. However when I attempt to use Auth::login it does not persist outside of the listener handle function and will go into an endless loop between the SAML authentication and the listener.
Here is my Listener:
namespace App\Listeners;
use \Aacotroneo\Saml2\Events\Saml2LoginEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Auth;
use Illuminate\Session\Middleware\StartSession;
use App\Http\Controllers\HomeController;
class LoginListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
}
/**
* Handle the event.
*
* #param Saml2LoginEvent $event
* #return void
*/
public function handle(Saml2LoginEvent $event)
{
$user = $event->getSaml2User();
$userData = [
'id' => $user->getUserId(),
'attributes' => $user->getAttributes(),
'assertion' => $user->getRawSamlAssertion()
];
//check if email already exists and fetch user
$user = \App\Models\User::where('username', $userData['attributes']['NameID'][0])->first();
Auth::guard('web')->login($user);
Session::save();
}
}
I have added 'web' to my routesMiddleware setting in the saml2-settings file as is suggested in multiple places with no effect. Does someone have a working example of this somewhere that I can dig through to see what I am doing wrong?
The solution to this turned out to be in the middleware. I have several custom middleware files setup and they were interferring with the web middleware begin the solution to the issue.
To solve this I created a custom middlewareGroup in the Kernel called listener and removed all of the extra middleware that I had added to web:
'listener' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
],
Then in the saml2_settings config file I changed the routesMiddleware variable to listener:
'routesMiddleware' => ['listener'],
Hopefully this helps someone else in the troubleshooting process.
I am using vinkla/hashids and i have followed the following steps
composer require vinkla/hashids
Add the service provider to config/app.php in the providers array
If you want you can use the facade. Add the reference in config/app.php to your aliases array.
php artisan vendor:publish this step does not create hashid.php in config file
use Vinkla\Hashids\Facades\Hashids;
Hashids::encode(4815162342);
And i get error that hashids class not found
It seems that the provider is not booting.
Try to do this:
php artisan config:clear
php artisan clear-compiled
The first will clear any cached config files, and the later will clear the services cache.
It worked for me, hope it works for you too.
I found the solution here: Laravel 5.2 Service provider not booting
Try checking inside your $laravelSite/config Directory to see if you find a file called hashids.php...
In your Controller; try also to import the the Hashids Class manually like so:
<?php
namespace App\Http\Controllers;
use Vinkla\Hashids\Facades\Hashids;
class SampleClass extends {
public function testHashID(){
$h1 = Hashids::encode(4815162342);
var_dump($h1);
$h2 = Hashids::decode('oaobgb-rnar');
var_dump($h2);
}
}
And by the way; if you don't see hashids.php within your $laravelSite/config Directory; you may try to manually create it. The file just returns an array of Configuration Settings... the content to the file looks like so:
/*
* This file is part of Laravel Hashids.
*
* (c) Vincent Klaiber <hello#vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| Hashids Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like.
|
*/
'connections' => [
'main' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
'alternative' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
],
];
To encode just do this
\Hashids::encode($characters)
And to decode
\Hashids::decode($characters)
I want to change the Laravel 5.1 storage path: something like /home/test/storage. This has the advantage that these files are not stored in the repository, which is fairly ugly I think.
In Laravel 4, this was very simple with bootstrap/paths.php.
In Laravel 5, it works by using $app->useStoragePath('/path/') in bootstrap/app.php. However, I want to define the storage path with a config option, like $app->useStoragePath(config('app.storage_path'). The config option calls an environment variable or returns a default location.
Doing this results in a Uncaught exception 'ReflectionException' with message 'Class config does not exist'; this makes sense, because this function is not loaded yet.
I tried setting the storage path just after booting:
$app->booted(function () use ($app) {
$app->useStoragePath(config('app.storage_root'));
});
This changed nothing. I also tried directly binding it to path.storage:
$app->bind('path.storage', function ($app) {
return config('app.storage_root');
});
The last option works partially; the view cache is now placed in the correct location, but the logs are still at the old location.
Set it up in .env
app.php
'app_storage' => env('APP_STORAGE', storage_path()),
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->useStoragePath(config('app.app_storage'));
}
.env
APP_STORAGE=custom_location
Laravel 5.3 is in bootstrap/app.php
/*
|--------------------------------------------------------------------------
| Set Storage Path
|--------------------------------------------------------------------------
|
| This script allows us to override the default storage location used by
| the application. You may set the APP_STORAGE environment variable
| in your .env file, if not set the default location will be used
|
*/
$app->useStoragePath( env( 'APP_STORAGE', base_path() . '/storage' ) );
Here is a simple solution of changing the storage path in Laravel 5 like we do in Laravel 4
on bootstrap/app.php
# new storage path
# base_path() -> returns root path
$path_storage = base_path() . "../../storage";
# override already $app->storagePath using the function
$app->useStoragePath($path_storage);
this will make the storage path to be same with the session, views, cache, logs
This works on Laravel 5.2
File: app/Providers/AppServiceProvider.php
public function register() {
...
$this->app->useStoragePath(config('what_ever_you_want'));
...
}
Calling useStoragePath on your AppServiceProvider wouldn't do the job properly because the AppServiceProvider is called after the config files are loaded. so any use of storage_path in config files would still refer to the old storage path.
In order to properly solve this problem I suggest you extend Application class and then on the constructor of your own class write the followings.
/**
* MyApplication constructor.
*/
public function __construct($basePath = null)
{
parent::__construct($basePath);
// set the storage path
$this->afterLoadingEnvironment(function () {
$this->useStoragePath(/*path to your storage directory*/);
});
}
if your website is hosted;
move everything from public folder to root folder
$app->bind('path.public', function() {
return __DIR__;
});
add this code in your bootstrap/app.php :
$app->useStoragePath(__DIR__ . '/../custom-path/');
and in config/filesystem.php :
'local' => [
'driver' => 'local',
'root' => storage_path('everything'), //custom-path/everything
],
'public' => [
'driver' => 'local',
'root' => storage_path(''),
'url' => env('APP_URL'),
'visibility' => 'public',
],
and then run php artisan config:cache
This works on Laravel 5.8 because you have to load the environment variables before you try to use them.
File: bootstrap/app.php
$app->afterLoadingEnvironment(function() use ($app) {
$app->useStoragePath(env('APP_STORAGE', storage_path()));
});
I try to send some emails with a CLI command with php artisan of Laravel, something easy like :
php artisan invitation:send recipient#mail.com
This command is calling a UserController method which contains :
Mail::send('emails.beta.invitation', $data, function($message) use ($address)
{
$message->to($address)
->subject('My subject');
});
The problem is that when it creates the HTML using the view, all references to URL::asset('img/foo.png') in the template gives me a beautiful :
http://localhost/img/foo.png
instead of the website url :
http://mydomain.com/img/foo.png
If I call this method by calling it in the web browser, there is the good URI for the asset.
I even tried with an environment to the CLI but it doesn't work. (ie. --env=production)
Where am I wrong ?
All right, I got it.
When using the CLI, Laravel is using the config file app/config/app.php to read the 'url' (default 'url' => 'http://localhost').
So I just had to create a new config file under app/config/local/app.php with :
<?php
return array(
'url' => 'http://localhost:8000',
);
And to change the app/config/app.php with my production value :
'url' => 'http://mydomain.com'
Now it works well !
https://github.com/laravel/framework/issues/2554#issuecomment-246645265
mstephens commented on 13 Sep 2016
Hello
In App\Providers\RouteServiceProvider you can define the following:
/**
* #inheritdoc
*/
public function boot()
{
parent::boot();
/** #var \Illuminate\Routing\UrlGenerator $url */
$url = $this->app['url'];
// Force the application URL
$url->forceRootUrl(config('app.url'));
}