How to print messages on console in Laravel? - php

How do laravel print out some string on console when running php artisan serve?
I tried Log::info but it isn't working.

It's very simple.
You can call it from anywhere in APP.
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");

Try with
error_log('message here.');
Read More
If You ant add LOG
Log::info('message');
If LOG with an array
Log::info(json_encode($array));
Import Illuminate\Support\Facades\Log;

Laravel 5.6 simplified this because you now have a logging.php config file you could leverage.
The key thing to know is that you want to output to stdout and php has a stream wrapper built-in called php://stdout. Given that, you could add channel for that wrapper. You would add the stdout "channel" to your channels that you will be logging to.
Here's how the config will basically look:
<?php
return [
'default' => env('LOG_CHANNEL', 'stack'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single','stdout'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'stdout' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'with' => [
'stream' => 'php://stdout',
],
],
];
I have more information here - Laravel 5.6 - Write to the Console

You've to config where laravel to store the logs. Default Log::info() put the log in the log file not the console. you can use tail -f logpath to see the log.

You can call info() method
$this->info("Your Message");

Related

Rollbar is not seen by Laravel 8.0

I have installed the Rollbar 7.0 into Laravel 8.0. PHP version is 7.4
I am trying to send a test exception message using a simple Console command but that sends me nothing.
My configs are the following:
config/app.php:
return [
'providers' => [
Rollbar\Laravel\RollbarServiceProvider::class
...
]
config/logging.php:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['other', 'rollbar'],
'ignore_exceptions' => false,
],
'rollbar' => [
'driver' => 'monolog',
'handler' => MonologHandler::class,
'access_token' => env('ROLLBAR_TOKEN'),
'level' => env('ROLLBAR_LEVEL'),
'enabled' => true,
'environment' => env('ROLLBAR_ENVIRONMENT'),
]
....
config/services.php (but seems to be that it doesn't work)
'rollbar' => [
'access_token' => env('ROLLBAR_TOKEN'),
'environment' => env('ROLLBAR_ENVIRONMENT'),
'level' => env('ROLLBAR_LEVEL')
],
app.env:
ROLLBAR_TOKEN=real_token
ROLLBAR_LEVEL=debug
ROLLBAR_ENVIRONMENT=backend_test
And the console command itself has the following view:
public function handle()
{
// Rollbar::init([
// 'driver' => 'monolog',
// 'handler' => MonologHandler::class,
// 'access_token' => env('ROLLBAR_TOKEN'),
// 'level' => env('ROLLBAR_LEVEL'),
// 'enabled' => true,
// 'environment' => env('ROLLBAR_ENVIRONMENT'),
// ]);
try{
$x = 4/0;
} catch(\Exception $exception) {
Rollbar::error('caught demo exception', ["details" => $exception->getMessage()]));
Rollbar::flush();
exit(1);
}
}
So when it is like this, the rollbar stays silent. But if I uncomment the initialisation, that works well, sending a debug message to the rollbar.
That doesn't work all over the project too.
Could you please advice me, what could I do here in order to make it work globally with initialising in every file?
upd: I've also cleared config cache and tried to make a rollbar as a default
Laravel in app/logging.php has a default channel configuration. Normally "default" should mean that there are some other working channel too but here, somehow it the meaning is like "the only used channel". Or I just do not fully understand how should it work. So my rollbar channel seems to be overriden by the another "default" one, that is why the system doesn't use it. So the solution is to switch the default channel:
'default' => env('LOG_CHANNEL', 'stack'),
when the rollbar is included to stack channel or just
'default' => env('LOG_CHANNEL', 'rollbar'),
when it is not.

Getting a list of all text that needs to be translated using Yii2 DbMessageSource

I am using Yii2 to work on a project that needs to be translated into various languages. I am using the advanced template and set up my common/main.php like so
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'language' => 'en',
'sourceLanguage' => 'en',
'components' => [
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\DbMessageSource',
'sourceLanguage' => 'en',
],
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'as beforeRequest' => [
'class' => 'common\components\CheckLanguage',
],
];
I have added the required database tables source_message and message. Now each text in the website that I need to have translated I use the Yii::t($category,$message) function.
My question is; How can I get a list of all text in my website that needs to be translated into the database? Do I have to manually scan my site for all Yii::t($category,$message) function calls?
Thanks in advance for your time and input
There is console command provided for this scan functionality.
./yii message
See the documentation in the Guide.
Generate configuration file for the scanner:
./yii message/config-template your/path/to/saving/config.php
Adjust the newly created config.php to your needs.
Run the command:
./yii message path/to/config.php

Laravel log file based on date

By default laravel saves the log file to a single log file called laravel.log located in /storage/logs/laravel.log
my question is how can i get a new log file everyday and store the log files like /storage/logs/laravel-2016-02-23.log for the current date, so i need everyday a new log file saved to /storage/logs/
i think we can do that by extending the default Illuminate\Foundation\Bootstrap\ConfigureLogging bootstraper class but i'm not sure how i can do that
i would really appreciate it if anyone could help me.
Thanks in advance.
In the version of Laravel 5.6 that I am using, the configuration file for logging is config/logging.php
There you will find the following section
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
],
...
]
Change the line
'channels' => ['single'],
into
'channels' => ['daily'],
Then it will be like:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
],
...
]
It will create log files for each day in the format laravel-2018-08-13.log in the logs directory.
The log directory will be like
Previously
After applying rotation configuration the directory is having the log file created for the current date (as circled one which is created for today 2018-08-13).
It's actually a lot simpler than that. In your config/app.php you'll see the line:
'log' => 'single',
closer to the bottom of the file. Laravel by default uses the single method, which stores all errors in a single, expanding file. If you change this line to:
'log' => 'daily',
it will tell Laravel that you'd prefer to have multiple logs, each suffixed with the date of the when the error occurs.
There's a few other methods available, so be sure to check out the official documentation for more info.
This answer is for Laravel 5.2, which is the version specified in the original question. In never versions of Laravel, the Logging config has been moved to it's own config file, as seen by #ShanthaKumara's answer (https://stackoverflow.com/a/51816907/3965631). Please do not suggest edits to change this answer to reflect the new version.
just open .env file and change
LOG_CHANNEL=stack
to
LOG_CHANNEL=daily
then run the command
php artisan config:cache
now i think your problem will solve.
The laravel on daily logging is fine, but on 1st year, you will have 365 files of laravel.log. My approach is to do the following on the 'path' of the 'single' channel.
storage_path('logs/' . date("Y") . '/' . date("m") . '/' . date("d") . '/' . 'laravel.log')
This way you have organize the logs by each year/month/day.
2021/
06/
01/
laravel.log
To generate a new file for everyday in Laravel, all you need to do is change 'channels' value in the \config\logging.php file from 'single' to 'daily'.
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
],

Controller mapping causing error in yii2 console application

Module section config
'user' => [
'class' => 'dektrium\user\Module',
'modelMap' => [
'User' => 'app\models\DL\User',
'registrationForm' => 'app\models\DL\registrationForm',
],
'controllerMap' => [
/*'registration' => 'app\controllers\user\RegistrationController',
'admin' => 'app\controllers\user\AdminController'*/
],
'layout' => '#app/views/layouts/container',
'defaultRoute' => 'profile',
'admins' => ['admin'],
'enableFlashMessages' => false,
'params' => [
'menuItems' => [
'label' => 'Users',
'url' => ['/user/admin']
]
]
],
Yii console application (./yii) showing me error
'Calling unknown method:
app\controllers\user\AdminController::getHelpSummary()'
If I uncomment the controllerMap section, I can't understand why it autoloads in console app if my AdminController extends web controller not console.
This is commands from user module.
Do you really need the user module in console?
Yii2 console and web applications have separated configuration files by default. If you changed this default and use the same config for both of them, you must take care about consistency.
You can check the list of loaded configs in ./yii.
You need to specify a valid defaultRoute for the console application.
With 'defaultRoute' => 'profile', ./yiimay try to load a Controller which requires the user module.
Try adding it in the console configuration.

How can I access CakePHP log files on Heroku?

I've deployed a CakePHP application to Heroku. CakePHP writes its logs in APP_ROOT/app/tmp/logs/error.log and APP_ROOT/app/tmp/logs/debug.log by default but since there's no way to get a shell to a running Heroku web dyno, I can't see the content of those files.
As I understand it, the heroku logs command returns everything which has been dumped to STDERR and STDOUT. If I'm right about that, is there a way to force CakePHP to send its logs to STDOUT?
The Heroku PHP Buildpack tails the Apache and PHP log files as a background process as part of the dyno setup. See below.
cat >>boot.sh <<EOF
for var in \`env|cut -f1 -d=\`; do
echo "PassEnv \$var" >> /app/apache/conf/httpd.conf;
done
touch /app/apache/logs/error_log
touch /app/apache/logs/access_log
tail -F /app/apache/logs/error_log &
tail -F /app/apache/logs/access_log &
export LD_LIBRARY_PATH=/app/php/ext
export PHP_INI_SCAN_DIR=/app/www
echo "Launching apache"
exec /app/apache/bin/httpd -DNO_DETACH
EOF
In a fork of that build pack, I added in my own lines in the appropriate positions, then configured my app to use my custom build pack.
touch /app/www/tmp/logs/error.log
tail -F /app/www/app/tmp/logs/error.log &
But this didn't work. In fact, setting aside CakePHP specifics, I don't see any PHP or Apache log contents in the heroku logs either.
I think the following might work. Make sure you're using CakePHP 2.3.9.
App::uses('ConsoleOutput', 'Console');
CakeLog::config('default', array(
'engine' => 'ConsoleLog',
'stream' => new ConsoleOutput('php://stdout')
));
CakeLog::config('stdout', array(
'engine' => 'ConsoleLog',
'types' => array('notice', 'info'),
'stream' => new ConsoleOutput('php://stdout')
));
CakeLog::config('stderr', array(
'engine' => 'ConsoleLog',
'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'),
'stream' => new ConsoleOutput('php://stderr')
));
CakeLog::config('debug', array(
'engine' => 'ConsoleLog',
'types' => array('notice', 'info', 'debug'),
'format' => 'debug %s: %s',
'stream' => new ConsoleOutput('php://stdout')
));
CakeLog::config('error', array(
'engine' => 'ConsoleLog',
'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
'format' => 'error %s: %s',
'stream' => new ConsoleOutput('php://stderr')
));
From the Heroku documentation: https://devcenter.heroku.com/articles/php-logging#cakephp
In your application configuration, instruct CakePHP to use the ConsoleLog engine for your logger setups:
CakeLog::config('default', array(
'engine' => 'ConsoleLog',
));
You can then use the regular logging methods.
CakeLog::warning("Hello, this is a test message!");
Refer to the Logging section of the CakePHP manual for more information.
In the latest versions of CakePHP (>= 3.6.0), the config/app.php file comes pre-configured to use an environment variable override for the stock debug and error logs. These vars should contain a DSN-style string defining the same attributes you would normally place in your config/app.php file.
In the Heroku dashboard under Settings (or via the heroku cli tool), you can add the following ENV vars:
LOG_DEBUG_URL = file:///?className=Cake%5CLog%5CEngine%5CConsoleLog&levels[]=notice&levels[]=info&levels[]=debug
LOG_ERROR_URL = file:///?className=Cake%5CLog%5CEngine%5CConsoleLog&levels[]=warning&levels[]=error&levels[]=critical&levels[]=alert&levels[]=emergency
The above two lines replicate the stock CakePHP logging, but redirect all output to the console instead of files.
you can use: 'className' => 'Cake\Log\Engine\ConsoleLog'
/**
* Configures logging options
*/
'Log' => [
'debug' => [
'className' => 'Cake\Log\Engine\ConsoleLog',
'path' => LOGS,
'file' => 'debug',
'levels' => ['notice', 'info', 'debug'],
'url' => env('LOG_DEBUG_URL', null),
],
'error' => [
'className' => 'Cake\Log\Engine\ConsoleLog',
'path' => LOGS,
'file' => 'error',
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
'url' => env('LOG_ERROR_URL', null),
],
],

Categories